blob: 1b2bb60ed55b9ea488ada1ba3c768583acb22e10 [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"
David Blaikie2be39222018-03-21 22:34:23 +000033#include "llvm/Analysis/Utils/Local.h"
Sanjay Patel69a50a12015-10-19 21:59:12 +000034#include "llvm/Analysis/ValueTracking.h"
Michael Kupersteinf79af6f2016-09-08 00:48:37 +000035#include "llvm/CodeGen/Analysis.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000036#include "llvm/CodeGen/ISDOpcodes.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000037#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"
Craig Topper2fa14362018-03-29 17:21:10 +000041#include "llvm/CodeGen/ValueTypes.h"
Nico Weber432a3882018-04-30 14:59:11 +000042#include "llvm/Config/llvm-config.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000043#include "llvm/IR/Argument.h"
44#include "llvm/IR/Attributes.h"
45#include "llvm/IR/BasicBlock.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000046#include "llvm/IR/CallSite.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000047#include "llvm/IR/Constant.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000048#include "llvm/IR/Constants.h"
49#include "llvm/IR/DataLayout.h"
50#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000051#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000052#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000053#include "llvm/IR/GetElementPtrTypeIterator.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000054#include "llvm/IR/GlobalValue.h"
55#include "llvm/IR/GlobalVariable.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000056#include "llvm/IR/IRBuilder.h"
57#include "llvm/IR/InlineAsm.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000058#include "llvm/IR/InstrTypes.h"
59#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000060#include "llvm/IR/Instructions.h"
61#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000062#include "llvm/IR/Intrinsics.h"
63#include "llvm/IR/LLVMContext.h"
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +000064#include "llvm/IR/MDBuilder.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000065#include "llvm/IR/Module.h"
66#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000067#include "llvm/IR/PatternMatch.h"
Ramkumar Ramachandradba73292015-01-14 23:27:07 +000068#include "llvm/IR/Statepoint.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000069#include "llvm/IR/Type.h"
70#include "llvm/IR/Use.h"
71#include "llvm/IR/User.h"
72#include "llvm/IR/Value.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000073#include "llvm/IR/ValueHandle.h"
Chandler Carrutha4ea2692014-03-04 11:26:31 +000074#include "llvm/IR/ValueMap.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000075#include "llvm/Pass.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000076#include "llvm/Support/BlockFrequency.h"
Sanjay Pateld66607b2016-04-26 17:11:17 +000077#include "llvm/Support/BranchProbability.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000078#include "llvm/Support/Casting.h"
Evan Cheng8b637b12010-08-17 01:34:49 +000079#include "llvm/Support/CommandLine.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000080#include "llvm/Support/Compiler.h"
Evan Chengd3d80172007-12-05 23:58:20 +000081#include "llvm/Support/Debug.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000082#include "llvm/Support/ErrorHandling.h"
David Blaikie13e77db2018-03-23 23:58:25 +000083#include "llvm/Support/MachineValueType.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000084#include "llvm/Support/MathExtras.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000085#include "llvm/Support/raw_ostream.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000086#include "llvm/Target/TargetMachine.h"
87#include "llvm/Target/TargetOptions.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000088#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Preston Gurdcdf540d2012-09-04 18:22:17 +000089#include "llvm/Transforms/Utils/BypassSlowDivision.h"
Ahmed Bougachae03bef72015-01-12 17:22:43 +000090#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000091#include <algorithm>
92#include <cassert>
93#include <cstdint>
94#include <iterator>
95#include <limits>
96#include <memory>
97#include <utility>
98#include <vector>
Zaara Syeda3a7578c2017-05-31 17:12:38 +000099
Chris Lattnerf2836d12007-03-31 04:06:36 +0000100using namespace llvm;
Chris Lattnerd616ef52008-11-25 04:42:10 +0000101using namespace llvm::PatternMatch;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000102
Chandler Carruth1b9dde02014-04-22 02:02:50 +0000103#define DEBUG_TYPE "codegenprepare"
104
Cameron Zwarichced753f2011-01-05 17:27:27 +0000105STATISTIC(NumBlocksElim, "Number of blocks eliminated");
Evan Cheng0663f232011-03-21 01:19:09 +0000106STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
107STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
Cameron Zwarichced753f2011-01-05 17:27:27 +0000108STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
109 "sunken Cmps");
110STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
111 "of sunken Casts");
112STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
113 "computations were sunk");
Serguei Katkovd5d8d542017-11-05 05:50:33 +0000114STATISTIC(NumMemoryInstsPhiCreated,
115 "Number of phis created when address "
116 "computations were sunk to memory instructions");
117STATISTIC(NumMemoryInstsSelectCreated,
118 "Number of select created when address "
119 "computations were sunk to memory instructions");
Evan Cheng0663f232011-03-21 01:19:09 +0000120STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
121STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
Geoff Berry5256fca2015-11-20 22:34:39 +0000122STATISTIC(NumAndsAdded,
123 "Number of and mask instructions added to form ext loads");
124STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized");
Evan Cheng0663f232011-03-21 01:19:09 +0000125STATISTIC(NumRetsDup, "Number of return instructions duplicated");
Devang Patel53771ba2011-08-18 00:50:51 +0000126STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000127STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
Quentin Colombetc32615d2014-10-31 17:52:53 +0000128STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
Jakob Stoklund Oleseneb12f492010-09-30 20:51:52 +0000129
Cameron Zwarich338d3622011-03-11 21:52:04 +0000130static cl::opt<bool> DisableBranchOpts(
131 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
132 cl::desc("Disable branch optimizations in CodeGenPrepare"));
133
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000134static cl::opt<bool>
135 DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
136 cl::desc("Disable GC optimizations in CodeGenPrepare"));
137
Benjamin Kramer3d38c172012-05-06 14:25:16 +0000138static cl::opt<bool> DisableSelectToBranch(
139 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
140 cl::desc("Disable select to branch conversion."));
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000141
Hal Finkelc3998302014-04-12 00:59:48 +0000142static cl::opt<bool> AddrSinkUsingGEPs(
Eli Friedman5fba1e52017-04-06 22:42:18 +0000143 "addr-sink-using-gep", cl::Hidden, cl::init(true),
Hal Finkelc3998302014-04-12 00:59:48 +0000144 cl::desc("Address sinking in CGP using GEPs."));
145
Tim Northovercea0abb2014-03-29 08:22:29 +0000146static cl::opt<bool> EnableAndCmpSinking(
147 "enable-andcmp-sinking", cl::Hidden, cl::init(true),
148 cl::desc("Enable sinkinig and/cmp into branches."));
149
Quentin Colombetc32615d2014-10-31 17:52:53 +0000150static cl::opt<bool> DisableStoreExtract(
151 "disable-cgp-store-extract", cl::Hidden, cl::init(false),
152 cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
153
154static cl::opt<bool> StressStoreExtract(
155 "stress-cgp-store-extract", cl::Hidden, cl::init(false),
156 cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
157
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000158static cl::opt<bool> DisableExtLdPromotion(
159 "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
160 cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
161 "CodeGenPrepare"));
162
163static cl::opt<bool> StressExtLdPromotion(
164 "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
165 cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
166 "optimization in CodeGenPrepare"));
167
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000168static cl::opt<bool> DisablePreheaderProtect(
169 "disable-preheader-prot", cl::Hidden, cl::init(false),
170 cl::desc("Disable protection against removing loop preheaders"));
171
Dehao Chen302b69c2016-10-18 20:42:47 +0000172static cl::opt<bool> ProfileGuidedSectionPrefix(
David Callahan5960d9b12017-06-14 20:35:33 +0000173 "profile-guided-section-prefix", cl::Hidden, cl::init(true), cl::ZeroOrMore,
Dehao Chen302b69c2016-10-18 20:42:47 +0000174 cl::desc("Use profile info to add section prefix for hot/cold functions"));
175
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000176static cl::opt<unsigned> FreqRatioToSkipMerge(
177 "cgp-freq-ratio-to-skip-merge", cl::Hidden, cl::init(2),
178 cl::desc("Skip merging empty blocks if (frequency of empty block) / "
179 "(frequency of destination block) is greater than this ratio"));
180
Wei Mia2f0b592016-12-22 19:44:45 +0000181static cl::opt<bool> ForceSplitStore(
182 "force-split-store", cl::Hidden, cl::init(false),
183 cl::desc("Force store splitting no matter what the target query says."));
184
Jun Bum Limdee55652017-04-03 19:20:07 +0000185static cl::opt<bool>
186EnableTypePromotionMerge("cgp-type-promotion-merge", cl::Hidden,
187 cl::desc("Enable merging of redundant sexts when one is dominating"
188 " the other."), cl::init(true));
189
Serguei Katkovd5d8d542017-11-05 05:50:33 +0000190static cl::opt<bool> DisableComplexAddrModes(
Serguei Katkovd4df7442017-11-29 09:48:50 +0000191 "disable-complex-addr-modes", cl::Hidden, cl::init(false),
Serguei Katkovd5d8d542017-11-05 05:50:33 +0000192 cl::desc("Disables combining addressing modes with different parts "
193 "in optimizeMemoryInst."));
194
195static cl::opt<bool>
196AddrSinkNewPhis("addr-sink-new-phis", cl::Hidden, cl::init(false),
197 cl::desc("Allow creation of Phis in Address sinking."));
198
199static cl::opt<bool>
Serguei Katkov9fe05242018-01-26 06:26:56 +0000200AddrSinkNewSelects("addr-sink-new-select", cl::Hidden, cl::init(true),
Serguei Katkovd5d8d542017-11-05 05:50:33 +0000201 cl::desc("Allow creation of selects in Address sinking."));
202
John Brawn70cdb5b2017-11-24 14:10:45 +0000203static cl::opt<bool> AddrSinkCombineBaseReg(
204 "addr-sink-combine-base-reg", cl::Hidden, cl::init(true),
205 cl::desc("Allow combining of BaseReg field in Address sinking."));
206
207static cl::opt<bool> AddrSinkCombineBaseGV(
208 "addr-sink-combine-base-gv", cl::Hidden, cl::init(true),
209 cl::desc("Allow combining of BaseGV field in Address sinking."));
210
211static cl::opt<bool> AddrSinkCombineBaseOffs(
212 "addr-sink-combine-base-offs", cl::Hidden, cl::init(true),
213 cl::desc("Allow combining of BaseOffs field in Address sinking."));
214
215static cl::opt<bool> AddrSinkCombineScaledReg(
216 "addr-sink-combine-scaled-reg", cl::Hidden, cl::init(true),
217 cl::desc("Allow combining of ScaledReg field in Address sinking."));
218
Eric Christopherc1ea1492008-09-24 05:32:41 +0000219namespace {
Eugene Zelenko900b6332017-08-29 22:32:07 +0000220
221using SetOfInstrs = SmallPtrSet<Instruction *, 16>;
222using TypeIsSExt = PointerIntPair<Type *, 1, bool>;
223using InstrToOrigTy = DenseMap<Instruction *, TypeIsSExt>;
224using SExts = SmallVector<Instruction *, 16>;
225using ValueToSExts = DenseMap<Value *, SExts>;
226
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000227class TypePromotionTransaction;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000228
Chris Lattner2dd09db2009-09-02 06:11:42 +0000229 class CodeGenPrepare : public FunctionPass {
Eugene Zelenko900b6332017-08-29 22:32:07 +0000230 const TargetMachine *TM = nullptr;
Igor Laevsky3be81ba2017-02-07 13:27:20 +0000231 const TargetSubtargetInfo *SubtargetInfo;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000232 const TargetLowering *TLI = nullptr;
Igor Laevsky3be81ba2017-02-07 13:27:20 +0000233 const TargetRegisterInfo *TRI;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000234 const TargetTransformInfo *TTI = nullptr;
Chad Rosierc24b86f2011-12-01 03:08:23 +0000235 const TargetLibraryInfo *TLInfo;
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000236 const LoopInfo *LI;
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000237 std::unique_ptr<BlockFrequencyInfo> BFI;
238 std::unique_ptr<BranchProbabilityInfo> BPI;
Nadav Rotem465834c2012-07-24 10:51:42 +0000239
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000240 /// As we scan instructions optimizing them, this is the next instruction
241 /// to optimize. Transforms that can invalidate this should update it.
Chris Lattner7a277142011-01-15 07:14:54 +0000242 BasicBlock::iterator CurInstIterator;
Evan Cheng3b3de7c2008-12-19 18:03:11 +0000243
Evan Cheng0663f232011-03-21 01:19:09 +0000244 /// Keeps track of non-local addresses that have been sunk into a block.
245 /// This allows us to avoid inserting duplicate code for blocks with
Simon Dardis230f4532017-11-24 16:45:28 +0000246 /// multiple load/stores of the same address. The usage of WeakTrackingVH
247 /// enables SunkAddrs to be treated as a cache whose entries can be
248 /// invalidated if a sunken address computation has been erased.
249 ValueMap<Value*, WeakTrackingVH> SunkAddrs;
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000250
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000251 /// Keeps track of all instructions inserted for the current function.
252 SetOfInstrs InsertedInsts;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000253
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000254 /// Keeps track of the type of the related instruction before their
255 /// promotion for the current function.
256 InstrToOrigTy PromotedInsts;
257
Jun Bum Limdee55652017-04-03 19:20:07 +0000258 /// Keep track of instructions removed during promotion.
259 SetOfInstrs RemovedInsts;
260
261 /// Keep track of sext chains based on their initial value.
262 DenseMap<Value *, Instruction *> SeenChainsForSExt;
263
264 /// Keep track of SExt promoted.
265 ValueToSExts ValToSExtendedUses;
266
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000267 /// True if CFG is modified in any way.
Devang Patel8f606d72011-03-24 15:35:25 +0000268 bool ModifiedDT;
Evan Cheng0663f232011-03-21 01:19:09 +0000269
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000270 /// True if optimizing for size.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000271 bool OptSize;
272
Mehdi Amini4fe37982015-07-07 18:45:17 +0000273 /// DataLayout for the Function being processed.
Eugene Zelenko900b6332017-08-29 22:32:07 +0000274 const DataLayout *DL = nullptr;
Mehdi Amini4fe37982015-07-07 18:45:17 +0000275
Chris Lattnerf2836d12007-03-31 04:06:36 +0000276 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +0000277 static char ID; // Pass identification, replacement for typeid
Eugene Zelenko900b6332017-08-29 22:32:07 +0000278
279 CodeGenPrepare() : FunctionPass(ID) {
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000280 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
281 }
Eugene Zelenko900b6332017-08-29 22:32:07 +0000282
Craig Topper4584cd52014-03-07 09:26:03 +0000283 bool runOnFunction(Function &F) override;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000284
Mehdi Amini117296c2016-10-01 02:56:57 +0000285 StringRef getPassName() const override { return "CodeGen Prepare"; }
Evan Cheng99cafb12012-12-21 01:48:14 +0000286
Craig Topper4584cd52014-03-07 09:26:03 +0000287 void getAnalysisUsage(AnalysisUsage &AU) const override {
George Burgess IVd4febd12016-03-22 21:25:08 +0000288 // FIXME: When we can selectively preserve passes, preserve the domtree.
Dehao Chen302b69c2016-10-18 20:42:47 +0000289 AU.addRequired<ProfileSummaryInfoWrapperPass>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000290 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000291 AU.addRequired<TargetTransformInfoWrapperPass>();
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000292 AU.addRequired<LoopInfoWrapperPass>();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000293 }
294
Chris Lattnerf2836d12007-03-31 04:06:36 +0000295 private:
Sanjay Patelfc580a62015-09-21 23:03:16 +0000296 bool eliminateFallThrough(Function &F);
297 bool eliminateMostlyEmptyBlocks(Function &F);
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000298 BasicBlock *findDestBlockOfMergeableEmptyBlock(BasicBlock *BB);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000299 bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
300 void eliminateMostlyEmptyBlock(BasicBlock *BB);
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000301 bool isMergingEmptyBlockProfitable(BasicBlock *BB, BasicBlock *DestBB,
302 bool isPreheader);
Sanjay Patel3b8974b2017-06-08 20:00:09 +0000303 bool optimizeBlock(BasicBlock &BB, bool &ModifiedDT);
304 bool optimizeInst(Instruction *I, bool &ModifiedDT);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000305 bool optimizeMemoryInst(Instruction *I, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +0000306 Type *AccessTy, unsigned AS);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000307 bool optimizeInlineAsmInst(CallInst *CS);
Sanjay Patel3b8974b2017-06-08 20:00:09 +0000308 bool optimizeCallInst(CallInst *CI, bool &ModifiedDT);
Jun Bum Limdee55652017-04-03 19:20:07 +0000309 bool optimizeExt(Instruction *&I);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000310 bool optimizeExtUses(Instruction *I);
Geoff Berry5256fca2015-11-20 22:34:39 +0000311 bool optimizeLoadExt(LoadInst *I);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000312 bool optimizeSelectInst(SelectInst *SI);
313 bool optimizeShuffleVectorInst(ShuffleVectorInst *SI);
Sanjay Patel0ed9aea2015-11-02 23:22:49 +0000314 bool optimizeSwitchInst(SwitchInst *CI);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000315 bool optimizeExtractElementInst(Instruction *Inst);
316 bool dupRetToEnableTailCallOpts(BasicBlock *BB);
317 bool placeDbgValues(Function &F);
Jun Bum Lim42301012017-03-17 19:05:21 +0000318 bool canFormExtLd(const SmallVectorImpl<Instruction *> &MovedExts,
319 LoadInst *&LI, Instruction *&Inst, bool HasPromoted);
320 bool tryToPromoteExts(TypePromotionTransaction &TPT,
321 const SmallVectorImpl<Instruction *> &Exts,
322 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
323 unsigned CreatedInstsCost = 0);
Jun Bum Limdee55652017-04-03 19:20:07 +0000324 bool mergeSExts(Function &F);
325 bool performAddressTypePromotion(
326 Instruction *&Inst,
327 bool AllowPromotionWithoutCommonHeader,
328 bool HasPromoted, TypePromotionTransaction &TPT,
329 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000330 bool splitBranchCondition(Function &F);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000331 bool simplifyOffsetableRelocate(Instruction &I);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000332 };
Eugene Zelenko900b6332017-08-29 22:32:07 +0000333
334} // end anonymous namespace
Devang Patel09f162c2007-05-01 21:15:47 +0000335
Devang Patel8c78a0b2007-05-03 01:11:54 +0000336char CodeGenPrepare::ID = 0;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000337
Matthias Braun1527baa2017-05-25 21:26:32 +0000338INITIALIZE_PASS_BEGIN(CodeGenPrepare, DEBUG_TYPE,
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000339 "Optimize for code generation", false, false)
Dehao Chen302b69c2016-10-18 20:42:47 +0000340INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
Matthias Braun1527baa2017-05-25 21:26:32 +0000341INITIALIZE_PASS_END(CodeGenPrepare, DEBUG_TYPE,
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000342 "Optimize for code generation", false, false)
Chris Lattnerf2836d12007-03-31 04:06:36 +0000343
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000344FunctionPass *llvm::createCodeGenPreparePass() { return new CodeGenPrepare(); }
Chris Lattnerf2836d12007-03-31 04:06:36 +0000345
Chris Lattnerf2836d12007-03-31 04:06:36 +0000346bool CodeGenPrepare::runOnFunction(Function &F) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000347 if (skipFunction(F))
Paul Robinson7c99ec52014-03-31 17:43:35 +0000348 return false;
349
Mehdi Amini4fe37982015-07-07 18:45:17 +0000350 DL = &F.getParent()->getDataLayout();
351
Chris Lattnerf2836d12007-03-31 04:06:36 +0000352 bool EverMadeChange = false;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000353 // Clear per function information.
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000354 InsertedInsts.clear();
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000355 PromotedInsts.clear();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000356
Devang Patel8f606d72011-03-24 15:35:25 +0000357 ModifiedDT = false;
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000358 if (auto *TPC = getAnalysisIfAvailable<TargetPassConfig>()) {
359 TM = &TPC->getTM<TargetMachine>();
Igor Laevsky3be81ba2017-02-07 13:27:20 +0000360 SubtargetInfo = TM->getSubtargetImpl(F);
361 TLI = SubtargetInfo->getTargetLowering();
362 TRI = SubtargetInfo->getRegisterInfo();
363 }
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000364 TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000365 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000366 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Teresa Johnsona4ce3bf2017-12-20 17:53:10 +0000367 BPI.reset(new BranchProbabilityInfo(F, *LI));
368 BFI.reset(new BlockFrequencyInfo(F, *BPI, *LI));
Sanjay Patel82d91dd2015-08-11 19:39:36 +0000369 OptSize = F.optForSize();
Evan Cheng0663f232011-03-21 01:19:09 +0000370
Easwaran Raman0d55b552017-11-14 19:31:51 +0000371 ProfileSummaryInfo *PSI =
372 getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
Dehao Chen302b69c2016-10-18 20:42:47 +0000373 if (ProfileGuidedSectionPrefix) {
Teresa Johnsona4ce3bf2017-12-20 17:53:10 +0000374 if (PSI->isFunctionHotInCallGraph(&F, *BFI))
Dehao Chen302b69c2016-10-18 20:42:47 +0000375 F.setSectionPrefix(".hot");
Teresa Johnsona4ce3bf2017-12-20 17:53:10 +0000376 else if (PSI->isFunctionColdInCallGraph(&F, *BFI))
Teresa Johnson720d9b42017-05-09 01:43:24 +0000377 F.setSectionPrefix(".unlikely");
Dehao Chen302b69c2016-10-18 20:42:47 +0000378 }
379
Preston Gurdcdf540d2012-09-04 18:22:17 +0000380 /// This optimization identifies DIV instructions that can be
381 /// profitably bypassed and carried out with a shorter, faster divide.
Easwaran Raman0d55b552017-11-14 19:31:51 +0000382 if (!OptSize && !PSI->hasHugeWorkingSetSize() && TLI &&
383 TLI->isSlowDivBypassed()) {
Preston Gurd0d67f512012-10-04 21:33:40 +0000384 const DenseMap<unsigned int, unsigned int> &BypassWidths =
385 TLI->getBypassSlowDivWidths();
Eric Christopher49a7d6c2016-01-04 23:18:58 +0000386 BasicBlock* BB = &*F.begin();
387 while (BB != nullptr) {
388 // bypassSlowDivision may create new BBs, but we don't want to reapply the
389 // optimization to those blocks.
390 BasicBlock* Next = BB->getNextNode();
391 EverMadeChange |= bypassSlowDivision(BB, BypassWidths);
392 BB = Next;
393 }
Preston Gurdcdf540d2012-09-04 18:22:17 +0000394 }
395
396 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerc3748562007-04-02 01:35:34 +0000397 // unconditional branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000398 EverMadeChange |= eliminateMostlyEmptyBlocks(F);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000399
Devang Patel53771ba2011-08-18 00:50:51 +0000400 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +0000401 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +0000402 // find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000403 EverMadeChange |= placeDbgValues(F);
Devang Patel53771ba2011-08-18 00:50:51 +0000404
Geoff Berry5d534b62017-02-21 18:53:14 +0000405 if (!DisableBranchOpts)
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000406 EverMadeChange |= splitBranchCondition(F);
Tim Northovercea0abb2014-03-29 08:22:29 +0000407
Michael Kuperstein13bf8a22017-02-28 00:11:34 +0000408 // Split some critical edges where one of the sources is an indirect branch,
409 // to help generate sane code for PHIs involving such edges.
Hiroshi Yamauchi9364fa32017-12-04 20:36:01 +0000410 EverMadeChange |= SplitIndirectBrCriticalEdges(F);
Michael Kuperstein13bf8a22017-02-28 00:11:34 +0000411
Chris Lattnerc3748562007-04-02 01:35:34 +0000412 bool MadeChange = true;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000413 while (MadeChange) {
414 MadeChange = false;
Jun Bum Limdee55652017-04-03 19:20:07 +0000415 SeenChainsForSExt.clear();
416 ValToSExtendedUses.clear();
417 RemovedInsts.clear();
Hans Wennborg02fbc712012-09-19 07:48:16 +0000418 for (Function::iterator I = F.begin(); I != F.end(); ) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000419 BasicBlock *BB = &*I++;
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000420 bool ModifiedDTOnIteration = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +0000421 MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000422
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000423 // Restart BB iteration if the dominator tree of the Function was changed
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000424 if (ModifiedDTOnIteration)
425 break;
Evan Cheng0663f232011-03-21 01:19:09 +0000426 }
Jun Bum Limdee55652017-04-03 19:20:07 +0000427 if (EnableTypePromotionMerge && !ValToSExtendedUses.empty())
428 MadeChange |= mergeSExts(F);
429
430 // Really free removed instructions during promotion.
431 for (Instruction *I : RemovedInsts)
Reid Kleckner96ab8722017-05-18 17:24:10 +0000432 I->deleteValue();
Jun Bum Limdee55652017-04-03 19:20:07 +0000433
Chris Lattnerf2836d12007-03-31 04:06:36 +0000434 EverMadeChange |= MadeChange;
435 }
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000436
437 SunkAddrs.clear();
438
Cameron Zwarich338d3622011-03-11 21:52:04 +0000439 if (!DisableBranchOpts) {
440 MadeChange = false;
Bill Wendling97b93592012-03-04 10:46:01 +0000441 SmallPtrSet<BasicBlock*, 8> WorkList;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +0000442 for (BasicBlock &BB : F) {
443 SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
444 MadeChange |= ConstantFoldTerminator(&BB, true);
Bill Wendling97b93592012-03-04 10:46:01 +0000445 if (!MadeChange) continue;
446
447 for (SmallVectorImpl<BasicBlock*>::iterator
448 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
449 if (pred_begin(*II) == pred_end(*II))
450 WorkList.insert(*II);
451 }
452
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000453 // Delete the dead blocks and any of their dead successors.
Bill Wendlingab417b62012-12-06 00:30:20 +0000454 MadeChange |= !WorkList.empty();
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000455 while (!WorkList.empty()) {
456 BasicBlock *BB = *WorkList.begin();
457 WorkList.erase(BB);
458 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
459
460 DeleteDeadBlock(BB);
Stephen Lin837bba12013-07-15 17:55:02 +0000461
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000462 for (SmallVectorImpl<BasicBlock*>::iterator
463 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
464 if (pred_begin(*II) == pred_end(*II))
465 WorkList.insert(*II);
466 }
Cameron Zwarich338d3622011-03-11 21:52:04 +0000467
Nadav Rotem70409992012-08-14 05:19:07 +0000468 // Merge pairs of basic blocks with unconditional branches, connected by
469 // a single edge.
470 if (EverMadeChange || MadeChange)
Sanjay Patelfc580a62015-09-21 23:03:16 +0000471 MadeChange |= eliminateFallThrough(F);
Nadav Rotem70409992012-08-14 05:19:07 +0000472
Cameron Zwarich338d3622011-03-11 21:52:04 +0000473 EverMadeChange |= MadeChange;
474 }
475
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000476 if (!DisableGCOpts) {
477 SmallVector<Instruction *, 2> Statepoints;
478 for (BasicBlock &BB : F)
479 for (Instruction &I : BB)
480 if (isStatepoint(I))
481 Statepoints.push_back(&I);
482 for (auto &I : Statepoints)
483 EverMadeChange |= simplifyOffsetableRelocate(*I);
484 }
485
Chris Lattnerf2836d12007-03-31 04:06:36 +0000486 return EverMadeChange;
487}
488
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000489/// Merge basic blocks which are connected by a single edge, where one of the
490/// basic blocks has a single successor pointing to the other basic block,
491/// which has a single predecessor.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000492bool CodeGenPrepare::eliminateFallThrough(Function &F) {
Nadav Rotem70409992012-08-14 05:19:07 +0000493 bool Changed = false;
494 // Scan all of the blocks in the function, except for the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000495 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000496 BasicBlock *BB = &*I++;
Nadav Rotem70409992012-08-14 05:19:07 +0000497 // If the destination block has a single pred, then this is a trivial
498 // edge, just collapse it.
499 BasicBlock *SinglePred = BB->getSinglePredecessor();
500
Evan Cheng64a223a2012-09-28 23:58:57 +0000501 // Don't merge if BB's address is taken.
502 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000503
504 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
505 if (Term && !Term->isConditional()) {
506 Changed = true;
Michael Liao6e12d122012-08-21 05:55:22 +0000507 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
Nadav Rotem70409992012-08-14 05:19:07 +0000508 // Remember if SinglePred was the entry block of the function.
509 // If so, we will need to move BB back to the entry position.
510 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000511 MergeBasicBlockIntoOnlyPred(BB, nullptr);
Nadav Rotem70409992012-08-14 05:19:07 +0000512
513 if (isEntry && BB != &BB->getParent()->getEntryBlock())
514 BB->moveBefore(&BB->getParent()->getEntryBlock());
515
516 // We have erased a block. Update the iterator.
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000517 I = BB->getIterator();
Nadav Rotem70409992012-08-14 05:19:07 +0000518 }
519 }
520 return Changed;
521}
522
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000523/// Find a destination block from BB if BB is mergeable empty block.
524BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) {
525 // If this block doesn't end with an uncond branch, ignore it.
526 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
527 if (!BI || !BI->isUnconditional())
528 return nullptr;
529
530 // If the instruction before the branch (skipping debug info) isn't a phi
531 // node, then other stuff is happening here.
532 BasicBlock::iterator BBI = BI->getIterator();
533 if (BBI != BB->begin()) {
534 --BBI;
535 while (isa<DbgInfoIntrinsic>(BBI)) {
536 if (BBI == BB->begin())
537 break;
538 --BBI;
539 }
540 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
541 return nullptr;
542 }
543
544 // Do not break infinite loops.
545 BasicBlock *DestBB = BI->getSuccessor(0);
546 if (DestBB == BB)
547 return nullptr;
548
549 if (!canMergeBlocks(BB, DestBB))
550 DestBB = nullptr;
551
552 return DestBB;
553}
554
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000555/// Eliminate blocks that contain only PHI nodes, debug info directives, and an
556/// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
557/// edges in ways that are non-optimal for isel. Start by eliminating these
558/// blocks so we can split them the way we want them.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000559bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000560 SmallPtrSet<BasicBlock *, 16> Preheaders;
561 SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end());
562 while (!LoopList.empty()) {
563 Loop *L = LoopList.pop_back_val();
564 LoopList.insert(LoopList.end(), L->begin(), L->end());
565 if (BasicBlock *Preheader = L->getLoopPreheader())
566 Preheaders.insert(Preheader);
567 }
568
Chris Lattnerc3748562007-04-02 01:35:34 +0000569 bool MadeChange = false;
570 // Note that this intentionally skips the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000571 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000572 BasicBlock *BB = &*I++;
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000573 BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB);
574 if (!DestBB ||
575 !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.count(BB)))
Chris Lattnerc3748562007-04-02 01:35:34 +0000576 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000577
Sanjay Patelfc580a62015-09-21 23:03:16 +0000578 eliminateMostlyEmptyBlock(BB);
Chris Lattnerc3748562007-04-02 01:35:34 +0000579 MadeChange = true;
580 }
581 return MadeChange;
582}
583
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000584bool CodeGenPrepare::isMergingEmptyBlockProfitable(BasicBlock *BB,
585 BasicBlock *DestBB,
586 bool isPreheader) {
587 // Do not delete loop preheaders if doing so would create a critical edge.
588 // Loop preheaders can be good locations to spill registers. If the
589 // preheader is deleted and we create a critical edge, registers may be
590 // spilled in the loop body instead.
591 if (!DisablePreheaderProtect && isPreheader &&
592 !(BB->getSinglePredecessor() &&
593 BB->getSinglePredecessor()->getSingleSuccessor()))
594 return false;
595
596 // Try to skip merging if the unique predecessor of BB is terminated by a
597 // switch or indirect branch instruction, and BB is used as an incoming block
598 // of PHIs in DestBB. In such case, merging BB and DestBB would cause ISel to
599 // add COPY instructions in the predecessor of BB instead of BB (if it is not
600 // merged). Note that the critical edge created by merging such blocks wont be
601 // split in MachineSink because the jump table is not analyzable. By keeping
602 // such empty block (BB), ISel will place COPY instructions in BB, not in the
603 // predecessor of BB.
604 BasicBlock *Pred = BB->getUniquePredecessor();
605 if (!Pred ||
606 !(isa<SwitchInst>(Pred->getTerminator()) ||
607 isa<IndirectBrInst>(Pred->getTerminator())))
608 return true;
609
610 if (BB->getTerminator() != BB->getFirstNonPHI())
611 return true;
612
613 // We use a simple cost heuristic which determine skipping merging is
614 // profitable if the cost of skipping merging is less than the cost of
615 // merging : Cost(skipping merging) < Cost(merging BB), where the
616 // Cost(skipping merging) is Freq(BB) * (Cost(Copy) + Cost(Branch)), and
617 // the Cost(merging BB) is Freq(Pred) * Cost(Copy).
618 // Assuming Cost(Copy) == Cost(Branch), we could simplify it to :
619 // Freq(Pred) / Freq(BB) > 2.
620 // Note that if there are multiple empty blocks sharing the same incoming
621 // value for the PHIs in the DestBB, we consider them together. In such
622 // case, Cost(merging BB) will be the sum of their frequencies.
623
624 if (!isa<PHINode>(DestBB->begin()))
625 return true;
626
627 SmallPtrSet<BasicBlock *, 16> SameIncomingValueBBs;
628
629 // Find all other incoming blocks from which incoming values of all PHIs in
630 // DestBB are the same as the ones from BB.
631 for (pred_iterator PI = pred_begin(DestBB), E = pred_end(DestBB); PI != E;
632 ++PI) {
633 BasicBlock *DestBBPred = *PI;
634 if (DestBBPred == BB)
635 continue;
636
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000637 if (llvm::all_of(DestBB->phis(), [&](const PHINode &DestPN) {
638 return DestPN.getIncomingValueForBlock(BB) ==
639 DestPN.getIncomingValueForBlock(DestBBPred);
640 }))
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000641 SameIncomingValueBBs.insert(DestBBPred);
642 }
643
644 // See if all BB's incoming values are same as the value from Pred. In this
645 // case, no reason to skip merging because COPYs are expected to be place in
646 // Pred already.
647 if (SameIncomingValueBBs.count(Pred))
648 return true;
649
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000650 BlockFrequency PredFreq = BFI->getBlockFreq(Pred);
651 BlockFrequency BBFreq = BFI->getBlockFreq(BB);
652
653 for (auto SameValueBB : SameIncomingValueBBs)
654 if (SameValueBB->getUniquePredecessor() == Pred &&
655 DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB))
656 BBFreq += BFI->getBlockFreq(SameValueBB);
657
658 return PredFreq.getFrequency() <=
659 BBFreq.getFrequency() * FreqRatioToSkipMerge;
660}
661
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000662/// Return true if we can merge BB into DestBB if there is a single
663/// unconditional branch between them, and BB contains no other non-phi
Chris Lattnerc3748562007-04-02 01:35:34 +0000664/// instructions.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000665bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
Chris Lattnerc3748562007-04-02 01:35:34 +0000666 const BasicBlock *DestBB) const {
667 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
668 // the successor. If there are more complex condition (e.g. preheaders),
669 // don't mess around with them.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000670 for (const PHINode &PN : BB->phis()) {
671 for (const User *U : PN.users()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000672 const Instruction *UI = cast<Instruction>(U);
673 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
Chris Lattnerc3748562007-04-02 01:35:34 +0000674 return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000675 // If User is inside DestBB block and it is a PHINode then check
676 // incoming value. If incoming value is not from BB then this is
Devang Pateld3208522007-04-25 00:37:04 +0000677 // a complex condition (e.g. preheaders) we want to avoid here.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000678 if (UI->getParent() == DestBB) {
679 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
Devang Pateld3208522007-04-25 00:37:04 +0000680 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
681 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
682 if (Insn && Insn->getParent() == BB &&
683 Insn->getParent() != UPN->getIncomingBlock(I))
684 return false;
685 }
686 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000687 }
688 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000689
Chris Lattnerc3748562007-04-02 01:35:34 +0000690 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
691 // and DestBB may have conflicting incoming values for the block. If so, we
692 // can't merge the block.
693 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
694 if (!DestBBPN) return true; // no conflict.
Eric Christopherc1ea1492008-09-24 05:32:41 +0000695
Chris Lattnerc3748562007-04-02 01:35:34 +0000696 // Collect the preds of BB.
Chris Lattner8201a9b2007-11-06 22:07:40 +0000697 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerc3748562007-04-02 01:35:34 +0000698 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
699 // It is faster to get preds from a PHI than with pred_iterator.
700 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
701 BBPreds.insert(BBPN->getIncomingBlock(i));
702 } else {
703 BBPreds.insert(pred_begin(BB), pred_end(BB));
704 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000705
Chris Lattnerc3748562007-04-02 01:35:34 +0000706 // Walk the preds of DestBB.
707 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
708 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
709 if (BBPreds.count(Pred)) { // Common predecessor?
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000710 for (const PHINode &PN : DestBB->phis()) {
711 const Value *V1 = PN.getIncomingValueForBlock(Pred);
712 const Value *V2 = PN.getIncomingValueForBlock(BB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000713
Chris Lattnerc3748562007-04-02 01:35:34 +0000714 // If V2 is a phi node in BB, look up what the mapped value will be.
715 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
716 if (V2PN->getParent() == BB)
717 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000718
Chris Lattnerc3748562007-04-02 01:35:34 +0000719 // If there is a conflict, bail out.
720 if (V1 != V2) return false;
721 }
722 }
723 }
724
725 return true;
726}
727
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000728/// Eliminate a basic block that has only phi's and an unconditional branch in
729/// it.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000730void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000731 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
732 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000733
David Greene74e2d492010-01-05 01:27:11 +0000734 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000735
Chris Lattnerc3748562007-04-02 01:35:34 +0000736 // If the destination block has a single pred, then this is a trivial edge,
737 // just collapse it.
Chris Lattner4059f432008-11-27 19:29:14 +0000738 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattner8a172da2008-11-28 19:54:49 +0000739 if (SinglePred != DestBB) {
740 // Remember if SinglePred was the entry block of the function. If so, we
741 // will need to move BB back to the entry position.
742 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Balaram Makam32bcb5d2017-10-27 00:35:18 +0000743 MergeBasicBlockIntoOnlyPred(DestBB, nullptr);
Chris Lattner4059f432008-11-27 19:29:14 +0000744
Chris Lattner8a172da2008-11-28 19:54:49 +0000745 if (isEntry && BB != &BB->getParent()->getEntryBlock())
746 BB->moveBefore(&BB->getParent()->getEntryBlock());
Nadav Rotem465834c2012-07-24 10:51:42 +0000747
David Greene74e2d492010-01-05 01:27:11 +0000748 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattner8a172da2008-11-28 19:54:49 +0000749 return;
750 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000751 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000752
Chris Lattnerc3748562007-04-02 01:35:34 +0000753 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
754 // to handle the new incoming edges it is about to have.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000755 for (PHINode &PN : DestBB->phis()) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000756 // Remove the incoming value for BB, and remember it.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000757 Value *InVal = PN.removeIncomingValue(BB, false);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000758
Chris Lattnerc3748562007-04-02 01:35:34 +0000759 // Two options: either the InVal is a phi node defined in BB or it is some
760 // value that dominates BB.
761 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
762 if (InValPhi && InValPhi->getParent() == BB) {
763 // Add all of the input values of the input PHI as inputs of this phi.
764 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000765 PN.addIncoming(InValPhi->getIncomingValue(i),
766 InValPhi->getIncomingBlock(i));
Chris Lattnerc3748562007-04-02 01:35:34 +0000767 } else {
768 // Otherwise, add one instance of the dominating value for each edge that
769 // we will be adding.
770 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
771 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000772 PN.addIncoming(InVal, BBPN->getIncomingBlock(i));
Chris Lattnerc3748562007-04-02 01:35:34 +0000773 } else {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000774 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000775 PN.addIncoming(InVal, *PI);
Chris Lattnerc3748562007-04-02 01:35:34 +0000776 }
777 }
778 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000779
Chris Lattnerc3748562007-04-02 01:35:34 +0000780 // The PHIs are now updated, change everything that refers to BB to use
781 // DestBB and remove BB.
782 BB->replaceAllUsesWith(DestBB);
783 BB->eraseFromParent();
Cameron Zwarichced753f2011-01-05 17:27:27 +0000784 ++NumBlocksElim;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000785
David Greene74e2d492010-01-05 01:27:11 +0000786 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerc3748562007-04-02 01:35:34 +0000787}
788
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000789// Computes a map of base pointer relocation instructions to corresponding
790// derived pointer relocation instructions given a vector of all relocate calls
791static void computeBaseDerivedRelocateMap(
Manuel Jacob83eefa62016-01-05 04:03:00 +0000792 const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
793 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>>
794 &RelocateInstMap) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000795 // Collect information in two maps: one primarily for locating the base object
796 // while filling the second map; the second map is the final structure holding
797 // a mapping between Base and corresponding Derived relocate calls
Manuel Jacob83eefa62016-01-05 04:03:00 +0000798 DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap;
799 for (auto *ThisRelocate : AllRelocateCalls) {
800 auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
801 ThisRelocate->getDerivedPtrIndex());
802 RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000803 }
804 for (auto &Item : RelocateIdxMap) {
805 std::pair<unsigned, unsigned> Key = Item.first;
806 if (Key.first == Key.second)
807 // Base relocation: nothing to insert
808 continue;
809
Manuel Jacob83eefa62016-01-05 04:03:00 +0000810 GCRelocateInst *I = Item.second;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000811 auto BaseKey = std::make_pair(Key.first, Key.first);
Sanjoy Dasb8186762015-02-27 02:24:16 +0000812
813 // We're iterating over RelocateIdxMap so we cannot modify it.
814 auto MaybeBase = RelocateIdxMap.find(BaseKey);
815 if (MaybeBase == RelocateIdxMap.end())
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000816 // TODO: We might want to insert a new base object relocate and gep off
817 // that, if there are enough derived object relocates.
818 continue;
Sanjoy Dasb8186762015-02-27 02:24:16 +0000819
820 RelocateInstMap[MaybeBase->second].push_back(I);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000821 }
822}
823
824// Accepts a GEP and extracts the operands into a vector provided they're all
825// small integer constants
826static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
827 SmallVectorImpl<Value *> &OffsetV) {
828 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
829 // Only accept small constant integer operands
830 auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
831 if (!Op || Op->getZExtValue() > 20)
832 return false;
833 }
834
835 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
836 OffsetV.push_back(GEP->getOperand(i));
837 return true;
838}
839
840// Takes a RelocatedBase (base pointer relocation instruction) and Targets to
841// replace, computes a replacement, and affects it.
842static bool
Manuel Jacob83eefa62016-01-05 04:03:00 +0000843simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase,
844 const SmallVectorImpl<GCRelocateInst *> &Targets) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000845 bool MadeChange = false;
Serguei Katkov9e5604d2017-08-17 05:48:30 +0000846 // We must ensure the relocation of derived pointer is defined after
847 // relocation of base pointer. If we find a relocation corresponding to base
848 // defined earlier than relocation of base then we move relocation of base
849 // right before found relocation. We consider only relocation in the same
850 // basic block as relocation of base. Relocations from other basic block will
851 // be skipped by optimization and we do not care about them.
852 for (auto R = RelocatedBase->getParent()->getFirstInsertionPt();
853 &*R != RelocatedBase; ++R)
854 if (auto RI = dyn_cast<GCRelocateInst>(R))
855 if (RI->getStatepoint() == RelocatedBase->getStatepoint())
856 if (RI->getBasePtrIndex() == RelocatedBase->getBasePtrIndex()) {
857 RelocatedBase->moveBefore(RI);
858 break;
859 }
860
Manuel Jacob83eefa62016-01-05 04:03:00 +0000861 for (GCRelocateInst *ToReplace : Targets) {
862 assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000863 "Not relocating a derived object of the original base object");
Manuel Jacob83eefa62016-01-05 04:03:00 +0000864 if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000865 // A duplicate relocate call. TODO: coalesce duplicates.
866 continue;
867 }
868
Igor Laevskyf637b4a2015-11-03 18:37:40 +0000869 if (RelocatedBase->getParent() != ToReplace->getParent()) {
870 // Base and derived relocates are in different basic blocks.
871 // In this case transform is only valid when base dominates derived
872 // relocate. However it would be too expensive to check dominance
873 // for each such relocate, so we skip the whole transformation.
874 continue;
875 }
876
Manuel Jacob83eefa62016-01-05 04:03:00 +0000877 Value *Base = ToReplace->getBasePtr();
878 auto Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000879 if (!Derived || Derived->getPointerOperand() != Base)
880 continue;
881
882 SmallVector<Value *, 2> OffsetV;
883 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
884 continue;
885
886 // Create a Builder and replace the target callsite with a gep
Sanjay Patel545a4562016-01-20 18:59:16 +0000887 assert(RelocatedBase->getNextNode() &&
888 "Should always have one since it's not a terminator");
Sanjoy Das3d705e32015-05-11 23:47:30 +0000889
890 // Insert after RelocatedBase
891 IRBuilder<> Builder(RelocatedBase->getNextNode());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000892 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
Sanjoy Das89c54912015-05-11 18:49:34 +0000893
894 // If gc_relocate does not match the actual type, cast it to the right type.
895 // In theory, there must be a bitcast after gc_relocate if the type does not
896 // match, and we should reuse it to get the derived pointer. But it could be
897 // cases like this:
898 // bb1:
899 // ...
900 // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
901 // br label %merge
902 //
903 // bb2:
904 // ...
905 // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
906 // br label %merge
907 //
908 // merge:
909 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
910 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
911 //
912 // In this case, we can not find the bitcast any more. So we insert a new bitcast
913 // no matter there is already one or not. In this way, we can handle all cases, and
914 // the extra bitcast should be optimized away in later passes.
Manuel Jacob5b90b142015-12-19 18:38:42 +0000915 Value *ActualRelocatedBase = RelocatedBase;
Sanjoy Das89c54912015-05-11 18:49:34 +0000916 if (RelocatedBase->getType() != Base->getType()) {
917 ActualRelocatedBase =
Manuel Jacob5b90b142015-12-19 18:38:42 +0000918 Builder.CreateBitCast(RelocatedBase, Base->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +0000919 }
David Blaikie68d535c2015-03-24 22:38:16 +0000920 Value *Replacement = Builder.CreateGEP(
Sanjoy Das89c54912015-05-11 18:49:34 +0000921 Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000922 Replacement->takeName(ToReplace);
Sanjoy Das89c54912015-05-11 18:49:34 +0000923 // If the newly generated derived pointer's type does not match the original derived
924 // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
Manuel Jacob5b90b142015-12-19 18:38:42 +0000925 Value *ActualReplacement = Replacement;
926 if (Replacement->getType() != ToReplace->getType()) {
Sanjoy Das89c54912015-05-11 18:49:34 +0000927 ActualReplacement =
Manuel Jacob5b90b142015-12-19 18:38:42 +0000928 Builder.CreateBitCast(Replacement, ToReplace->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +0000929 }
930 ToReplace->replaceAllUsesWith(ActualReplacement);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000931 ToReplace->eraseFromParent();
932
933 MadeChange = true;
934 }
935 return MadeChange;
936}
937
938// Turns this:
939//
940// %base = ...
941// %ptr = gep %base + 15
942// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
943// %base' = relocate(%tok, i32 4, i32 4)
944// %ptr' = relocate(%tok, i32 4, i32 5)
945// %val = load %ptr'
946//
947// into this:
948//
949// %base = ...
950// %ptr = gep %base + 15
951// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
952// %base' = gc.relocate(%tok, i32 4, i32 4)
953// %ptr' = gep %base' + 15
954// %val = load %ptr'
955bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
956 bool MadeChange = false;
Manuel Jacob83eefa62016-01-05 04:03:00 +0000957 SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000958
959 for (auto *U : I.users())
Manuel Jacob83eefa62016-01-05 04:03:00 +0000960 if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000961 // Collect all the relocate calls associated with a statepoint
Manuel Jacob83eefa62016-01-05 04:03:00 +0000962 AllRelocateCalls.push_back(Relocate);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000963
964 // We need atleast one base pointer relocation + one derived pointer
965 // relocation to mangle
966 if (AllRelocateCalls.size() < 2)
967 return false;
968
969 // RelocateInstMap is a mapping from the base relocate instruction to the
970 // corresponding derived relocate instructions
Manuel Jacob83eefa62016-01-05 04:03:00 +0000971 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000972 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
973 if (RelocateInstMap.empty())
974 return false;
975
976 for (auto &Item : RelocateInstMap)
977 // Item.first is the RelocatedBase to offset against
978 // Item.second is the vector of Targets to replace
979 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
980 return MadeChange;
981}
982
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000983/// SinkCast - Sink the specified cast instruction into its user blocks
984static bool SinkCast(CastInst *CI) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000985 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000986
Chris Lattnerf2836d12007-03-31 04:06:36 +0000987 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000988 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000989
Chris Lattnerf2836d12007-03-31 04:06:36 +0000990 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000991 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Chris Lattnerf2836d12007-03-31 04:06:36 +0000992 UI != E; ) {
993 Use &TheUse = UI.getUse();
994 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000995
Chris Lattnerf2836d12007-03-31 04:06:36 +0000996 // Figure out which BB this cast is used in. For PHI's this is the
997 // appropriate predecessor block.
998 BasicBlock *UserBB = User->getParent();
999 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001000 UserBB = PN->getIncomingBlock(TheUse);
Chris Lattnerf2836d12007-03-31 04:06:36 +00001001 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001002
Chris Lattnerf2836d12007-03-31 04:06:36 +00001003 // Preincrement use iterator so we don't invalidate it.
1004 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001005
David Majnemer0c80e2e2016-04-27 19:36:38 +00001006 // The first insertion point of a block containing an EH pad is after the
1007 // pad. If the pad is the user, we cannot sink the cast past the pad.
1008 if (User->isEHPad())
1009 continue;
1010
Andrew Kaylord0430e82015-11-23 19:16:15 +00001011 // If the block selected to receive the cast is an EH pad that does not
1012 // allow non-PHI instructions before the terminator, we can't sink the
1013 // cast.
1014 if (UserBB->getTerminator()->isEHPad())
1015 continue;
1016
Chris Lattnerf2836d12007-03-31 04:06:36 +00001017 // If this user is in the same block as the cast, don't change the cast.
1018 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001019
Chris Lattnerf2836d12007-03-31 04:06:36 +00001020 // If we have already inserted a cast into this block, use it.
1021 CastInst *&InsertedCast = InsertedCasts[UserBB];
1022
1023 if (!InsertedCast) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00001024 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001025 assert(InsertPt != UserBB->end());
1026 InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
1027 CI->getType(), "", &*InsertPt);
Chris Lattnerf2836d12007-03-31 04:06:36 +00001028 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001029
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001030 // Replace a use of the cast with a use of the new cast.
Chris Lattnerf2836d12007-03-31 04:06:36 +00001031 TheUse = InsertedCast;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001032 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +00001033 ++NumCastUses;
Chris Lattnerf2836d12007-03-31 04:06:36 +00001034 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001035
Chris Lattnerf2836d12007-03-31 04:06:36 +00001036 // If we removed all uses, nuke the cast.
Duncan Sandsafa84da42008-01-20 16:51:46 +00001037 if (CI->use_empty()) {
Adrian Prantl261ac8b2017-11-03 21:55:03 +00001038 salvageDebugInfo(*CI);
Chris Lattnerf2836d12007-03-31 04:06:36 +00001039 CI->eraseFromParent();
Duncan Sandsafa84da42008-01-20 16:51:46 +00001040 MadeChange = true;
1041 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001042
Chris Lattnerf2836d12007-03-31 04:06:36 +00001043 return MadeChange;
1044}
1045
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001046/// If the specified cast instruction is a noop copy (e.g. it's casting from
1047/// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
1048/// reduce the number of virtual registers that must be created and coalesced.
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001049///
1050/// Return true if any changes are made.
Mehdi Amini44ede332015-07-09 02:09:04 +00001051static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
1052 const DataLayout &DL) {
Justin Lebar3e50a5b2016-11-21 22:49:15 +00001053 // Sink only "cheap" (or nop) address-space casts. This is a weaker condition
1054 // than sinking only nop casts, but is helpful on some platforms.
1055 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(CI)) {
1056 if (!TLI.isCheapAddrSpaceCast(ASC->getSrcAddressSpace(),
1057 ASC->getDestAddressSpace()))
1058 return false;
1059 }
1060
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001061 // If this is a noop copy,
Mehdi Amini44ede332015-07-09 02:09:04 +00001062 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
1063 EVT DstVT = TLI.getValueType(DL, CI->getType());
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001064
1065 // This is an fp<->int conversion?
1066 if (SrcVT.isInteger() != DstVT.isInteger())
1067 return false;
1068
1069 // If this is an extension, it will be a zero or sign extension, which
1070 // isn't a noop.
1071 if (SrcVT.bitsLT(DstVT)) return false;
1072
1073 // If these values will be promoted, find out what they will be promoted
1074 // to. This helps us consider truncates on PPC as noop copies when they
1075 // are.
1076 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
1077 TargetLowering::TypePromoteInteger)
1078 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
1079 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
1080 TargetLowering::TypePromoteInteger)
1081 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
1082
1083 // If, after promotion, these are the same types, this is a noop copy.
1084 if (SrcVT != DstVT)
1085 return false;
1086
1087 return SinkCast(CI);
1088}
1089
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001090/// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if
1091/// possible.
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001092///
1093/// Return true if any changes were made.
1094static bool CombineUAddWithOverflow(CmpInst *CI) {
1095 Value *A, *B;
1096 Instruction *AddI;
1097 if (!match(CI,
1098 m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI))))
1099 return false;
1100
1101 Type *Ty = AddI->getType();
1102 if (!isa<IntegerType>(Ty))
1103 return false;
1104
1105 // We don't want to move around uses of condition values this late, so we we
1106 // check if it is legal to create the call to the intrinsic in the basic
1107 // block containing the icmp:
1108
1109 if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse())
1110 return false;
1111
1112#ifndef NDEBUG
1113 // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
1114 // for now:
1115 if (AddI->hasOneUse())
1116 assert(*AddI->user_begin() == CI && "expected!");
1117#endif
1118
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001119 Module *M = CI->getModule();
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001120 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
1121
1122 auto *InsertPt = AddI->hasOneUse() ? CI : AddI;
1123
1124 auto *UAddWithOverflow =
1125 CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt);
1126 auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt);
1127 auto *Overflow =
1128 ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt);
1129
1130 CI->replaceAllUsesWith(Overflow);
1131 AddI->replaceAllUsesWith(UAdd);
1132 CI->eraseFromParent();
1133 AddI->eraseFromParent();
1134 return true;
1135}
1136
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001137/// Sink the given CmpInst into user blocks to reduce the number of virtual
1138/// registers that must be created and coalesced. This is a clear win except on
1139/// targets with multiple condition code registers (PowerPC), where it might
1140/// lose; some adjustment may be wanted there.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001141///
1142/// Return true if any changes are made.
Peter Zotov8efe38a2016-04-03 19:32:13 +00001143static bool SinkCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001144 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001145
Peter Zotov0b6d7bc2016-04-03 16:36:17 +00001146 // Avoid sinking soft-FP comparisons, since this can move them into a loop.
Peter Zotov8efe38a2016-04-03 19:32:13 +00001147 if (TLI && TLI->useSoftFloat() && isa<FCmpInst>(CI))
Peter Zotov0b6d7bc2016-04-03 16:36:17 +00001148 return false;
1149
1150 // Only insert a cmp in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001151 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001152
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001153 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001154 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001155 UI != E; ) {
1156 Use &TheUse = UI.getUse();
1157 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +00001158
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001159 // Preincrement use iterator so we don't invalidate it.
1160 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001161
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001162 // Don't bother for PHI nodes.
1163 if (isa<PHINode>(User))
1164 continue;
1165
1166 // Figure out which BB this cmp is used in.
1167 BasicBlock *UserBB = User->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001168
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001169 // If this user is in the same block as the cmp, don't change the cmp.
1170 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001171
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001172 // If we have already inserted a cmp into this block, use it.
1173 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
1174
1175 if (!InsertedCmp) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00001176 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001177 assert(InsertPt != UserBB->end());
Eric Christopherc1ea1492008-09-24 05:32:41 +00001178 InsertedCmp =
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001179 CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
1180 CI->getOperand(0), CI->getOperand(1), "", &*InsertPt);
Wolfgang Piebe51bede2016-10-06 21:43:45 +00001181 // Propagate the debug info.
1182 InsertedCmp->setDebugLoc(CI->getDebugLoc());
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001183 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001184
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001185 // Replace a use of the cmp with a use of the new cmp.
1186 TheUse = InsertedCmp;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001187 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +00001188 ++NumCmpUses;
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001189 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001190
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001191 // If we removed all uses, nuke the cmp.
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001192 if (CI->use_empty()) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001193 CI->eraseFromParent();
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001194 MadeChange = true;
1195 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001196
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001197 return MadeChange;
1198}
1199
Peter Zotovf87e5502016-04-03 17:11:53 +00001200static bool OptimizeCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
Peter Zotov8efe38a2016-04-03 19:32:13 +00001201 if (SinkCmpExpression(CI, TLI))
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001202 return true;
1203
1204 if (CombineUAddWithOverflow(CI))
1205 return true;
1206
1207 return false;
1208}
1209
Geoff Berry5d534b62017-02-21 18:53:14 +00001210/// Duplicate and sink the given 'and' instruction into user blocks where it is
1211/// used in a compare to allow isel to generate better code for targets where
1212/// this operation can be combined.
1213///
1214/// Return true if any changes are made.
1215static bool sinkAndCmp0Expression(Instruction *AndI,
1216 const TargetLowering &TLI,
1217 SetOfInstrs &InsertedInsts) {
1218 // Double-check that we're not trying to optimize an instruction that was
1219 // already optimized by some other part of this pass.
1220 assert(!InsertedInsts.count(AndI) &&
1221 "Attempting to optimize already optimized and instruction");
1222 (void) InsertedInsts;
1223
1224 // Nothing to do for single use in same basic block.
1225 if (AndI->hasOneUse() &&
1226 AndI->getParent() == cast<Instruction>(*AndI->user_begin())->getParent())
1227 return false;
1228
1229 // Try to avoid cases where sinking/duplicating is likely to increase register
1230 // pressure.
1231 if (!isa<ConstantInt>(AndI->getOperand(0)) &&
1232 !isa<ConstantInt>(AndI->getOperand(1)) &&
1233 AndI->getOperand(0)->hasOneUse() && AndI->getOperand(1)->hasOneUse())
1234 return false;
1235
1236 for (auto *U : AndI->users()) {
1237 Instruction *User = cast<Instruction>(U);
1238
1239 // Only sink for and mask feeding icmp with 0.
1240 if (!isa<ICmpInst>(User))
1241 return false;
1242
1243 auto *CmpC = dyn_cast<ConstantInt>(User->getOperand(1));
1244 if (!CmpC || !CmpC->isZero())
1245 return false;
1246 }
1247
1248 if (!TLI.isMaskAndCmp0FoldingBeneficial(*AndI))
1249 return false;
1250
1251 DEBUG(dbgs() << "found 'and' feeding only icmp 0;\n");
1252 DEBUG(AndI->getParent()->dump());
1253
1254 // Push the 'and' into the same block as the icmp 0. There should only be
1255 // one (icmp (and, 0)) in each block, since CSE/GVN should have removed any
1256 // others, so we don't need to keep track of which BBs we insert into.
1257 for (Value::user_iterator UI = AndI->user_begin(), E = AndI->user_end();
1258 UI != E; ) {
1259 Use &TheUse = UI.getUse();
1260 Instruction *User = cast<Instruction>(*UI);
1261
1262 // Preincrement use iterator so we don't invalidate it.
1263 ++UI;
1264
1265 DEBUG(dbgs() << "sinking 'and' use: " << *User << "\n");
1266
1267 // Keep the 'and' in the same place if the use is already in the same block.
1268 Instruction *InsertPt =
1269 User->getParent() == AndI->getParent() ? AndI : User;
1270 Instruction *InsertedAnd =
1271 BinaryOperator::Create(Instruction::And, AndI->getOperand(0),
1272 AndI->getOperand(1), "", InsertPt);
1273 // Propagate the debug info.
1274 InsertedAnd->setDebugLoc(AndI->getDebugLoc());
1275
1276 // Replace a use of the 'and' with a use of the new 'and'.
1277 TheUse = InsertedAnd;
1278 ++NumAndUses;
1279 DEBUG(User->getParent()->dump());
1280 }
1281
1282 // We removed all uses, nuke the and.
1283 AndI->eraseFromParent();
1284 return true;
1285}
1286
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001287/// Check if the candidates could be combined with a shift instruction, which
1288/// includes:
Yi Jiangd069f632014-04-21 19:34:27 +00001289/// 1. Truncate instruction
1290/// 2. And instruction and the imm is a mask of the low bits:
1291/// imm & (imm+1) == 0
Benjamin Kramer322053c2014-04-27 14:54:59 +00001292static bool isExtractBitsCandidateUse(Instruction *User) {
Yi Jiangd069f632014-04-21 19:34:27 +00001293 if (!isa<TruncInst>(User)) {
1294 if (User->getOpcode() != Instruction::And ||
1295 !isa<ConstantInt>(User->getOperand(1)))
1296 return false;
1297
Quentin Colombetd4f44692014-04-22 01:20:34 +00001298 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
Yi Jiangd069f632014-04-21 19:34:27 +00001299
Quentin Colombetd4f44692014-04-22 01:20:34 +00001300 if ((Cimm & (Cimm + 1)).getBoolValue())
Yi Jiangd069f632014-04-21 19:34:27 +00001301 return false;
1302 }
1303 return true;
1304}
1305
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001306/// Sink both shift and truncate instruction to the use of truncate's BB.
Benjamin Kramer322053c2014-04-27 14:54:59 +00001307static bool
Yi Jiangd069f632014-04-21 19:34:27 +00001308SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
1309 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
Mehdi Amini44ede332015-07-09 02:09:04 +00001310 const TargetLowering &TLI, const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001311 BasicBlock *UserBB = User->getParent();
1312 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
1313 TruncInst *TruncI = dyn_cast<TruncInst>(User);
1314 bool MadeChange = false;
1315
1316 for (Value::user_iterator TruncUI = TruncI->user_begin(),
1317 TruncE = TruncI->user_end();
1318 TruncUI != TruncE;) {
1319
1320 Use &TruncTheUse = TruncUI.getUse();
1321 Instruction *TruncUser = cast<Instruction>(*TruncUI);
1322 // Preincrement use iterator so we don't invalidate it.
1323
1324 ++TruncUI;
1325
1326 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
1327 if (!ISDOpcode)
1328 continue;
1329
Tim Northovere2239ff2014-07-29 10:20:22 +00001330 // If the use is actually a legal node, there will not be an
1331 // implicit truncate.
1332 // FIXME: always querying the result type is just an
1333 // approximation; some nodes' legality is determined by the
1334 // operand or other means. There's no good way to find out though.
Ahmed Bougacha0788d492014-11-12 22:16:55 +00001335 if (TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00001336 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
Yi Jiangd069f632014-04-21 19:34:27 +00001337 continue;
1338
1339 // Don't bother for PHI nodes.
1340 if (isa<PHINode>(TruncUser))
1341 continue;
1342
1343 BasicBlock *TruncUserBB = TruncUser->getParent();
1344
1345 if (UserBB == TruncUserBB)
1346 continue;
1347
1348 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
1349 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
1350
1351 if (!InsertedShift && !InsertedTrunc) {
1352 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001353 assert(InsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001354 // Sink the shift
1355 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001356 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1357 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001358 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001359 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1360 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001361
1362 // Sink the trunc
1363 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
1364 TruncInsertPt++;
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001365 assert(TruncInsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001366
1367 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001368 TruncI->getType(), "", &*TruncInsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001369
1370 MadeChange = true;
1371
1372 TruncTheUse = InsertedTrunc;
1373 }
1374 }
1375 return MadeChange;
1376}
1377
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001378/// Sink the shift *right* instruction into user blocks if the uses could
1379/// potentially be combined with this shift instruction and generate BitExtract
1380/// instruction. It will only be applied if the architecture supports BitExtract
1381/// instruction. Here is an example:
Yi Jiangd069f632014-04-21 19:34:27 +00001382/// BB1:
1383/// %x.extract.shift = lshr i64 %arg1, 32
1384/// BB2:
1385/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
1386/// ==>
1387///
1388/// BB2:
1389/// %x.extract.shift.1 = lshr i64 %arg1, 32
1390/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
1391///
1392/// CodeGen will recoginze the pattern in BB2 and generate BitExtract
1393/// instruction.
1394/// Return true if any changes are made.
1395static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
Mehdi Amini44ede332015-07-09 02:09:04 +00001396 const TargetLowering &TLI,
1397 const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001398 BasicBlock *DefBB = ShiftI->getParent();
1399
1400 /// Only insert instructions in each block once.
1401 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
1402
Mehdi Amini44ede332015-07-09 02:09:04 +00001403 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
Yi Jiangd069f632014-04-21 19:34:27 +00001404
1405 bool MadeChange = false;
1406 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
1407 UI != E;) {
1408 Use &TheUse = UI.getUse();
1409 Instruction *User = cast<Instruction>(*UI);
1410 // Preincrement use iterator so we don't invalidate it.
1411 ++UI;
1412
1413 // Don't bother for PHI nodes.
1414 if (isa<PHINode>(User))
1415 continue;
1416
1417 if (!isExtractBitsCandidateUse(User))
1418 continue;
1419
1420 BasicBlock *UserBB = User->getParent();
1421
1422 if (UserBB == DefBB) {
1423 // If the shift and truncate instruction are in the same BB. The use of
1424 // the truncate(TruncUse) may still introduce another truncate if not
1425 // legal. In this case, we would like to sink both shift and truncate
1426 // instruction to the BB of TruncUse.
1427 // for example:
1428 // BB1:
1429 // i64 shift.result = lshr i64 opnd, imm
1430 // trunc.result = trunc shift.result to i16
1431 //
1432 // BB2:
1433 // ----> We will have an implicit truncate here if the architecture does
1434 // not have i16 compare.
1435 // cmp i16 trunc.result, opnd2
1436 //
1437 if (isa<TruncInst>(User) && shiftIsLegal
1438 // If the type of the truncate is legal, no trucate will be
1439 // introduced in other basic blocks.
Mehdi Amini44ede332015-07-09 02:09:04 +00001440 &&
1441 (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
Yi Jiangd069f632014-04-21 19:34:27 +00001442 MadeChange =
Mehdi Amini44ede332015-07-09 02:09:04 +00001443 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
Yi Jiangd069f632014-04-21 19:34:27 +00001444
1445 continue;
1446 }
1447 // If we have already inserted a shift into this block, use it.
1448 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
1449
1450 if (!InsertedShift) {
1451 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001452 assert(InsertPt != UserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001453
1454 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001455 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1456 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001457 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001458 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1459 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001460
1461 MadeChange = true;
1462 }
1463
1464 // Replace a use of the shift with a use of the new shift.
1465 TheUse = InsertedShift;
1466 }
1467
1468 // If we removed all uses, nuke the shift.
1469 if (ShiftI->use_empty())
1470 ShiftI->eraseFromParent();
1471
1472 return MadeChange;
1473}
1474
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001475/// If counting leading or trailing zeros is an expensive operation and a zero
1476/// input is defined, add a check for zero to avoid calling the intrinsic.
1477///
1478/// We want to transform:
1479/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
1480///
1481/// into:
1482/// entry:
1483/// %cmpz = icmp eq i64 %A, 0
1484/// br i1 %cmpz, label %cond.end, label %cond.false
1485/// cond.false:
1486/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
1487/// br label %cond.end
1488/// cond.end:
1489/// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
1490///
1491/// If the transform is performed, return true and set ModifiedDT to true.
1492static bool despeculateCountZeros(IntrinsicInst *CountZeros,
1493 const TargetLowering *TLI,
1494 const DataLayout *DL,
1495 bool &ModifiedDT) {
1496 if (!TLI || !DL)
1497 return false;
1498
1499 // If a zero input is undefined, it doesn't make sense to despeculate that.
1500 if (match(CountZeros->getOperand(1), m_One()))
1501 return false;
1502
1503 // If it's cheap to speculate, there's nothing to do.
1504 auto IntrinsicID = CountZeros->getIntrinsicID();
1505 if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) ||
1506 (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz()))
1507 return false;
1508
1509 // Only handle legal scalar cases. Anything else requires too much work.
1510 Type *Ty = CountZeros->getType();
1511 unsigned SizeInBits = Ty->getPrimitiveSizeInBits();
Jun Bum Limbe11bdc2016-05-13 18:38:35 +00001512 if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSizeInBits())
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001513 return false;
1514
1515 // The intrinsic will be sunk behind a compare against zero and branch.
1516 BasicBlock *StartBlock = CountZeros->getParent();
1517 BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
1518
1519 // Create another block after the count zero intrinsic. A PHI will be added
1520 // in this block to select the result of the intrinsic or the bit-width
1521 // constant if the input to the intrinsic is zero.
1522 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
1523 BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
1524
1525 // Set up a builder to create a compare, conditional branch, and PHI.
1526 IRBuilder<> Builder(CountZeros->getContext());
1527 Builder.SetInsertPoint(StartBlock->getTerminator());
1528 Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
1529
1530 // Replace the unconditional branch that was created by the first split with
1531 // a compare against zero and a conditional branch.
1532 Value *Zero = Constant::getNullValue(Ty);
1533 Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz");
1534 Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
1535 StartBlock->getTerminator()->eraseFromParent();
1536
1537 // Create a PHI in the end block to select either the output of the intrinsic
1538 // or the bit width of the operand.
1539 Builder.SetInsertPoint(&EndBlock->front());
1540 PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
1541 CountZeros->replaceAllUsesWith(PN);
1542 Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
1543 PN->addIncoming(BitWidth, StartBlock);
1544 PN->addIncoming(CountZeros, CallBlock);
1545
1546 // We are explicitly handling the zero case, so we can set the intrinsic's
1547 // undefined zero argument to 'true'. This will also prevent reprocessing the
1548 // intrinsic; we only despeculate when a zero input is defined.
1549 CountZeros->setArgOperand(1, Builder.getTrue());
1550 ModifiedDT = true;
1551 return true;
1552}
1553
Sanjay Patel3b8974b2017-06-08 20:00:09 +00001554bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool &ModifiedDT) {
Chris Lattner7a277142011-01-15 07:14:54 +00001555 BasicBlock *BB = CI->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00001556
Chris Lattner7a277142011-01-15 07:14:54 +00001557 // Lower inline assembly if we can.
1558 // If we found an inline asm expession, and if the target knows how to
1559 // lower it to normal LLVM code, do so now.
1560 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
1561 if (TLI->ExpandInlineAsm(CI)) {
1562 // Avoid invalidating the iterator.
1563 CurInstIterator = BB->begin();
1564 // Avoid processing instructions out of order, which could cause
1565 // reuse before a value is defined.
1566 SunkAddrs.clear();
1567 return true;
1568 }
1569 // Sink address computing for memory operands into the block.
Sanjay Patelfc580a62015-09-21 23:03:16 +00001570 if (optimizeInlineAsmInst(CI))
Chris Lattner7a277142011-01-15 07:14:54 +00001571 return true;
1572 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001573
John Brawn0dbcd652015-03-18 12:01:59 +00001574 // Align the pointer arguments to this call if the target thinks it's a good
1575 // idea
1576 unsigned MinSize, PrefAlign;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001577 if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
John Brawn0dbcd652015-03-18 12:01:59 +00001578 for (auto &Arg : CI->arg_operands()) {
1579 // We want to align both objects whose address is used directly and
1580 // objects whose address is used in casts and GEPs, though it only makes
1581 // sense for GEPs if the offset is a multiple of the desired alignment and
1582 // if size - offset meets the size threshold.
1583 if (!Arg->getType()->isPointerTy())
1584 continue;
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00001585 APInt Offset(DL->getIndexSizeInBits(
Mehdi Amini4fe37982015-07-07 18:45:17 +00001586 cast<PointerType>(Arg->getType())->getAddressSpace()),
1587 0);
1588 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
John Brawn0dbcd652015-03-18 12:01:59 +00001589 uint64_t Offset2 = Offset.getLimitedValue();
John Brawne8fd6c82015-04-13 10:47:39 +00001590 if ((Offset2 & (PrefAlign-1)) != 0)
1591 continue;
John Brawn0dbcd652015-03-18 12:01:59 +00001592 AllocaInst *AI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001593 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
1594 DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
John Brawn0dbcd652015-03-18 12:01:59 +00001595 AI->setAlignment(PrefAlign);
John Brawne8fd6c82015-04-13 10:47:39 +00001596 // Global variables can only be aligned if they are defined in this
1597 // object (i.e. they are uniquely initialized in this object), and
1598 // over-aligning global variables that have an explicit section is
1599 // forbidden.
1600 GlobalVariable *GV;
James Y Knightac03dca2016-01-15 16:33:06 +00001601 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
Tim Northover918f0502016-07-18 18:28:52 +00001602 GV->getPointerAlignment(*DL) < PrefAlign &&
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001603 DL->getTypeAllocSize(GV->getValueType()) >=
Mehdi Amini4fe37982015-07-07 18:45:17 +00001604 MinSize + Offset2)
John Brawne8fd6c82015-04-13 10:47:39 +00001605 GV->setAlignment(PrefAlign);
John Brawn0dbcd652015-03-18 12:01:59 +00001606 }
1607 // If this is a memcpy (or similar) then we may be able to improve the
1608 // alignment
1609 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
Daniel Neilsonbe58a222018-01-31 17:24:53 +00001610 unsigned DestAlign = getKnownAlignment(MI->getDest(), *DL);
1611 if (DestAlign > MI->getDestAlignment())
1612 MI->setDestAlignment(DestAlign);
1613 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
1614 unsigned SrcAlign = getKnownAlignment(MTI->getSource(), *DL);
1615 if (SrcAlign > MTI->getSourceAlignment())
1616 MTI->setSourceAlignment(SrcAlign);
1617 }
John Brawn0dbcd652015-03-18 12:01:59 +00001618 }
1619 }
1620
Philip Reamesac115ed2016-03-09 23:13:12 +00001621 // If we have a cold call site, try to sink addressing computation into the
1622 // cold block. This interacts with our handling for loads and stores to
1623 // ensure that we can fold all uses of a potential addressing computation
1624 // into their uses. TODO: generalize this to work over profiling data
1625 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
1626 for (auto &Arg : CI->arg_operands()) {
1627 if (!Arg->getType()->isPointerTy())
1628 continue;
1629 unsigned AS = Arg->getType()->getPointerAddressSpace();
1630 return optimizeMemoryInst(CI, Arg, Arg->getType(), AS);
1631 }
Junmo Park6098cbb2016-03-11 07:05:32 +00001632
Eric Christopher4b7948e2010-03-11 02:41:03 +00001633 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001634 if (II) {
1635 switch (II->getIntrinsicID()) {
1636 default: break;
1637 case Intrinsic::objectsize: {
1638 // Lower all uses of llvm.objectsize.*
George Burgess IV3f089142016-12-20 23:46:36 +00001639 ConstantInt *RetVal =
1640 lowerObjectSizeCall(II, *DL, TLInfo, /*MustSucceed=*/true);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001641 // Substituting this can cause recursive simplifications, which can
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00001642 // invalidate our iterator. Use a WeakTrackingVH to hold onto it in case
1643 // this
Sanjoy Das2cbeb002017-04-26 16:37:05 +00001644 // happens.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00001645 Value *CurValue = &*CurInstIterator;
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00001646 WeakTrackingVH IterHandle(CurValue);
Nadav Rotem465834c2012-07-24 10:51:42 +00001647
Sanjay Patel545a4562016-01-20 18:59:16 +00001648 replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
Chris Lattner1b93be52011-01-15 07:25:29 +00001649
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001650 // If the iterator instruction was recursively deleted, start over at the
1651 // start of the block.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00001652 if (IterHandle != CurValue) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001653 CurInstIterator = BB->begin();
1654 SunkAddrs.clear();
1655 }
1656 return true;
Chris Lattner86d56c62011-01-18 20:53:04 +00001657 }
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001658 case Intrinsic::aarch64_stlxr:
1659 case Intrinsic::aarch64_stxr: {
1660 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
1661 if (!ExtVal || !ExtVal->hasOneUse() ||
1662 ExtVal->getParent() == CI->getParent())
1663 return false;
1664 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
1665 ExtVal->moveBefore(CI);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00001666 // Mark this instruction as "inserted by CGP", so that other
1667 // optimizations don't touch it.
1668 InsertedInsts.insert(ExtVal);
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001669 return true;
1670 }
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00001671 case Intrinsic::invariant_group_barrier:
1672 II->replaceAllUsesWith(II->getArgOperand(0));
1673 II->eraseFromParent();
1674 return true;
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001675
1676 case Intrinsic::cttz:
1677 case Intrinsic::ctlz:
1678 // If counting zeros is expensive, try to avoid it.
1679 return despeculateCountZeros(II, TLI, DL, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001680 }
Eric Christopher4b7948e2010-03-11 02:41:03 +00001681
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001682 if (TLI) {
1683 SmallVector<Value*, 2> PtrOps;
1684 Type *AccessTy;
Matt Arsenault1672b1b2017-02-08 07:09:03 +00001685 if (TLI->getAddrModeArguments(II, PtrOps, AccessTy))
1686 while (!PtrOps.empty()) {
1687 Value *PtrVal = PtrOps.pop_back_val();
1688 unsigned AS = PtrVal->getType()->getPointerAddressSpace();
1689 if (optimizeMemoryInst(II, PtrVal, AccessTy, AS))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001690 return true;
Matt Arsenault1672b1b2017-02-08 07:09:03 +00001691 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001692 }
Pete Cooper615fd892012-03-13 20:59:56 +00001693 }
1694
Eric Christopher4b7948e2010-03-11 02:41:03 +00001695 // From here on out we're working with named functions.
Craig Topperc0196b12014-04-14 00:51:57 +00001696 if (!CI->getCalledFunction()) return false;
Devang Patel0da52502011-05-26 21:51:06 +00001697
Benjamin Kramer7b88a492010-03-12 09:27:41 +00001698 // Lower all default uses of _chk calls. This is very similar
1699 // to what InstCombineCalls does, but here we are only lowering calls
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001700 // to fortified library functions (e.g. __memcpy_chk) that have the default
1701 // "don't know" as the objectsize. Anything else should be left alone.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001702 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001703 if (Value *V = Simplifier.optimizeCall(CI)) {
1704 CI->replaceAllUsesWith(V);
1705 CI->eraseFromParent();
1706 return true;
1707 }
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001708
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001709 return false;
Eric Christopher4b7948e2010-03-11 02:41:03 +00001710}
Chris Lattner1b93be52011-01-15 07:25:29 +00001711
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001712/// Look for opportunities to duplicate return instructions to the predecessor
1713/// to enable tail call optimizations. The case it is currently looking for is:
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001714/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001715/// bb0:
1716/// %tmp0 = tail call i32 @f0()
1717/// br label %return
1718/// bb1:
1719/// %tmp1 = tail call i32 @f1()
1720/// br label %return
1721/// bb2:
1722/// %tmp2 = tail call i32 @f2()
1723/// br label %return
1724/// return:
1725/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
1726/// ret i32 %retval
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001727/// @endcode
Evan Cheng0663f232011-03-21 01:19:09 +00001728///
1729/// =>
1730///
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001731/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001732/// bb0:
1733/// %tmp0 = tail call i32 @f0()
1734/// ret i32 %tmp0
1735/// bb1:
1736/// %tmp1 = tail call i32 @f1()
1737/// ret i32 %tmp1
1738/// bb2:
1739/// %tmp2 = tail call i32 @f2()
1740/// ret i32 %tmp2
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001741/// @endcode
Sanjay Patelfc580a62015-09-21 23:03:16 +00001742bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich47e71752011-03-24 04:51:51 +00001743 if (!TLI)
1744 return false;
1745
Michael Kuperstein71321562016-09-07 20:29:49 +00001746 ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator());
1747 if (!RetI)
Benjamin Kramer455fa352012-11-23 19:17:06 +00001748 return false;
1749
Craig Topperc0196b12014-04-14 00:51:57 +00001750 PHINode *PN = nullptr;
1751 BitCastInst *BCI = nullptr;
Michael Kuperstein71321562016-09-07 20:29:49 +00001752 Value *V = RetI->getReturnValue();
Evan Cheng249716e2012-07-27 21:21:26 +00001753 if (V) {
1754 BCI = dyn_cast<BitCastInst>(V);
1755 if (BCI)
1756 V = BCI->getOperand(0);
1757
1758 PN = dyn_cast<PHINode>(V);
1759 if (!PN)
1760 return false;
1761 }
Evan Cheng0663f232011-03-21 01:19:09 +00001762
Cameron Zwarich4649f172011-03-24 04:52:10 +00001763 if (PN && PN->getParent() != BB)
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001764 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00001765
Cameron Zwarich4649f172011-03-24 04:52:10 +00001766 // Make sure there are no instructions between the PHI and return, or that the
1767 // return is the first instruction in the block.
1768 if (PN) {
1769 BasicBlock::iterator BI = BB->begin();
1770 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng249716e2012-07-27 21:21:26 +00001771 if (&*BI == BCI)
1772 // Also skip over the bitcast.
1773 ++BI;
Michael Kuperstein71321562016-09-07 20:29:49 +00001774 if (&*BI != RetI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001775 return false;
1776 } else {
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001777 BasicBlock::iterator BI = BB->begin();
1778 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
Michael Kuperstein71321562016-09-07 20:29:49 +00001779 if (&*BI != RetI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001780 return false;
1781 }
Evan Cheng0663f232011-03-21 01:19:09 +00001782
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001783 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
1784 /// call.
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00001785 const Function *F = BB->getParent();
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001786 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich4649f172011-03-24 04:52:10 +00001787 if (PN) {
1788 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
1789 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
1790 // Make sure the phi value is indeed produced by the tail call.
1791 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00001792 TLI->mayBeEmittedAsTailCall(CI) &&
1793 attributesPermitTailCall(F, CI, RetI, *TLI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00001794 TailCalls.push_back(CI);
1795 }
1796 } else {
1797 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001798 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
David Blaikie70573dc2014-11-19 07:49:26 +00001799 if (!VisitedBBs.insert(*PI).second)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001800 continue;
1801
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001802 BasicBlock::InstListType &InstList = (*PI)->getInstList();
Cameron Zwarich4649f172011-03-24 04:52:10 +00001803 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
1804 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001805 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
1806 if (RI == RE)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001807 continue;
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001808
Cameron Zwarich4649f172011-03-24 04:52:10 +00001809 CallInst *CI = dyn_cast<CallInst>(&*RI);
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00001810 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI) &&
1811 attributesPermitTailCall(F, CI, RetI, *TLI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00001812 TailCalls.push_back(CI);
1813 }
Evan Cheng0663f232011-03-21 01:19:09 +00001814 }
1815
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001816 bool Changed = false;
1817 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
1818 CallInst *CI = TailCalls[i];
1819 CallSite CS(CI);
1820
1821 // Conservatively require the attributes of the call to match those of the
1822 // return. Ignore noalias because it doesn't affect the call sequence.
Reid Klecknerb5180542017-03-21 16:57:19 +00001823 AttributeList CalleeAttrs = CS.getAttributes();
1824 if (AttrBuilder(CalleeAttrs, AttributeList::ReturnIndex)
1825 .removeAttribute(Attribute::NoAlias) !=
1826 AttrBuilder(CalleeAttrs, AttributeList::ReturnIndex)
1827 .removeAttribute(Attribute::NoAlias))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001828 continue;
1829
1830 // Make sure the call instruction is followed by an unconditional branch to
1831 // the return block.
1832 BasicBlock *CallBB = CI->getParent();
1833 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
1834 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
1835 continue;
1836
1837 // Duplicate the return into CallBB.
Michael Kuperstein71321562016-09-07 20:29:49 +00001838 (void)FoldReturnIntoUncondBranch(RetI, BB, CallBB);
Devang Patel8f606d72011-03-24 15:35:25 +00001839 ModifiedDT = Changed = true;
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001840 ++NumRetsDup;
1841 }
1842
1843 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng64a223a2012-09-28 23:58:57 +00001844 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001845 BB->eraseFromParent();
1846
1847 return Changed;
Evan Cheng0663f232011-03-21 01:19:09 +00001848}
1849
Chris Lattner728f9022008-11-25 07:09:13 +00001850//===----------------------------------------------------------------------===//
Chris Lattner728f9022008-11-25 07:09:13 +00001851// Memory Optimization
1852//===----------------------------------------------------------------------===//
1853
Chandler Carruthc8925912013-01-05 02:09:22 +00001854namespace {
1855
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001856/// This is an extended version of TargetLowering::AddrMode
Chandler Carruthc8925912013-01-05 02:09:22 +00001857/// which holds actual Value*'s for register values.
Chandler Carruth95f83e02013-01-07 15:14:13 +00001858struct ExtAddrMode : public TargetLowering::AddrMode {
Eugene Zelenko900b6332017-08-29 22:32:07 +00001859 Value *BaseReg = nullptr;
1860 Value *ScaledReg = nullptr;
John Brawn736bf002017-10-03 13:08:22 +00001861 Value *OriginalValue = nullptr;
1862
1863 enum FieldName {
1864 NoField = 0x00,
1865 BaseRegField = 0x01,
1866 BaseGVField = 0x02,
1867 BaseOffsField = 0x04,
1868 ScaledRegField = 0x08,
1869 ScaleField = 0x10,
1870 MultipleFields = 0xff
1871 };
Eugene Zelenko900b6332017-08-29 22:32:07 +00001872
1873 ExtAddrMode() = default;
1874
Chandler Carruthc8925912013-01-05 02:09:22 +00001875 void print(raw_ostream &OS) const;
1876 void dump() const;
Stephen Lin837bba12013-07-15 17:55:02 +00001877
John Brawn736bf002017-10-03 13:08:22 +00001878 FieldName compare(const ExtAddrMode &other) {
1879 // First check that the types are the same on each field, as differing types
1880 // is something we can't cope with later on.
1881 if (BaseReg && other.BaseReg &&
1882 BaseReg->getType() != other.BaseReg->getType())
1883 return MultipleFields;
1884 if (BaseGV && other.BaseGV &&
1885 BaseGV->getType() != other.BaseGV->getType())
1886 return MultipleFields;
1887 if (ScaledReg && other.ScaledReg &&
1888 ScaledReg->getType() != other.ScaledReg->getType())
1889 return MultipleFields;
1890
1891 // Check each field to see if it differs.
1892 unsigned Result = NoField;
1893 if (BaseReg != other.BaseReg)
1894 Result |= BaseRegField;
1895 if (BaseGV != other.BaseGV)
1896 Result |= BaseGVField;
1897 if (BaseOffs != other.BaseOffs)
1898 Result |= BaseOffsField;
1899 if (ScaledReg != other.ScaledReg)
1900 Result |= ScaledRegField;
1901 // Don't count 0 as being a different scale, because that actually means
1902 // unscaled (which will already be counted by having no ScaledReg).
1903 if (Scale && other.Scale && Scale != other.Scale)
1904 Result |= ScaleField;
1905
1906 if (countPopulation(Result) > 1)
1907 return MultipleFields;
1908 else
1909 return static_cast<FieldName>(Result);
1910 }
1911
John Brawn4b476482017-11-27 11:29:15 +00001912 // An AddrMode is trivial if it involves no calculation i.e. it is just a base
1913 // with no offset.
John Brawn736bf002017-10-03 13:08:22 +00001914 bool isTrivial() {
John Brawn4b476482017-11-27 11:29:15 +00001915 // An AddrMode is (BaseGV + BaseReg + BaseOffs + ScaleReg * Scale) so it is
1916 // trivial if at most one of these terms is nonzero, except that BaseGV and
1917 // BaseReg both being zero actually means a null pointer value, which we
1918 // consider to be 'non-zero' here.
1919 return !BaseOffs && !Scale && !(BaseGV && BaseReg);
Chandler Carruthc8925912013-01-05 02:09:22 +00001920 }
John Brawn70cdb5b2017-11-24 14:10:45 +00001921
1922 Value *GetFieldAsValue(FieldName Field, Type *IntPtrTy) {
1923 switch (Field) {
1924 default:
1925 return nullptr;
1926 case BaseRegField:
1927 return BaseReg;
1928 case BaseGVField:
1929 return BaseGV;
1930 case ScaledRegField:
1931 return ScaledReg;
1932 case BaseOffsField:
1933 return ConstantInt::get(IntPtrTy, BaseOffs);
1934 }
1935 }
1936
1937 void SetCombinedField(FieldName Field, Value *V,
1938 const SmallVectorImpl<ExtAddrMode> &AddrModes) {
1939 switch (Field) {
1940 default:
1941 llvm_unreachable("Unhandled fields are expected to be rejected earlier");
1942 break;
1943 case ExtAddrMode::BaseRegField:
1944 BaseReg = V;
1945 break;
1946 case ExtAddrMode::BaseGVField:
1947 // A combined BaseGV is an Instruction, not a GlobalValue, so it goes
1948 // in the BaseReg field.
1949 assert(BaseReg == nullptr);
1950 BaseReg = V;
1951 BaseGV = nullptr;
1952 break;
1953 case ExtAddrMode::ScaledRegField:
1954 ScaledReg = V;
1955 // If we have a mix of scaled and unscaled addrmodes then we want scale
1956 // to be the scale and not zero.
1957 if (!Scale)
1958 for (const ExtAddrMode &AM : AddrModes)
1959 if (AM.Scale) {
1960 Scale = AM.Scale;
1961 break;
1962 }
1963 break;
1964 case ExtAddrMode::BaseOffsField:
1965 // The offset is no longer a constant, so it goes in ScaledReg with a
1966 // scale of 1.
1967 assert(ScaledReg == nullptr);
1968 ScaledReg = V;
1969 Scale = 1;
1970 BaseOffs = 0;
1971 break;
1972 }
1973 }
Chandler Carruthc8925912013-01-05 02:09:22 +00001974};
1975
Eugene Zelenko900b6332017-08-29 22:32:07 +00001976} // end anonymous namespace
1977
Eli Friedmanc1f1f852013-09-10 23:09:24 +00001978#ifndef NDEBUG
1979static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
1980 AM.print(OS);
1981 return OS;
1982}
1983#endif
1984
Aaron Ballman615eb472017-10-15 14:32:27 +00001985#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruthc8925912013-01-05 02:09:22 +00001986void ExtAddrMode::print(raw_ostream &OS) const {
1987 bool NeedPlus = false;
1988 OS << "[";
1989 if (BaseGV) {
1990 OS << (NeedPlus ? " + " : "")
1991 << "GV:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001992 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00001993 NeedPlus = true;
1994 }
1995
Richard Trieuc0f91212014-05-30 03:15:17 +00001996 if (BaseOffs) {
1997 OS << (NeedPlus ? " + " : "")
1998 << BaseOffs;
1999 NeedPlus = true;
2000 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002001
2002 if (BaseReg) {
2003 OS << (NeedPlus ? " + " : "")
2004 << "Base:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002005 BaseReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002006 NeedPlus = true;
2007 }
2008 if (Scale) {
2009 OS << (NeedPlus ? " + " : "")
2010 << Scale << "*";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002011 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002012 }
2013
2014 OS << ']';
2015}
2016
Yaron Kereneb2a2542016-01-29 20:50:44 +00002017LLVM_DUMP_METHOD void ExtAddrMode::dump() const {
Chandler Carruthc8925912013-01-05 02:09:22 +00002018 print(dbgs());
2019 dbgs() << '\n';
2020}
2021#endif
2022
Eugene Zelenko900b6332017-08-29 22:32:07 +00002023namespace {
2024
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002025/// \brief This class provides transaction based operation on the IR.
2026/// Every change made through this class is recorded in the internal state and
2027/// can be undone (rollback) until commit is called.
2028class TypePromotionTransaction {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002029 /// \brief This represents the common interface of the individual transaction.
2030 /// Each class implements the logic for doing one specific modification on
2031 /// the IR via the TypePromotionTransaction.
2032 class TypePromotionAction {
2033 protected:
2034 /// The Instruction modified.
2035 Instruction *Inst;
2036
2037 public:
2038 /// \brief Constructor of the action.
2039 /// The constructor performs the related action on the IR.
2040 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
2041
Eugene Zelenko900b6332017-08-29 22:32:07 +00002042 virtual ~TypePromotionAction() = default;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002043
2044 /// \brief Undo the modification done by this action.
2045 /// When this method is called, the IR must be in the same state as it was
2046 /// before this action was applied.
2047 /// \pre Undoing the action works if and only if the IR is in the exact same
2048 /// state as it was directly after this action was applied.
2049 virtual void undo() = 0;
2050
2051 /// \brief Advocate every change made by this action.
2052 /// When the results on the IR of the action are to be kept, it is important
2053 /// to call this function, otherwise hidden information may be kept forever.
2054 virtual void commit() {
2055 // Nothing to be done, this action is not doing anything.
2056 }
2057 };
2058
2059 /// \brief Utility to remember the position of an instruction.
2060 class InsertionHandler {
2061 /// Position of an instruction.
2062 /// Either an instruction:
2063 /// - Is the first in a basic block: BB is used.
2064 /// - Has a previous instructon: PrevInst is used.
2065 union {
2066 Instruction *PrevInst;
2067 BasicBlock *BB;
2068 } Point;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002069
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002070 /// Remember whether or not the instruction had a previous instruction.
2071 bool HasPrevInstruction;
2072
2073 public:
2074 /// \brief Record the position of \p Inst.
2075 InsertionHandler(Instruction *Inst) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002076 BasicBlock::iterator It = Inst->getIterator();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002077 HasPrevInstruction = (It != (Inst->getParent()->begin()));
2078 if (HasPrevInstruction)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002079 Point.PrevInst = &*--It;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002080 else
2081 Point.BB = Inst->getParent();
2082 }
2083
2084 /// \brief Insert \p Inst at the recorded position.
2085 void insert(Instruction *Inst) {
2086 if (HasPrevInstruction) {
2087 if (Inst->getParent())
2088 Inst->removeFromParent();
2089 Inst->insertAfter(Point.PrevInst);
2090 } else {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002091 Instruction *Position = &*Point.BB->getFirstInsertionPt();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002092 if (Inst->getParent())
2093 Inst->moveBefore(Position);
2094 else
2095 Inst->insertBefore(Position);
2096 }
2097 }
2098 };
2099
2100 /// \brief Move an instruction before another.
2101 class InstructionMoveBefore : public TypePromotionAction {
2102 /// Original position of the instruction.
2103 InsertionHandler Position;
2104
2105 public:
2106 /// \brief Move \p Inst before \p Before.
2107 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
2108 : TypePromotionAction(Inst), Position(Inst) {
2109 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
2110 Inst->moveBefore(Before);
2111 }
2112
2113 /// \brief Move the instruction back to its original position.
Craig Topper4584cd52014-03-07 09:26:03 +00002114 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002115 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
2116 Position.insert(Inst);
2117 }
2118 };
2119
2120 /// \brief Set the operand of an instruction with a new value.
2121 class OperandSetter : public TypePromotionAction {
2122 /// Original operand of the instruction.
2123 Value *Origin;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002124
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002125 /// Index of the modified instruction.
2126 unsigned Idx;
2127
2128 public:
2129 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
2130 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
2131 : TypePromotionAction(Inst), Idx(Idx) {
2132 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
2133 << "for:" << *Inst << "\n"
2134 << "with:" << *NewVal << "\n");
2135 Origin = Inst->getOperand(Idx);
2136 Inst->setOperand(Idx, NewVal);
2137 }
2138
2139 /// \brief Restore the original value of the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002140 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002141 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
2142 << "for: " << *Inst << "\n"
2143 << "with: " << *Origin << "\n");
2144 Inst->setOperand(Idx, Origin);
2145 }
2146 };
2147
2148 /// \brief Hide the operands of an instruction.
2149 /// Do as if this instruction was not using any of its operands.
2150 class OperandsHider : public TypePromotionAction {
2151 /// The list of original operands.
2152 SmallVector<Value *, 4> OriginalValues;
2153
2154 public:
2155 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
2156 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
2157 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
2158 unsigned NumOpnds = Inst->getNumOperands();
2159 OriginalValues.reserve(NumOpnds);
2160 for (unsigned It = 0; It < NumOpnds; ++It) {
2161 // Save the current operand.
2162 Value *Val = Inst->getOperand(It);
2163 OriginalValues.push_back(Val);
2164 // Set a dummy one.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002165 // We could use OperandSetter here, but that would imply an overhead
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002166 // that we are not willing to pay.
2167 Inst->setOperand(It, UndefValue::get(Val->getType()));
2168 }
2169 }
2170
2171 /// \brief Restore the original list of uses.
Craig Topper4584cd52014-03-07 09:26:03 +00002172 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002173 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
2174 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
2175 Inst->setOperand(It, OriginalValues[It]);
2176 }
2177 };
2178
2179 /// \brief Build a truncate instruction.
2180 class TruncBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002181 Value *Val;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002182
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002183 public:
2184 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
2185 /// result.
2186 /// trunc Opnd to Ty.
2187 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
2188 IRBuilder<> Builder(Opnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00002189 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
2190 DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002191 }
2192
Quentin Colombetac55b152014-09-16 22:36:07 +00002193 /// \brief Get the built value.
2194 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002195
2196 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002197 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002198 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
2199 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2200 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002201 }
2202 };
2203
2204 /// \brief Build a sign extension instruction.
2205 class SExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002206 Value *Val;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002207
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002208 public:
2209 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
2210 /// result.
2211 /// sext Opnd to Ty.
2212 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002213 : TypePromotionAction(InsertPt) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002214 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002215 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
2216 DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002217 }
2218
Quentin Colombetac55b152014-09-16 22:36:07 +00002219 /// \brief Get the built value.
2220 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002221
2222 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002223 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002224 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
2225 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2226 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002227 }
2228 };
2229
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002230 /// \brief Build a zero extension instruction.
2231 class ZExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002232 Value *Val;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002233
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002234 public:
2235 /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
2236 /// result.
2237 /// zext Opnd to Ty.
2238 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002239 : TypePromotionAction(InsertPt) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002240 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002241 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
2242 DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002243 }
2244
Quentin Colombetac55b152014-09-16 22:36:07 +00002245 /// \brief Get the built value.
2246 Value *getBuiltValue() { return Val; }
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002247
2248 /// \brief Remove the built instruction.
2249 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002250 DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
2251 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2252 IVal->eraseFromParent();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002253 }
2254 };
2255
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002256 /// \brief Mutate an instruction to another type.
2257 class TypeMutator : public TypePromotionAction {
2258 /// Record the original type.
2259 Type *OrigTy;
2260
2261 public:
2262 /// \brief Mutate the type of \p Inst into \p NewTy.
2263 TypeMutator(Instruction *Inst, Type *NewTy)
2264 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
2265 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
2266 << "\n");
2267 Inst->mutateType(NewTy);
2268 }
2269
2270 /// \brief Mutate the instruction back to its original type.
Craig Topper4584cd52014-03-07 09:26:03 +00002271 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002272 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
2273 << "\n");
2274 Inst->mutateType(OrigTy);
2275 }
2276 };
2277
2278 /// \brief Replace the uses of an instruction by another instruction.
2279 class UsesReplacer : public TypePromotionAction {
2280 /// Helper structure to keep track of the replaced uses.
2281 struct InstructionAndIdx {
2282 /// The instruction using the instruction.
2283 Instruction *Inst;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002284
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002285 /// The index where this instruction is used for Inst.
2286 unsigned Idx;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002287
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002288 InstructionAndIdx(Instruction *Inst, unsigned Idx)
2289 : Inst(Inst), Idx(Idx) {}
2290 };
2291
2292 /// Keep track of the original uses (pair Instruction, Index).
2293 SmallVector<InstructionAndIdx, 4> OriginalUses;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002294
2295 using use_iterator = SmallVectorImpl<InstructionAndIdx>::iterator;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002296
2297 public:
2298 /// \brief Replace all the use of \p Inst by \p New.
2299 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
2300 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
2301 << "\n");
2302 // Record the original uses.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002303 for (Use &U : Inst->uses()) {
2304 Instruction *UserI = cast<Instruction>(U.getUser());
2305 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002306 }
2307 // Now, we can replace the uses.
2308 Inst->replaceAllUsesWith(New);
2309 }
2310
2311 /// \brief Reassign the original uses of Inst to Inst.
Craig Topper4584cd52014-03-07 09:26:03 +00002312 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002313 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
2314 for (use_iterator UseIt = OriginalUses.begin(),
2315 EndIt = OriginalUses.end();
2316 UseIt != EndIt; ++UseIt) {
2317 UseIt->Inst->setOperand(UseIt->Idx, Inst);
2318 }
2319 }
2320 };
2321
2322 /// \brief Remove an instruction from the IR.
2323 class InstructionRemover : public TypePromotionAction {
2324 /// Original position of the instruction.
2325 InsertionHandler Inserter;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002326
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002327 /// Helper structure to hide all the link to the instruction. In other
2328 /// words, this helps to do as if the instruction was removed.
2329 OperandsHider Hider;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002330
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002331 /// Keep track of the uses replaced, if any.
Eugene Zelenko900b6332017-08-29 22:32:07 +00002332 UsesReplacer *Replacer = nullptr;
2333
Jun Bum Limdee55652017-04-03 19:20:07 +00002334 /// Keep track of instructions removed.
2335 SetOfInstrs &RemovedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002336
2337 public:
2338 /// \brief Remove all reference of \p Inst and optinally replace all its
2339 /// uses with New.
Jun Bum Limdee55652017-04-03 19:20:07 +00002340 /// \p RemovedInsts Keep track of the instructions removed by this Action.
Craig Topperc0196b12014-04-14 00:51:57 +00002341 /// \pre If !Inst->use_empty(), then New != nullptr
Jun Bum Limdee55652017-04-03 19:20:07 +00002342 InstructionRemover(Instruction *Inst, SetOfInstrs &RemovedInsts,
2343 Value *New = nullptr)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002344 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
Eugene Zelenko900b6332017-08-29 22:32:07 +00002345 RemovedInsts(RemovedInsts) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002346 if (New)
2347 Replacer = new UsesReplacer(Inst, New);
2348 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
Jun Bum Limdee55652017-04-03 19:20:07 +00002349 RemovedInsts.insert(Inst);
2350 /// The instructions removed here will be freed after completing
2351 /// optimizeBlock() for all blocks as we need to keep track of the
2352 /// removed instructions during promotion.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002353 Inst->removeFromParent();
2354 }
2355
Alexander Kornienkof817c1c2015-04-11 02:11:45 +00002356 ~InstructionRemover() override { delete Replacer; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002357
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002358 /// \brief Resurrect the instruction and reassign it to the proper uses if
2359 /// new value was provided when build this action.
Craig Topper4584cd52014-03-07 09:26:03 +00002360 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002361 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
2362 Inserter.insert(Inst);
2363 if (Replacer)
2364 Replacer->undo();
2365 Hider.undo();
Jun Bum Limdee55652017-04-03 19:20:07 +00002366 RemovedInsts.erase(Inst);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002367 }
2368 };
2369
2370public:
2371 /// Restoration point.
2372 /// The restoration point is a pointer to an action instead of an iterator
2373 /// because the iterator may be invalidated but not the pointer.
Eugene Zelenko900b6332017-08-29 22:32:07 +00002374 using ConstRestorationPt = const TypePromotionAction *;
Jun Bum Limdee55652017-04-03 19:20:07 +00002375
2376 TypePromotionTransaction(SetOfInstrs &RemovedInsts)
2377 : RemovedInsts(RemovedInsts) {}
2378
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002379 /// Advocate every changes made in that transaction.
2380 void commit();
Eugene Zelenko900b6332017-08-29 22:32:07 +00002381
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002382 /// Undo all the changes made after the given point.
2383 void rollback(ConstRestorationPt Point);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002384
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002385 /// Get the current restoration point.
2386 ConstRestorationPt getRestorationPoint() const;
2387
2388 /// \name API for IR modification with state keeping to support rollback.
2389 /// @{
2390 /// Same as Instruction::setOperand.
2391 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002392
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002393 /// Same as Instruction::eraseFromParent.
Craig Topperc0196b12014-04-14 00:51:57 +00002394 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002395
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002396 /// Same as Value::replaceAllUsesWith.
2397 void replaceAllUsesWith(Instruction *Inst, Value *New);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002398
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002399 /// Same as Value::mutateType.
2400 void mutateType(Instruction *Inst, Type *NewTy);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002401
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002402 /// Same as IRBuilder::createTrunc.
Quentin Colombetac55b152014-09-16 22:36:07 +00002403 Value *createTrunc(Instruction *Opnd, Type *Ty);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002404
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002405 /// Same as IRBuilder::createSExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002406 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002407
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002408 /// Same as IRBuilder::createZExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002409 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002410
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002411 /// Same as Instruction::moveBefore.
2412 void moveBefore(Instruction *Inst, Instruction *Before);
2413 /// @}
2414
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002415private:
2416 /// The ordered list of actions made so far.
David Blaikie7620b312014-04-15 06:17:44 +00002417 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002418
2419 using CommitPt = SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator;
2420
Jun Bum Limdee55652017-04-03 19:20:07 +00002421 SetOfInstrs &RemovedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002422};
2423
Eugene Zelenko900b6332017-08-29 22:32:07 +00002424} // end anonymous namespace
2425
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002426void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
2427 Value *NewVal) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00002428 Actions.push_back(llvm::make_unique<TypePromotionTransaction::OperandSetter>(
2429 Inst, Idx, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002430}
2431
2432void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
2433 Value *NewVal) {
2434 Actions.push_back(
Eugene Zelenko900b6332017-08-29 22:32:07 +00002435 llvm::make_unique<TypePromotionTransaction::InstructionRemover>(
2436 Inst, RemovedInsts, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002437}
2438
2439void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
2440 Value *New) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00002441 Actions.push_back(
2442 llvm::make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002443}
2444
2445void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00002446 Actions.push_back(
2447 llvm::make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002448}
2449
Quentin Colombetac55b152014-09-16 22:36:07 +00002450Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
2451 Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002452 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002453 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002454 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002455 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002456}
2457
Quentin Colombetac55b152014-09-16 22:36:07 +00002458Value *TypePromotionTransaction::createSExt(Instruction *Inst,
2459 Value *Opnd, Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002460 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002461 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002462 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002463 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002464}
2465
Quentin Colombetac55b152014-09-16 22:36:07 +00002466Value *TypePromotionTransaction::createZExt(Instruction *Inst,
2467 Value *Opnd, Type *Ty) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002468 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002469 Value *Val = Ptr->getBuiltValue();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002470 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002471 return Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002472}
2473
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002474void TypePromotionTransaction::moveBefore(Instruction *Inst,
2475 Instruction *Before) {
2476 Actions.push_back(
Eugene Zelenko900b6332017-08-29 22:32:07 +00002477 llvm::make_unique<TypePromotionTransaction::InstructionMoveBefore>(
2478 Inst, Before));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002479}
2480
2481TypePromotionTransaction::ConstRestorationPt
2482TypePromotionTransaction::getRestorationPoint() const {
David Blaikie7620b312014-04-15 06:17:44 +00002483 return !Actions.empty() ? Actions.back().get() : nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002484}
2485
2486void TypePromotionTransaction::commit() {
2487 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
David Blaikie7620b312014-04-15 06:17:44 +00002488 ++It)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002489 (*It)->commit();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002490 Actions.clear();
2491}
2492
2493void TypePromotionTransaction::rollback(
2494 TypePromotionTransaction::ConstRestorationPt Point) {
David Blaikie7620b312014-04-15 06:17:44 +00002495 while (!Actions.empty() && Point != Actions.back().get()) {
2496 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002497 Curr->undo();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002498 }
2499}
2500
Eugene Zelenko900b6332017-08-29 22:32:07 +00002501namespace {
2502
Chandler Carruthc8925912013-01-05 02:09:22 +00002503/// \brief A helper class for matching addressing modes.
2504///
2505/// This encapsulates the logic for matching the target-legal addressing modes.
2506class AddressingModeMatcher {
2507 SmallVectorImpl<Instruction*> &AddrModeInsts;
2508 const TargetLowering &TLI;
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002509 const TargetRegisterInfo &TRI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00002510 const DataLayout &DL;
Chandler Carruthc8925912013-01-05 02:09:22 +00002511
2512 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
2513 /// the memory instruction that we're computing this address for.
2514 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002515 unsigned AddrSpace;
Chandler Carruthc8925912013-01-05 02:09:22 +00002516 Instruction *MemoryInst;
Stephen Lin837bba12013-07-15 17:55:02 +00002517
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002518 /// This is the addressing mode that we're building up. This is
Chandler Carruthc8925912013-01-05 02:09:22 +00002519 /// part of the return value of this addressing mode matching stuff.
2520 ExtAddrMode &AddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002521
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002522 /// The instructions inserted by other CodeGenPrepare optimizations.
2523 const SetOfInstrs &InsertedInsts;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002524
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002525 /// A map from the instructions to their type before promotion.
2526 InstrToOrigTy &PromotedInsts;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002527
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002528 /// The ongoing transaction where every action should be registered.
2529 TypePromotionTransaction &TPT;
2530
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002531 /// This is set to true when we should not do profitability checks.
2532 /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
Chandler Carruthc8925912013-01-05 02:09:22 +00002533 bool IgnoreProfitability;
Stephen Lin837bba12013-07-15 17:55:02 +00002534
Eric Christopherd75c00c2015-02-26 22:38:34 +00002535 AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI,
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002536 const TargetLowering &TLI,
2537 const TargetRegisterInfo &TRI,
2538 Type *AT, unsigned AS,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002539 Instruction *MI, ExtAddrMode &AM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002540 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002541 InstrToOrigTy &PromotedInsts,
2542 TypePromotionTransaction &TPT)
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002543 : AddrModeInsts(AMI), TLI(TLI), TRI(TRI),
Mehdi Amini4fe37982015-07-07 18:45:17 +00002544 DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
2545 MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
2546 PromotedInsts(PromotedInsts), TPT(TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002547 IgnoreProfitability = false;
2548 }
Stephen Lin837bba12013-07-15 17:55:02 +00002549
Eugene Zelenko900b6332017-08-29 22:32:07 +00002550public:
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002551 /// Find the maximal addressing mode that a load/store of V can fold,
Chandler Carruthc8925912013-01-05 02:09:22 +00002552 /// give an access type of AccessTy. This returns a list of involved
2553 /// instructions in AddrModeInsts.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002554 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002555 /// optimizations.
2556 /// \p PromotedInsts maps the instructions to their type before promotion.
2557 /// \p The ongoing transaction where every action should be registered.
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002558 static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS,
Chandler Carruthc8925912013-01-05 02:09:22 +00002559 Instruction *MemoryInst,
2560 SmallVectorImpl<Instruction*> &AddrModeInsts,
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002561 const TargetLowering &TLI,
2562 const TargetRegisterInfo &TRI,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002563 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002564 InstrToOrigTy &PromotedInsts,
2565 TypePromotionTransaction &TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002566 ExtAddrMode Result;
2567
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002568 bool Success = AddressingModeMatcher(AddrModeInsts, TLI, TRI,
2569 AccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002570 MemoryInst, Result, InsertedInsts,
Sanjay Patelfc580a62015-09-21 23:03:16 +00002571 PromotedInsts, TPT).matchAddr(V, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00002572 (void)Success; assert(Success && "Couldn't select *anything*?");
2573 return Result;
2574 }
Eugene Zelenko900b6332017-08-29 22:32:07 +00002575
Chandler Carruthc8925912013-01-05 02:09:22 +00002576private:
Sanjay Patelfc580a62015-09-21 23:03:16 +00002577 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
2578 bool matchAddr(Value *V, unsigned Depth);
2579 bool matchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
Craig Topperc0196b12014-04-14 00:51:57 +00002580 bool *MovedAway = nullptr);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002581 bool isProfitableToFoldIntoAddressingMode(Instruction *I,
Chandler Carruthc8925912013-01-05 02:09:22 +00002582 ExtAddrMode &AMBefore,
2583 ExtAddrMode &AMAfter);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002584 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
2585 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
Quentin Colombet867c5502014-02-14 22:23:22 +00002586 Value *PromotedOperand) const;
Chandler Carruthc8925912013-01-05 02:09:22 +00002587};
2588
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002589/// \brief Keep track of simplification of Phi nodes.
2590/// Accept the set of all phi nodes and erase phi node from this set
2591/// if it is simplified.
2592class SimplificationTracker {
2593 DenseMap<Value *, Value *> Storage;
2594 const SimplifyQuery &SQ;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002595 // Tracks newly created Phi nodes. We use a SetVector to get deterministic
2596 // order when iterating over the set in MatchPhiSet.
2597 SmallSetVector<PHINode *, 32> AllPhiNodes;
2598 // Tracks newly created Select nodes.
2599 SmallPtrSet<SelectInst *, 32> AllSelectNodes;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002600
2601public:
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002602 SimplificationTracker(const SimplifyQuery &sq)
2603 : SQ(sq) {}
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002604
2605 Value *Get(Value *V) {
2606 do {
2607 auto SV = Storage.find(V);
2608 if (SV == Storage.end())
2609 return V;
2610 V = SV->second;
2611 } while (true);
2612 }
2613
2614 Value *Simplify(Value *Val) {
2615 SmallVector<Value *, 32> WorkList;
2616 SmallPtrSet<Value *, 32> Visited;
2617 WorkList.push_back(Val);
2618 while (!WorkList.empty()) {
2619 auto P = WorkList.pop_back_val();
2620 if (!Visited.insert(P).second)
2621 continue;
2622 if (auto *PI = dyn_cast<Instruction>(P))
2623 if (Value *V = SimplifyInstruction(cast<Instruction>(PI), SQ)) {
2624 for (auto *U : PI->users())
2625 WorkList.push_back(cast<Value>(U));
2626 Put(PI, V);
2627 PI->replaceAllUsesWith(V);
2628 if (auto *PHI = dyn_cast<PHINode>(PI))
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002629 AllPhiNodes.remove(PHI);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002630 if (auto *Select = dyn_cast<SelectInst>(PI))
2631 AllSelectNodes.erase(Select);
2632 PI->eraseFromParent();
2633 }
2634 }
2635 return Get(Val);
2636 }
2637
2638 void Put(Value *From, Value *To) {
2639 Storage.insert({ From, To });
2640 }
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002641
2642 void ReplacePhi(PHINode *From, PHINode *To) {
2643 Value* OldReplacement = Get(From);
2644 while (OldReplacement != From) {
2645 From = To;
2646 To = dyn_cast<PHINode>(OldReplacement);
2647 OldReplacement = Get(From);
2648 }
2649 assert(Get(To) == To && "Replacement PHI node is already replaced.");
2650 Put(From, To);
2651 From->replaceAllUsesWith(To);
2652 AllPhiNodes.remove(From);
2653 From->eraseFromParent();
2654 }
2655
2656 SmallSetVector<PHINode *, 32>& newPhiNodes() { return AllPhiNodes; }
2657
2658 void insertNewPhi(PHINode *PN) { AllPhiNodes.insert(PN); }
2659
2660 void insertNewSelect(SelectInst *SI) { AllSelectNodes.insert(SI); }
2661
2662 unsigned countNewPhiNodes() const { return AllPhiNodes.size(); }
2663
2664 unsigned countNewSelectNodes() const { return AllSelectNodes.size(); }
2665
2666 void destroyNewNodes(Type *CommonType) {
2667 // For safe erasing, replace the uses with dummy value first.
2668 auto Dummy = UndefValue::get(CommonType);
2669 for (auto I : AllPhiNodes) {
2670 I->replaceAllUsesWith(Dummy);
2671 I->eraseFromParent();
2672 }
2673 AllPhiNodes.clear();
2674 for (auto I : AllSelectNodes) {
2675 I->replaceAllUsesWith(Dummy);
2676 I->eraseFromParent();
2677 }
2678 AllSelectNodes.clear();
2679 }
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002680};
2681
John Brawn736bf002017-10-03 13:08:22 +00002682/// \brief A helper class for combining addressing modes.
2683class AddressingModeCombiner {
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002684 typedef std::pair<Value *, BasicBlock *> ValueInBB;
2685 typedef DenseMap<ValueInBB, Value *> FoldAddrToValueMapping;
2686 typedef std::pair<PHINode *, PHINode *> PHIPair;
2687
John Brawn736bf002017-10-03 13:08:22 +00002688private:
2689 /// The addressing modes we've collected.
2690 SmallVector<ExtAddrMode, 16> AddrModes;
2691
2692 /// The field in which the AddrModes differ, when we have more than one.
2693 ExtAddrMode::FieldName DifferentField = ExtAddrMode::NoField;
2694
2695 /// Are the AddrModes that we have all just equal to their original values?
2696 bool AllAddrModesTrivial = true;
2697
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002698 /// Common Type for all different fields in addressing modes.
2699 Type *CommonType;
2700
2701 /// SimplifyQuery for simplifyInstruction utility.
2702 const SimplifyQuery &SQ;
2703
2704 /// Original Address.
2705 ValueInBB Original;
2706
John Brawn736bf002017-10-03 13:08:22 +00002707public:
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002708 AddressingModeCombiner(const SimplifyQuery &_SQ, ValueInBB OriginalValue)
2709 : CommonType(nullptr), SQ(_SQ), Original(OriginalValue) {}
2710
John Brawn736bf002017-10-03 13:08:22 +00002711 /// \brief Get the combined AddrMode
2712 const ExtAddrMode &getAddrMode() const {
2713 return AddrModes[0];
2714 }
2715
2716 /// \brief Add a new AddrMode if it's compatible with the AddrModes we already
2717 /// have.
2718 /// \return True iff we succeeded in doing so.
2719 bool addNewAddrMode(ExtAddrMode &NewAddrMode) {
2720 // Take note of if we have any non-trivial AddrModes, as we need to detect
2721 // when all AddrModes are trivial as then we would introduce a phi or select
2722 // which just duplicates what's already there.
2723 AllAddrModesTrivial = AllAddrModesTrivial && NewAddrMode.isTrivial();
2724
2725 // If this is the first addrmode then everything is fine.
2726 if (AddrModes.empty()) {
2727 AddrModes.emplace_back(NewAddrMode);
2728 return true;
2729 }
2730
2731 // Figure out how different this is from the other address modes, which we
2732 // can do just by comparing against the first one given that we only care
2733 // about the cumulative difference.
2734 ExtAddrMode::FieldName ThisDifferentField =
2735 AddrModes[0].compare(NewAddrMode);
2736 if (DifferentField == ExtAddrMode::NoField)
2737 DifferentField = ThisDifferentField;
2738 else if (DifferentField != ThisDifferentField)
2739 DifferentField = ExtAddrMode::MultipleFields;
2740
Serguei Katkov17e57942018-01-23 12:07:49 +00002741 // If NewAddrMode differs in more than one dimension we cannot handle it.
2742 bool CanHandle = DifferentField != ExtAddrMode::MultipleFields;
2743
2744 // If Scale Field is different then we reject.
2745 CanHandle = CanHandle && DifferentField != ExtAddrMode::ScaleField;
2746
Serguei Katkov4d1dd6b2018-01-09 04:37:06 +00002747 // We also must reject the case when base offset is different and
2748 // scale reg is not null, we cannot handle this case due to merge of
2749 // different offsets will be used as ScaleReg.
Serguei Katkov17e57942018-01-23 12:07:49 +00002750 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseOffsField ||
2751 !NewAddrMode.ScaledReg);
John Brawn736bf002017-10-03 13:08:22 +00002752
Serguei Katkov17e57942018-01-23 12:07:49 +00002753 // We also must reject the case when GV is different and BaseReg installed
2754 // due to we want to use base reg as a merge of GV values.
2755 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseGVField ||
2756 !NewAddrMode.HasBaseReg);
2757
2758 // Even if NewAddMode is the same we still need to collect it due to
2759 // original value is different. And later we will need all original values
2760 // as anchors during finding the common Phi node.
2761 if (CanHandle)
2762 AddrModes.emplace_back(NewAddrMode);
2763 else
2764 AddrModes.clear();
2765
2766 return CanHandle;
John Brawn736bf002017-10-03 13:08:22 +00002767 }
2768
2769 /// \brief Combine the addressing modes we've collected into a single
2770 /// addressing mode.
2771 /// \return True iff we successfully combined them or we only had one so
2772 /// didn't need to combine them anyway.
2773 bool combineAddrModes() {
2774 // If we have no AddrModes then they can't be combined.
2775 if (AddrModes.size() == 0)
2776 return false;
2777
2778 // A single AddrMode can trivially be combined.
Serguei Katkov505359f2017-11-20 05:42:36 +00002779 if (AddrModes.size() == 1 || DifferentField == ExtAddrMode::NoField)
John Brawn736bf002017-10-03 13:08:22 +00002780 return true;
2781
2782 // If the AddrModes we collected are all just equal to the value they are
2783 // derived from then combining them wouldn't do anything useful.
2784 if (AllAddrModesTrivial)
2785 return false;
2786
John Brawn70cdb5b2017-11-24 14:10:45 +00002787 if (!addrModeCombiningAllowed())
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002788 return false;
2789
2790 // Build a map between <original value, basic block where we saw it> to
2791 // value of base register.
Serguei Katkov50364592017-11-29 05:51:26 +00002792 // Bail out if there is no common type.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002793 FoldAddrToValueMapping Map;
Serguei Katkov50364592017-11-29 05:51:26 +00002794 if (!initializeMap(Map))
2795 return false;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002796
2797 Value *CommonValue = findCommon(Map);
2798 if (CommonValue)
John Brawn70cdb5b2017-11-24 14:10:45 +00002799 AddrModes[0].SetCombinedField(DifferentField, CommonValue, AddrModes);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002800 return CommonValue != nullptr;
2801 }
2802
2803private:
2804 /// \brief Initialize Map with anchor values. For address seen in some BB
2805 /// we set the value of different field saw in this address.
2806 /// If address is not an instruction than basic block is set to null.
2807 /// At the same time we find a common type for different field we will
2808 /// use to create new Phi/Select nodes. Keep it in CommonType field.
Serguei Katkov50364592017-11-29 05:51:26 +00002809 /// Return false if there is no common type found.
2810 bool initializeMap(FoldAddrToValueMapping &Map) {
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002811 // Keep track of keys where the value is null. We will need to replace it
2812 // with constant null when we know the common type.
2813 SmallVector<ValueInBB, 2> NullValue;
John Brawn70cdb5b2017-11-24 14:10:45 +00002814 Type *IntPtrTy = SQ.DL.getIntPtrType(AddrModes[0].OriginalValue->getType());
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002815 for (auto &AM : AddrModes) {
2816 BasicBlock *BB = nullptr;
2817 if (Instruction *I = dyn_cast<Instruction>(AM.OriginalValue))
2818 BB = I->getParent();
2819
John Brawn70cdb5b2017-11-24 14:10:45 +00002820 Value *DV = AM.GetFieldAsValue(DifferentField, IntPtrTy);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002821 if (DV) {
Serguei Katkov50364592017-11-29 05:51:26 +00002822 auto *Type = DV->getType();
2823 if (CommonType && CommonType != Type)
2824 return false;
2825 CommonType = Type;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002826 Map[{ AM.OriginalValue, BB }] = DV;
2827 } else {
2828 NullValue.push_back({ AM.OriginalValue, BB });
2829 }
2830 }
2831 assert(CommonType && "At least one non-null value must be!");
2832 for (auto VIBB : NullValue)
2833 Map[VIBB] = Constant::getNullValue(CommonType);
Serguei Katkov50364592017-11-29 05:51:26 +00002834 return true;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002835 }
2836
2837 /// \brief We have mapping between value A and basic block where value A
2838 /// seen to other value B where B was a field in addressing mode represented
2839 /// by A. Also we have an original value C representin an address in some
2840 /// basic block. Traversing from C through phi and selects we ended up with
2841 /// A's in a map. This utility function tries to find a value V which is a
2842 /// field in addressing mode C and traversing through phi nodes and selects
2843 /// we will end up in corresponded values B in a map.
2844 /// The utility will create a new Phi/Selects if needed.
2845 // The simple example looks as follows:
2846 // BB1:
2847 // p1 = b1 + 40
2848 // br cond BB2, BB3
2849 // BB2:
2850 // p2 = b2 + 40
2851 // br BB3
2852 // BB3:
2853 // p = phi [p1, BB1], [p2, BB2]
2854 // v = load p
2855 // Map is
2856 // <p1, BB1> -> b1
2857 // <p2, BB2> -> b2
2858 // Request is
2859 // <p, BB3> -> ?
2860 // The function tries to find or build phi [b1, BB1], [b2, BB2] in BB3
2861 Value *findCommon(FoldAddrToValueMapping &Map) {
Eric Christopherd72f78e2018-01-09 23:25:38 +00002862 // Tracks the simplification of newly created phi nodes. The reason we use
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002863 // this mapping is because we will add new created Phi nodes in AddrToBase.
2864 // Simplification of Phi nodes is recursive, so some Phi node may
2865 // be simplified after we added it to AddrToBase.
2866 // Using this mapping we can find the current value in AddrToBase.
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002867 SimplificationTracker ST(SQ);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002868
2869 // First step, DFS to create PHI nodes for all intermediate blocks.
2870 // Also fill traverse order for the second step.
2871 SmallVector<ValueInBB, 32> TraverseOrder;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002872 InsertPlaceholders(Map, TraverseOrder, ST);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002873
2874 // Second Step, fill new nodes by merged values and simplify if possible.
2875 FillPlaceholders(Map, TraverseOrder, ST);
2876
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002877 if (!AddrSinkNewSelects && ST.countNewSelectNodes() > 0) {
2878 ST.destroyNewNodes(CommonType);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002879 return nullptr;
2880 }
2881
2882 // Now we'd like to match New Phi nodes to existed ones.
2883 unsigned PhiNotMatchedCount = 0;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002884 if (!MatchPhiSet(ST, AddrSinkNewPhis, PhiNotMatchedCount)) {
2885 ST.destroyNewNodes(CommonType);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002886 return nullptr;
2887 }
2888
2889 auto *Result = ST.Get(Map.find(Original)->second);
2890 if (Result) {
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002891 NumMemoryInstsPhiCreated += ST.countNewPhiNodes() + PhiNotMatchedCount;
2892 NumMemoryInstsSelectCreated += ST.countNewSelectNodes();
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002893 }
2894 return Result;
2895 }
2896
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002897 /// \brief Try to match PHI node to Candidate.
2898 /// Matcher tracks the matched Phi nodes.
2899 bool MatchPhiNode(PHINode *PHI, PHINode *Candidate,
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002900 SmallSetVector<PHIPair, 8> &Matcher,
2901 SmallSetVector<PHINode *, 32> &PhiNodesToMatch) {
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002902 SmallVector<PHIPair, 8> WorkList;
2903 Matcher.insert({ PHI, Candidate });
2904 WorkList.push_back({ PHI, Candidate });
2905 SmallSet<PHIPair, 8> Visited;
2906 while (!WorkList.empty()) {
2907 auto Item = WorkList.pop_back_val();
2908 if (!Visited.insert(Item).second)
2909 continue;
2910 // We iterate over all incoming values to Phi to compare them.
2911 // If values are different and both of them Phi and the first one is a
2912 // Phi we added (subject to match) and both of them is in the same basic
2913 // block then we can match our pair if values match. So we state that
2914 // these values match and add it to work list to verify that.
2915 for (auto B : Item.first->blocks()) {
2916 Value *FirstValue = Item.first->getIncomingValueForBlock(B);
2917 Value *SecondValue = Item.second->getIncomingValueForBlock(B);
2918 if (FirstValue == SecondValue)
2919 continue;
2920
2921 PHINode *FirstPhi = dyn_cast<PHINode>(FirstValue);
2922 PHINode *SecondPhi = dyn_cast<PHINode>(SecondValue);
2923
2924 // One of them is not Phi or
2925 // The first one is not Phi node from the set we'd like to match or
2926 // Phi nodes from different basic blocks then
2927 // we will not be able to match.
2928 if (!FirstPhi || !SecondPhi || !PhiNodesToMatch.count(FirstPhi) ||
2929 FirstPhi->getParent() != SecondPhi->getParent())
2930 return false;
2931
2932 // If we already matched them then continue.
2933 if (Matcher.count({ FirstPhi, SecondPhi }))
2934 continue;
2935 // So the values are different and does not match. So we need them to
2936 // match.
2937 Matcher.insert({ FirstPhi, SecondPhi });
2938 // But me must check it.
2939 WorkList.push_back({ FirstPhi, SecondPhi });
2940 }
2941 }
2942 return true;
2943 }
2944
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002945 /// \brief For the given set of PHI nodes (in the SimplificationTracker) try
2946 /// to find their equivalents.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002947 /// Returns false if this matching fails and creation of new Phi is disabled.
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002948 bool MatchPhiSet(SimplificationTracker &ST, bool AllowNewPhiNodes,
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002949 unsigned &PhiNotMatchedCount) {
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002950 // Use a SetVector for Matched to make sure we do replacements (ReplacePhi)
2951 // in a deterministic order below.
2952 SmallSetVector<PHIPair, 8> Matched;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002953 SmallPtrSet<PHINode *, 8> WillNotMatch;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002954 SmallSetVector<PHINode *, 32> &PhiNodesToMatch = ST.newPhiNodes();
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002955 while (PhiNodesToMatch.size()) {
2956 PHINode *PHI = *PhiNodesToMatch.begin();
2957
2958 // Add us, if no Phi nodes in the basic block we do not match.
2959 WillNotMatch.clear();
2960 WillNotMatch.insert(PHI);
2961
2962 // Traverse all Phis until we found equivalent or fail to do that.
2963 bool IsMatched = false;
2964 for (auto &P : PHI->getParent()->phis()) {
2965 if (&P == PHI)
2966 continue;
2967 if ((IsMatched = MatchPhiNode(PHI, &P, Matched, PhiNodesToMatch)))
2968 break;
2969 // If it does not match, collect all Phi nodes from matcher.
2970 // if we end up with no match, them all these Phi nodes will not match
2971 // later.
2972 for (auto M : Matched)
2973 WillNotMatch.insert(M.first);
2974 Matched.clear();
2975 }
2976 if (IsMatched) {
Serguei Katkova20e05b2018-03-12 03:50:07 +00002977 // Replace all matched values and erase them.
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002978 for (auto MV : Matched)
2979 ST.ReplacePhi(MV.first, MV.second);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002980 Matched.clear();
2981 continue;
2982 }
2983 // If we are not allowed to create new nodes then bail out.
2984 if (!AllowNewPhiNodes)
2985 return false;
2986 // Just remove all seen values in matcher. They will not match anything.
2987 PhiNotMatchedCount += WillNotMatch.size();
2988 for (auto *P : WillNotMatch)
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002989 PhiNodesToMatch.remove(P);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002990 }
2991 return true;
2992 }
2993 /// \brief Fill the placeholder with values from predecessors and simplify it.
2994 void FillPlaceholders(FoldAddrToValueMapping &Map,
2995 SmallVectorImpl<ValueInBB> &TraverseOrder,
2996 SimplificationTracker &ST) {
2997 while (!TraverseOrder.empty()) {
2998 auto Current = TraverseOrder.pop_back_val();
2999 assert(Map.find(Current) != Map.end() && "No node to fill!!!");
3000 Value *CurrentValue = Current.first;
3001 BasicBlock *CurrentBlock = Current.second;
3002 Value *V = Map[Current];
3003
3004 if (SelectInst *Select = dyn_cast<SelectInst>(V)) {
3005 // CurrentValue also must be Select.
3006 auto *CurrentSelect = cast<SelectInst>(CurrentValue);
3007 auto *TrueValue = CurrentSelect->getTrueValue();
3008 ValueInBB TrueItem = { TrueValue, isa<Instruction>(TrueValue)
3009 ? CurrentBlock
3010 : nullptr };
3011 assert(Map.find(TrueItem) != Map.end() && "No True Value!");
Serguei Katkovb0b67a82017-12-18 04:25:07 +00003012 Select->setTrueValue(ST.Get(Map[TrueItem]));
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003013 auto *FalseValue = CurrentSelect->getFalseValue();
3014 ValueInBB FalseItem = { FalseValue, isa<Instruction>(FalseValue)
3015 ? CurrentBlock
3016 : nullptr };
3017 assert(Map.find(FalseItem) != Map.end() && "No False Value!");
Serguei Katkovb0b67a82017-12-18 04:25:07 +00003018 Select->setFalseValue(ST.Get(Map[FalseItem]));
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003019 } else {
3020 // Must be a Phi node then.
3021 PHINode *PHI = cast<PHINode>(V);
3022 // Fill the Phi node with values from predecessors.
3023 bool IsDefinedInThisBB =
3024 cast<Instruction>(CurrentValue)->getParent() == CurrentBlock;
3025 auto *CurrentPhi = dyn_cast<PHINode>(CurrentValue);
3026 for (auto B : predecessors(CurrentBlock)) {
3027 Value *PV = IsDefinedInThisBB
3028 ? CurrentPhi->getIncomingValueForBlock(B)
3029 : CurrentValue;
3030 ValueInBB item = { PV, isa<Instruction>(PV) ? B : nullptr };
3031 assert(Map.find(item) != Map.end() && "No predecessor Value!");
3032 PHI->addIncoming(ST.Get(Map[item]), B);
3033 }
3034 }
3035 // Simplify if possible.
3036 Map[Current] = ST.Simplify(V);
3037 }
3038 }
3039
3040 /// Starting from value recursively iterates over predecessors up to known
3041 /// ending values represented in a map. For each traversed block inserts
3042 /// a placeholder Phi or Select.
3043 /// Reports all new created Phi/Select nodes by adding them to set.
3044 /// Also reports and order in what basic blocks have been traversed.
3045 void InsertPlaceholders(FoldAddrToValueMapping &Map,
3046 SmallVectorImpl<ValueInBB> &TraverseOrder,
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003047 SimplificationTracker &ST) {
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003048 SmallVector<ValueInBB, 32> Worklist;
3049 assert((isa<PHINode>(Original.first) || isa<SelectInst>(Original.first)) &&
3050 "Address must be a Phi or Select node");
3051 auto *Dummy = UndefValue::get(CommonType);
3052 Worklist.push_back(Original);
3053 while (!Worklist.empty()) {
3054 auto Current = Worklist.pop_back_val();
3055 // If value is not an instruction it is something global, constant,
3056 // parameter and we can say that this value is observable in any block.
3057 // Set block to null to denote it.
3058 // Also please take into account that it is how we build anchors.
3059 if (!isa<Instruction>(Current.first))
3060 Current.second = nullptr;
3061 // if it is already visited or it is an ending value then skip it.
3062 if (Map.find(Current) != Map.end())
3063 continue;
3064 TraverseOrder.push_back(Current);
3065
3066 Value *CurrentValue = Current.first;
3067 BasicBlock *CurrentBlock = Current.second;
3068 // CurrentValue must be a Phi node or select. All others must be covered
3069 // by anchors.
3070 Instruction *CurrentI = cast<Instruction>(CurrentValue);
3071 bool IsDefinedInThisBB = CurrentI->getParent() == CurrentBlock;
3072
3073 unsigned PredCount =
3074 std::distance(pred_begin(CurrentBlock), pred_end(CurrentBlock));
3075 // if Current Value is not defined in this basic block we are interested
3076 // in values in predecessors.
3077 if (!IsDefinedInThisBB) {
3078 assert(PredCount && "Unreachable block?!");
3079 PHINode *PHI = PHINode::Create(CommonType, PredCount, "sunk_phi",
3080 &CurrentBlock->front());
3081 Map[Current] = PHI;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003082 ST.insertNewPhi(PHI);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003083 // Add all predecessors in work list.
3084 for (auto B : predecessors(CurrentBlock))
3085 Worklist.push_back({ CurrentValue, B });
3086 continue;
3087 }
3088 // Value is defined in this basic block.
3089 if (SelectInst *OrigSelect = dyn_cast<SelectInst>(CurrentI)) {
3090 // Is it OK to get metadata from OrigSelect?!
3091 // Create a Select placeholder with dummy value.
3092 SelectInst *Select =
3093 SelectInst::Create(OrigSelect->getCondition(), Dummy, Dummy,
3094 OrigSelect->getName(), OrigSelect, OrigSelect);
3095 Map[Current] = Select;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003096 ST.insertNewSelect(Select);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003097 // We are interested in True and False value in this basic block.
3098 Worklist.push_back({ OrigSelect->getTrueValue(), CurrentBlock });
3099 Worklist.push_back({ OrigSelect->getFalseValue(), CurrentBlock });
3100 } else {
3101 // It must be a Phi node then.
3102 auto *CurrentPhi = cast<PHINode>(CurrentI);
3103 // Create new Phi node for merge of bases.
3104 assert(PredCount && "Unreachable block?!");
3105 PHINode *PHI = PHINode::Create(CommonType, PredCount, "sunk_phi",
3106 &CurrentBlock->front());
3107 Map[Current] = PHI;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003108 ST.insertNewPhi(PHI);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003109
3110 // Add all predecessors in work list.
3111 for (auto B : predecessors(CurrentBlock))
3112 Worklist.push_back({ CurrentPhi->getIncomingValueForBlock(B), B });
3113 }
3114 }
John Brawn736bf002017-10-03 13:08:22 +00003115 }
John Brawn70cdb5b2017-11-24 14:10:45 +00003116
3117 bool addrModeCombiningAllowed() {
3118 if (DisableComplexAddrModes)
3119 return false;
3120 switch (DifferentField) {
3121 default:
3122 return false;
3123 case ExtAddrMode::BaseRegField:
3124 return AddrSinkCombineBaseReg;
3125 case ExtAddrMode::BaseGVField:
3126 return AddrSinkCombineBaseGV;
3127 case ExtAddrMode::BaseOffsField:
3128 return AddrSinkCombineBaseOffs;
3129 case ExtAddrMode::ScaledRegField:
3130 return AddrSinkCombineScaledReg;
3131 }
3132 }
John Brawn736bf002017-10-03 13:08:22 +00003133};
Eugene Zelenko900b6332017-08-29 22:32:07 +00003134} // end anonymous namespace
3135
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003136/// Try adding ScaleReg*Scale to the current addressing mode.
Chandler Carruthc8925912013-01-05 02:09:22 +00003137/// Return true and update AddrMode if this addr mode is legal for the target,
3138/// false if not.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003139bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
Chandler Carruthc8925912013-01-05 02:09:22 +00003140 unsigned Depth) {
3141 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
3142 // mode. Just process that directly.
3143 if (Scale == 1)
Sanjay Patelfc580a62015-09-21 23:03:16 +00003144 return matchAddr(ScaleReg, Depth);
Stephen Lin837bba12013-07-15 17:55:02 +00003145
Chandler Carruthc8925912013-01-05 02:09:22 +00003146 // If the scale is 0, it takes nothing to add this.
3147 if (Scale == 0)
3148 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003149
Chandler Carruthc8925912013-01-05 02:09:22 +00003150 // If we already have a scale of this value, we can add to it, otherwise, we
3151 // need an available scale field.
3152 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
3153 return false;
3154
3155 ExtAddrMode TestAddrMode = AddrMode;
3156
3157 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
3158 // [A+B + A*7] -> [B+A*8].
3159 TestAddrMode.Scale += Scale;
3160 TestAddrMode.ScaledReg = ScaleReg;
3161
3162 // If the new address isn't legal, bail out.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003163 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003164 return false;
3165
3166 // It was legal, so commit it.
3167 AddrMode = TestAddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00003168
Chandler Carruthc8925912013-01-05 02:09:22 +00003169 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
3170 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
3171 // X*Scale + C*Scale to addr mode.
Craig Topperc0196b12014-04-14 00:51:57 +00003172 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003173 if (isa<Instruction>(ScaleReg) && // not a constant expr.
3174 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
3175 TestAddrMode.ScaledReg = AddLHS;
3176 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00003177
Chandler Carruthc8925912013-01-05 02:09:22 +00003178 // If this addressing mode is legal, commit it and remember that we folded
3179 // this instruction.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003180 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003181 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
3182 AddrMode = TestAddrMode;
3183 return true;
3184 }
3185 }
3186
3187 // Otherwise, not (x+c)*scale, just return what we have.
3188 return true;
3189}
3190
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003191/// This is a little filter, which returns true if an addressing computation
3192/// involving I might be folded into a load/store accessing it.
3193/// This doesn't need to be perfect, but needs to accept at least
Chandler Carruthc8925912013-01-05 02:09:22 +00003194/// the set of instructions that MatchOperationAddr can.
3195static bool MightBeFoldableInst(Instruction *I) {
3196 switch (I->getOpcode()) {
3197 case Instruction::BitCast:
Eli Benderskyf13a0562014-05-22 00:02:52 +00003198 case Instruction::AddrSpaceCast:
Chandler Carruthc8925912013-01-05 02:09:22 +00003199 // Don't touch identity bitcasts.
3200 if (I->getType() == I->getOperand(0)->getType())
3201 return false;
3202 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
3203 case Instruction::PtrToInt:
3204 // PtrToInt is always a noop, as we know that the int type is pointer sized.
3205 return true;
3206 case Instruction::IntToPtr:
3207 // We know the input is intptr_t, so this is foldable.
3208 return true;
3209 case Instruction::Add:
3210 return true;
3211 case Instruction::Mul:
3212 case Instruction::Shl:
3213 // Can only handle X*C and X << C.
3214 return isa<ConstantInt>(I->getOperand(1));
3215 case Instruction::GetElementPtr:
3216 return true;
3217 default:
3218 return false;
3219 }
3220}
3221
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003222/// \brief Check whether or not \p Val is a legal instruction for \p TLI.
3223/// \note \p Val is assumed to be the product of some type promotion.
3224/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
3225/// to be legal, as the non-promoted value would have had the same state.
Mehdi Amini44ede332015-07-09 02:09:04 +00003226static bool isPromotedInstructionLegal(const TargetLowering &TLI,
3227 const DataLayout &DL, Value *Val) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003228 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
3229 if (!PromotedInst)
3230 return false;
3231 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
3232 // If the ISDOpcode is undefined, it was undefined before the promotion.
3233 if (!ISDOpcode)
3234 return true;
3235 // Otherwise, check if the promoted instruction is legal or not.
3236 return TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00003237 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003238}
3239
Eugene Zelenko900b6332017-08-29 22:32:07 +00003240namespace {
3241
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003242/// \brief Hepler class to perform type promotion.
3243class TypePromotionHelper {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003244 /// \brief Utility function to check whether or not a sign or zero extension
3245 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
3246 /// either using the operands of \p Inst or promoting \p Inst.
3247 /// The type of the extension is defined by \p IsSExt.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003248 /// In other words, check if:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003249 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003250 /// #1 Promotion applies:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003251 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003252 /// #2 Operand reuses:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003253 /// ext opnd1 to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003254 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003255 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
3256 const InstrToOrigTy &PromotedInsts, bool IsSExt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003257
3258 /// \brief Utility function to determine if \p OpIdx should be promoted when
3259 /// promoting \p Inst.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003260 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
Rafael Espindola84921b92015-10-24 23:11:13 +00003261 return !(isa<SelectInst>(Inst) && OpIdx == 0);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003262 }
3263
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003264 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003265 /// operand is a promotable trunc or sext or zext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003266 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003267 /// \p CreatedInstsCost[out] contains the cost of all instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003268 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003269 /// Newly added extensions are inserted in \p Exts.
3270 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003271 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003272 /// \return The promoted value which is used instead of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003273 static Value *promoteOperandForTruncAndAnyExt(
3274 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003275 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003276 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003277 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003278
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003279 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003280 /// operand is promotable and is not a supported trunc or sext.
3281 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003282 /// \p CreatedInstsCost[out] contains the cost of all the instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003283 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003284 /// Newly added extensions are inserted in \p Exts.
3285 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003286 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003287 /// \return The promoted value which is used instead of Ext.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003288 static Value *promoteOperandForOther(Instruction *Ext,
3289 TypePromotionTransaction &TPT,
3290 InstrToOrigTy &PromotedInsts,
3291 unsigned &CreatedInstsCost,
3292 SmallVectorImpl<Instruction *> *Exts,
3293 SmallVectorImpl<Instruction *> *Truncs,
3294 const TargetLowering &TLI, bool IsSExt);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003295
3296 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003297 static Value *signExtendOperandForOther(
3298 Instruction *Ext, TypePromotionTransaction &TPT,
3299 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3300 SmallVectorImpl<Instruction *> *Exts,
3301 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3302 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3303 Exts, Truncs, TLI, true);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003304 }
3305
3306 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003307 static Value *zeroExtendOperandForOther(
3308 Instruction *Ext, TypePromotionTransaction &TPT,
3309 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3310 SmallVectorImpl<Instruction *> *Exts,
3311 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3312 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3313 Exts, Truncs, TLI, false);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003314 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003315
3316public:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003317 /// Type for the utility function that promotes the operand of Ext.
Eugene Zelenko900b6332017-08-29 22:32:07 +00003318 using Action = Value *(*)(Instruction *Ext, TypePromotionTransaction &TPT,
3319 InstrToOrigTy &PromotedInsts,
3320 unsigned &CreatedInstsCost,
3321 SmallVectorImpl<Instruction *> *Exts,
3322 SmallVectorImpl<Instruction *> *Truncs,
3323 const TargetLowering &TLI);
3324
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003325 /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
3326 /// action to promote the operand of \p Ext instead of using Ext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003327 /// \return NULL if no promotable action is possible with the current
3328 /// sign extension.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003329 /// \p InsertedInsts keeps track of all the instructions inserted by the
3330 /// other CodeGenPrepare optimizations. This information is important
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003331 /// because we do not want to promote these instructions as CodeGenPrepare
3332 /// will reinsert them later. Thus creating an infinite loop: create/remove.
3333 /// \p PromotedInsts maps the instructions to their type before promotion.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003334 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003335 const TargetLowering &TLI,
3336 const InstrToOrigTy &PromotedInsts);
3337};
3338
Eugene Zelenko900b6332017-08-29 22:32:07 +00003339} // end anonymous namespace
3340
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003341bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003342 Type *ConsideredExtType,
3343 const InstrToOrigTy &PromotedInsts,
3344 bool IsSExt) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003345 // The promotion helper does not know how to deal with vector types yet.
3346 // To be able to fix that, we would need to fix the places where we
3347 // statically extend, e.g., constants and such.
3348 if (Inst->getType()->isVectorTy())
3349 return false;
3350
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003351 // We can always get through zext.
3352 if (isa<ZExtInst>(Inst))
3353 return true;
3354
3355 // sext(sext) is ok too.
3356 if (IsSExt && isa<SExtInst>(Inst))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003357 return true;
3358
3359 // We can get through binary operator, if it is legal. In other words, the
3360 // binary operator must have a nuw or nsw flag.
3361 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
3362 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003363 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
3364 (IsSExt && BinOp->hasNoSignedWrap())))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003365 return true;
3366
3367 // Check if we can do the following simplification.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003368 // ext(trunc(opnd)) --> ext(opnd)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003369 if (!isa<TruncInst>(Inst))
3370 return false;
3371
3372 Value *OpndVal = Inst->getOperand(0);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003373 // Check if we can use this operand in the extension.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003374 // If the type is larger than the result type of the extension, we cannot.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003375 if (!OpndVal->getType()->isIntegerTy() ||
3376 OpndVal->getType()->getIntegerBitWidth() >
3377 ConsideredExtType->getIntegerBitWidth())
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003378 return false;
3379
3380 // If the operand of the truncate is not an instruction, we will not have
3381 // any information on the dropped bits.
3382 // (Actually we could for constant but it is not worth the extra logic).
3383 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
3384 if (!Opnd)
3385 return false;
3386
3387 // Check if the source of the type is narrow enough.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003388 // I.e., check that trunc just drops extended bits of the same kind of
3389 // the extension.
3390 // #1 get the type of the operand and check the kind of the extended bits.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003391 const Type *OpndType;
3392 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
Benjamin Kramer4cd5faa2015-07-31 17:00:39 +00003393 if (It != PromotedInsts.end() && It->second.getInt() == IsSExt)
3394 OpndType = It->second.getPointer();
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003395 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
3396 OpndType = Opnd->getOperand(0)->getType();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003397 else
3398 return false;
3399
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003400 // #2 check that the truncate just drops extended bits.
Rafael Espindola84921b92015-10-24 23:11:13 +00003401 return Inst->getType()->getIntegerBitWidth() >=
3402 OpndType->getIntegerBitWidth();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003403}
3404
3405TypePromotionHelper::Action TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003406 Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003407 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003408 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
3409 "Unexpected instruction type");
3410 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
3411 Type *ExtTy = Ext->getType();
3412 bool IsSExt = isa<SExtInst>(Ext);
3413 // If the operand of the extension is not an instruction, we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003414 // get through.
3415 // If it, check we can get through.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003416 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
Craig Topperc0196b12014-04-14 00:51:57 +00003417 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003418
3419 // Do not promote if the operand has been added by codegenprepare.
3420 // Otherwise, it means we are undoing an optimization that is likely to be
3421 // redone, thus causing potential infinite loop.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003422 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
Craig Topperc0196b12014-04-14 00:51:57 +00003423 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003424
3425 // SExt or Trunc instructions.
3426 // Return the related handler.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003427 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
3428 isa<ZExtInst>(ExtOpnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003429 return promoteOperandForTruncAndAnyExt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003430
3431 // Regular instruction.
3432 // Abort early if we will have to insert non-free instructions.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003433 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
Craig Topperc0196b12014-04-14 00:51:57 +00003434 return nullptr;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003435 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003436}
3437
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003438Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
Eugene Zelenko900b6332017-08-29 22:32:07 +00003439 Instruction *SExt, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003440 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003441 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003442 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003443 // By construction, the operand of SExt is an instruction. Otherwise we cannot
3444 // get through it and this method should not be called.
3445 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
Quentin Colombetac55b152014-09-16 22:36:07 +00003446 Value *ExtVal = SExt;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003447 bool HasMergedNonFreeExt = false;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003448 if (isa<ZExtInst>(SExtOpnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003449 // Replace s|zext(zext(opnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003450 // => zext(opnd).
Quentin Colombet1b274f92015-03-10 21:48:15 +00003451 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00003452 Value *ZExt =
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003453 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
3454 TPT.replaceAllUsesWith(SExt, ZExt);
3455 TPT.eraseInstruction(SExt);
Quentin Colombetac55b152014-09-16 22:36:07 +00003456 ExtVal = ZExt;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003457 } else {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003458 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
3459 // => z|sext(opnd).
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003460 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
3461 }
Quentin Colombet1b274f92015-03-10 21:48:15 +00003462 CreatedInstsCost = 0;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003463
3464 // Remove dead code.
3465 if (SExtOpnd->use_empty())
3466 TPT.eraseInstruction(SExtOpnd);
3467
Quentin Colombet9dcb7242014-09-15 18:26:58 +00003468 // Check if the extension is still needed.
Quentin Colombetac55b152014-09-16 22:36:07 +00003469 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003470 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
Quentin Colombet1b274f92015-03-10 21:48:15 +00003471 if (ExtInst) {
3472 if (Exts)
3473 Exts->push_back(ExtInst);
3474 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
3475 }
Quentin Colombetac55b152014-09-16 22:36:07 +00003476 return ExtVal;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003477 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003478
Quentin Colombet9dcb7242014-09-15 18:26:58 +00003479 // At this point we have: ext ty opnd to ty.
3480 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
3481 Value *NextVal = ExtInst->getOperand(0);
3482 TPT.eraseInstruction(ExtInst, NextVal);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003483 return NextVal;
3484}
3485
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003486Value *TypePromotionHelper::promoteOperandForOther(
3487 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003488 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003489 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003490 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
3491 bool IsSExt) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003492 // By construction, the operand of Ext is an instruction. Otherwise we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003493 // get through it and this method should not be called.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003494 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
Quentin Colombet1b274f92015-03-10 21:48:15 +00003495 CreatedInstsCost = 0;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003496 if (!ExtOpnd->hasOneUse()) {
3497 // ExtOpnd will be promoted.
3498 // All its uses, but Ext, will need to use a truncated value of the
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003499 // promoted version.
3500 // Create the truncate now.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003501 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
Quentin Colombetac55b152014-09-16 22:36:07 +00003502 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
Quentin Colombetac55b152014-09-16 22:36:07 +00003503 // Insert it just after the definition.
Sanjay Patel674d2c22017-08-29 14:07:48 +00003504 ITrunc->moveAfter(ExtOpnd);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003505 if (Truncs)
3506 Truncs->push_back(ITrunc);
Quentin Colombetac55b152014-09-16 22:36:07 +00003507 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003508
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003509 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003510 // Restore the operand of Ext (which has been replaced by the previous call
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003511 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003512 TPT.setOperand(Ext, 0, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003513 }
3514
3515 // Get through the Instruction:
3516 // 1. Update its type.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003517 // 2. Replace the uses of Ext by Inst.
3518 // 3. Extend each operand that needs to be extended.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003519
3520 // Remember the original type of the instruction before promotion.
3521 // This is useful to know that the high bits are sign extended bits.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003522 PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
3523 ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003524 // Step #1.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003525 TPT.mutateType(ExtOpnd, Ext->getType());
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003526 // Step #2.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003527 TPT.replaceAllUsesWith(Ext, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003528 // Step #3.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003529 Instruction *ExtForOpnd = Ext;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003530
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003531 DEBUG(dbgs() << "Propagate Ext to operands\n");
3532 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003533 ++OpIdx) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003534 DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
3535 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
3536 !shouldExtOperand(ExtOpnd, OpIdx)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003537 DEBUG(dbgs() << "No need to propagate\n");
3538 continue;
3539 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003540 // Check if we can statically extend the operand.
3541 Value *Opnd = ExtOpnd->getOperand(OpIdx);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003542 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003543 DEBUG(dbgs() << "Statically extend\n");
3544 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
3545 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
3546 : Cst->getValue().zext(BitWidth);
3547 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003548 continue;
3549 }
3550 // UndefValue are typed, so we have to statically sign extend them.
3551 if (isa<UndefValue>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003552 DEBUG(dbgs() << "Statically extend\n");
3553 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003554 continue;
3555 }
3556
3557 // Otherwise we have to explicity sign extend the operand.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003558 // Check if Ext was reused to extend an operand.
3559 if (!ExtForOpnd) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003560 // If yes, create a new one.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003561 DEBUG(dbgs() << "More operands to ext\n");
Quentin Colombet84f89cc2014-12-22 18:11:52 +00003562 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
3563 : TPT.createZExt(Ext, Opnd, Ext->getType());
3564 if (!isa<Instruction>(ValForExtOpnd)) {
3565 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
3566 continue;
3567 }
3568 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003569 }
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003570 if (Exts)
3571 Exts->push_back(ExtForOpnd);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003572 TPT.setOperand(ExtForOpnd, 0, Opnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003573
3574 // Move the sign extension before the insertion point.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003575 TPT.moveBefore(ExtForOpnd, ExtOpnd);
3576 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
Quentin Colombet1b274f92015-03-10 21:48:15 +00003577 CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003578 // If more sext are required, new instructions will have to be created.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003579 ExtForOpnd = nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003580 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003581 if (ExtForOpnd == Ext) {
3582 DEBUG(dbgs() << "Extension is useless now\n");
3583 TPT.eraseInstruction(Ext);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003584 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003585 return ExtOpnd;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003586}
3587
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003588/// Check whether or not promoting an instruction to a wider type is profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003589/// \p NewCost gives the cost of extension instructions created by the
3590/// promotion.
3591/// \p OldCost gives the cost of extension instructions before the promotion
3592/// plus the number of instructions that have been
3593/// matched in the addressing mode the promotion.
Quentin Colombet867c5502014-02-14 22:23:22 +00003594/// \p PromotedOperand is the value that has been promoted.
3595/// \return True if the promotion is profitable, false otherwise.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003596bool AddressingModeMatcher::isPromotionProfitable(
Quentin Colombet1b274f92015-03-10 21:48:15 +00003597 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
3598 DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n');
3599 // The cost of the new extensions is greater than the cost of the
3600 // old extension plus what we folded.
Quentin Colombet867c5502014-02-14 22:23:22 +00003601 // This is not profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003602 if (NewCost > OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003603 return false;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003604 if (NewCost < OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003605 return true;
3606 // The promotion is neutral but it may help folding the sign extension in
3607 // loads for instance.
3608 // Check that we did not create an illegal instruction.
Mehdi Amini44ede332015-07-09 02:09:04 +00003609 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
Quentin Colombet867c5502014-02-14 22:23:22 +00003610}
3611
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003612/// Given an instruction or constant expr, see if we can fold the operation
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003613/// into the addressing mode. If so, update the addressing mode and return
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003614/// true, otherwise return false without modifying AddrMode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003615/// If \p MovedAway is not NULL, it contains the information of whether or
3616/// not AddrInst has to be folded into the addressing mode on success.
3617/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
3618/// because it has been moved away.
3619/// Thus AddrInst must not be added in the matched instructions.
3620/// This state can happen when AddrInst is a sext, since it may be moved away.
3621/// Therefore, AddrInst may not be valid when MovedAway is true and it must
3622/// not be referenced anymore.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003623bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003624 unsigned Depth,
3625 bool *MovedAway) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003626 // Avoid exponential behavior on extremely deep expression trees.
3627 if (Depth >= 5) return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003628
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003629 // By default, all matched instructions stay in place.
3630 if (MovedAway)
3631 *MovedAway = false;
3632
Chandler Carruthc8925912013-01-05 02:09:22 +00003633 switch (Opcode) {
3634 case Instruction::PtrToInt:
3635 // PtrToInt is always a noop, as we know that the int type is pointer sized.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003636 return matchAddr(AddrInst->getOperand(0), Depth);
Mehdi Amini44ede332015-07-09 02:09:04 +00003637 case Instruction::IntToPtr: {
3638 auto AS = AddrInst->getType()->getPointerAddressSpace();
3639 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
Chandler Carruthc8925912013-01-05 02:09:22 +00003640 // This inttoptr is a no-op if the integer type is pointer sized.
Mehdi Amini44ede332015-07-09 02:09:04 +00003641 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
Sanjay Patelfc580a62015-09-21 23:03:16 +00003642 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003643 return false;
Mehdi Amini44ede332015-07-09 02:09:04 +00003644 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003645 case Instruction::BitCast:
3646 // BitCast is always a noop, and we can handle it as long as it is
3647 // int->int or pointer->pointer (we don't want int<->fp or something).
3648 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
3649 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
3650 // Don't touch identity bitcasts. These were probably put here by LSR,
3651 // and we don't want to mess around with them. Assume it knows what it
3652 // is doing.
3653 AddrInst->getOperand(0)->getType() != AddrInst->getType())
Sanjay Patelfc580a62015-09-21 23:03:16 +00003654 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003655 return false;
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003656 case Instruction::AddrSpaceCast: {
3657 unsigned SrcAS
3658 = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
3659 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
3660 if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
Sanjay Patelfc580a62015-09-21 23:03:16 +00003661 return matchAddr(AddrInst->getOperand(0), Depth);
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003662 return false;
3663 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003664 case Instruction::Add: {
3665 // Check to see if we can merge in the RHS then the LHS. If so, we win.
3666 ExtAddrMode BackupAddrMode = AddrMode;
3667 unsigned OldSize = AddrModeInsts.size();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003668 // Start a transaction at this point.
3669 // The LHS may match but not the RHS.
3670 // Therefore, we need a higher level restoration point to undo partially
3671 // matched operation.
3672 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3673 TPT.getRestorationPoint();
3674
Sanjay Patelfc580a62015-09-21 23:03:16 +00003675 if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
3676 matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003677 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003678
Chandler Carruthc8925912013-01-05 02:09:22 +00003679 // Restore the old addr mode info.
3680 AddrMode = BackupAddrMode;
3681 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003682 TPT.rollback(LastKnownGood);
Stephen Lin837bba12013-07-15 17:55:02 +00003683
Chandler Carruthc8925912013-01-05 02:09:22 +00003684 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003685 if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
3686 matchAddr(AddrInst->getOperand(1), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003687 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003688
Chandler Carruthc8925912013-01-05 02:09:22 +00003689 // Otherwise we definitely can't merge the ADD in.
3690 AddrMode = BackupAddrMode;
3691 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003692 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003693 break;
3694 }
3695 //case Instruction::Or:
3696 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
3697 //break;
3698 case Instruction::Mul:
3699 case Instruction::Shl: {
3700 // Can only handle X*C and X << C.
3701 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
Philip Reames9c3cbee2017-10-30 23:59:51 +00003702 if (!RHS || RHS->getBitWidth() > 64)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003703 return false;
Chandler Carruthc8925912013-01-05 02:09:22 +00003704 int64_t Scale = RHS->getSExtValue();
3705 if (Opcode == Instruction::Shl)
3706 Scale = 1LL << Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00003707
Sanjay Patelfc580a62015-09-21 23:03:16 +00003708 return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003709 }
3710 case Instruction::GetElementPtr: {
3711 // Scan the GEP. We check it if it contains constant offsets and at most
3712 // one variable offset.
3713 int VariableOperand = -1;
3714 unsigned VariableScale = 0;
Stephen Lin837bba12013-07-15 17:55:02 +00003715
Chandler Carruthc8925912013-01-05 02:09:22 +00003716 int64_t ConstantOffset = 0;
Chandler Carruthc8925912013-01-05 02:09:22 +00003717 gep_type_iterator GTI = gep_type_begin(AddrInst);
3718 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
Peter Collingbourneab85225b2016-12-02 02:24:42 +00003719 if (StructType *STy = GTI.getStructTypeOrNull()) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003720 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruthc8925912013-01-05 02:09:22 +00003721 unsigned Idx =
3722 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
3723 ConstantOffset += SL->getElementOffset(Idx);
3724 } else {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003725 uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
Chandler Carruthc8925912013-01-05 02:09:22 +00003726 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
Haicheng Wu0be88252017-12-19 20:53:32 +00003727 ConstantOffset += CI->getSExtValue() * TypeSize;
Chandler Carruthc8925912013-01-05 02:09:22 +00003728 } else if (TypeSize) { // Scales of zero don't do anything.
3729 // We only allow one variable index at the moment.
3730 if (VariableOperand != -1)
3731 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003732
Chandler Carruthc8925912013-01-05 02:09:22 +00003733 // Remember the variable index.
3734 VariableOperand = i;
3735 VariableScale = TypeSize;
3736 }
3737 }
3738 }
Stephen Lin837bba12013-07-15 17:55:02 +00003739
Chandler Carruthc8925912013-01-05 02:09:22 +00003740 // A common case is for the GEP to only do a constant offset. In this case,
3741 // just add it to the disp field and check validity.
3742 if (VariableOperand == -1) {
3743 AddrMode.BaseOffs += ConstantOffset;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003744 if (ConstantOffset == 0 ||
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003745 TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003746 // Check to see if we can fold the base pointer in too.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003747 if (matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003748 return true;
3749 }
3750 AddrMode.BaseOffs -= ConstantOffset;
3751 return false;
3752 }
3753
3754 // Save the valid addressing mode in case we can't match.
3755 ExtAddrMode BackupAddrMode = AddrMode;
3756 unsigned OldSize = AddrModeInsts.size();
3757
3758 // See if the scale and offset amount is valid for this target.
3759 AddrMode.BaseOffs += ConstantOffset;
3760
3761 // Match the base operand of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003762 if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003763 // If it couldn't be matched, just stuff the value in a register.
3764 if (AddrMode.HasBaseReg) {
3765 AddrMode = BackupAddrMode;
3766 AddrModeInsts.resize(OldSize);
3767 return false;
3768 }
3769 AddrMode.HasBaseReg = true;
3770 AddrMode.BaseReg = AddrInst->getOperand(0);
3771 }
3772
3773 // Match the remaining variable portion of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003774 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
Chandler Carruthc8925912013-01-05 02:09:22 +00003775 Depth)) {
3776 // If it couldn't be matched, try stuffing the base into a register
3777 // instead of matching it, and retrying the match of the scale.
3778 AddrMode = BackupAddrMode;
3779 AddrModeInsts.resize(OldSize);
3780 if (AddrMode.HasBaseReg)
3781 return false;
3782 AddrMode.HasBaseReg = true;
3783 AddrMode.BaseReg = AddrInst->getOperand(0);
3784 AddrMode.BaseOffs += ConstantOffset;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003785 if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
Chandler Carruthc8925912013-01-05 02:09:22 +00003786 VariableScale, Depth)) {
3787 // If even that didn't work, bail.
3788 AddrMode = BackupAddrMode;
3789 AddrModeInsts.resize(OldSize);
3790 return false;
3791 }
3792 }
3793
3794 return true;
3795 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003796 case Instruction::SExt:
3797 case Instruction::ZExt: {
3798 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
3799 if (!Ext)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003800 return false;
Sanjay Patelab60d042014-07-16 21:08:10 +00003801
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003802 // Try to move this ext out of the way of the addressing mode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003803 // Ask for a method for doing so.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003804 TypePromotionHelper::Action TPH =
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003805 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003806 if (!TPH)
3807 return false;
3808
3809 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3810 TPT.getRestorationPoint();
Quentin Colombet1b274f92015-03-10 21:48:15 +00003811 unsigned CreatedInstsCost = 0;
3812 unsigned ExtCost = !TLI.isExtFree(Ext);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003813 Value *PromotedOperand =
Quentin Colombet1b274f92015-03-10 21:48:15 +00003814 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003815 // SExt has been moved away.
3816 // Thus either it will be rematched later in the recursive calls or it is
3817 // gone. Anyway, we must not fold it into the addressing mode at this point.
3818 // E.g.,
3819 // op = add opnd, 1
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003820 // idx = ext op
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003821 // addr = gep base, idx
3822 // is now:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003823 // promotedOpnd = ext opnd <- no match here
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003824 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
3825 // addr = gep base, op <- match
3826 if (MovedAway)
3827 *MovedAway = true;
3828
3829 assert(PromotedOperand &&
3830 "TypePromotionHelper should have filtered out those cases");
3831
3832 ExtAddrMode BackupAddrMode = AddrMode;
3833 unsigned OldSize = AddrModeInsts.size();
3834
Sanjay Patelfc580a62015-09-21 23:03:16 +00003835 if (!matchAddr(PromotedOperand, Depth) ||
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003836 // The total of the new cost is equal to the cost of the created
Quentin Colombet1b274f92015-03-10 21:48:15 +00003837 // instructions.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003838 // The total of the old cost is equal to the cost of the extension plus
Quentin Colombet1b274f92015-03-10 21:48:15 +00003839 // what we have saved in the addressing mode.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003840 !isPromotionProfitable(CreatedInstsCost,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003841 ExtCost + (AddrModeInsts.size() - OldSize),
Quentin Colombet867c5502014-02-14 22:23:22 +00003842 PromotedOperand)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003843 AddrMode = BackupAddrMode;
3844 AddrModeInsts.resize(OldSize);
3845 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
3846 TPT.rollback(LastKnownGood);
3847 return false;
3848 }
3849 return true;
3850 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003851 }
3852 return false;
3853}
3854
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003855/// If we can, try to add the value of 'Addr' into the current addressing mode.
3856/// If Addr can't be added to AddrMode this returns false and leaves AddrMode
3857/// unmodified. This assumes that Addr is either a pointer type or intptr_t
3858/// for the target.
Chandler Carruthc8925912013-01-05 02:09:22 +00003859///
Sanjay Patelfc580a62015-09-21 23:03:16 +00003860bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003861 // Start a transaction at this point that we will rollback if the matching
3862 // fails.
3863 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3864 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00003865 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
3866 // Fold in immediates if legal for the target.
3867 AddrMode.BaseOffs += CI->getSExtValue();
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003868 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003869 return true;
3870 AddrMode.BaseOffs -= CI->getSExtValue();
3871 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
3872 // If this is a global variable, try to fold it into the addressing mode.
Craig Topperc0196b12014-04-14 00:51:57 +00003873 if (!AddrMode.BaseGV) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003874 AddrMode.BaseGV = GV;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003875 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003876 return true;
Craig Topperc0196b12014-04-14 00:51:57 +00003877 AddrMode.BaseGV = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003878 }
3879 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
3880 ExtAddrMode BackupAddrMode = AddrMode;
3881 unsigned OldSize = AddrModeInsts.size();
3882
3883 // Check to see if it is possible to fold this operation.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003884 bool MovedAway = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003885 if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003886 // This instruction may have been moved away. If so, there is nothing
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003887 // to check here.
3888 if (MovedAway)
3889 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00003890 // Okay, it's possible to fold this. Check to see if it is actually
3891 // *profitable* to do so. We use a simple cost model to avoid increasing
3892 // register pressure too much.
3893 if (I->hasOneUse() ||
Sanjay Patelfc580a62015-09-21 23:03:16 +00003894 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003895 AddrModeInsts.push_back(I);
3896 return true;
3897 }
Stephen Lin837bba12013-07-15 17:55:02 +00003898
Chandler Carruthc8925912013-01-05 02:09:22 +00003899 // It isn't profitable to do this, roll back.
3900 //cerr << "NOT FOLDING: " << *I;
3901 AddrMode = BackupAddrMode;
3902 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003903 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003904 }
3905 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
Sanjay Patelfc580a62015-09-21 23:03:16 +00003906 if (matchOperationAddr(CE, CE->getOpcode(), Depth))
Chandler Carruthc8925912013-01-05 02:09:22 +00003907 return true;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003908 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003909 } else if (isa<ConstantPointerNull>(Addr)) {
3910 // Null pointer gets folded without affecting the addressing mode.
3911 return true;
3912 }
3913
3914 // Worse case, the target should support [reg] addressing modes. :)
3915 if (!AddrMode.HasBaseReg) {
3916 AddrMode.HasBaseReg = true;
3917 AddrMode.BaseReg = Addr;
3918 // Still check for legality in case the target supports [imm] but not [i+r].
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003919 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003920 return true;
3921 AddrMode.HasBaseReg = false;
Craig Topperc0196b12014-04-14 00:51:57 +00003922 AddrMode.BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003923 }
3924
3925 // If the base register is already taken, see if we can do [r+r].
3926 if (AddrMode.Scale == 0) {
3927 AddrMode.Scale = 1;
3928 AddrMode.ScaledReg = Addr;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003929 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003930 return true;
3931 AddrMode.Scale = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00003932 AddrMode.ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003933 }
3934 // Couldn't match.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003935 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003936 return false;
3937}
3938
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003939/// Check to see if all uses of OpVal by the specified inline asm call are due
3940/// to memory operands. If so, return true, otherwise return false.
Chandler Carruthc8925912013-01-05 02:09:22 +00003941static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003942 const TargetLowering &TLI,
3943 const TargetRegisterInfo &TRI) {
Sanjay Patel4137d512017-06-07 14:29:52 +00003944 const Function *F = CI->getFunction();
Eric Christopherd75c00c2015-02-26 22:38:34 +00003945 TargetLowering::AsmOperandInfoVector TargetConstraints =
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003946 TLI.ParseConstraints(F->getParent()->getDataLayout(), &TRI,
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00003947 ImmutableCallSite(CI));
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003948
Chandler Carruthc8925912013-01-05 02:09:22 +00003949 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
3950 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Stephen Lin837bba12013-07-15 17:55:02 +00003951
Chandler Carruthc8925912013-01-05 02:09:22 +00003952 // Compute the constraint code and ConstraintType to use.
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003953 TLI.ComputeConstraintToUse(OpInfo, SDValue());
Chandler Carruthc8925912013-01-05 02:09:22 +00003954
3955 // If this asm operand is our Value*, and if it isn't an indirect memory
3956 // operand, we can't fold it!
3957 if (OpInfo.CallOperandVal == OpVal &&
3958 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
3959 !OpInfo.isIndirect))
3960 return false;
3961 }
3962
3963 return true;
3964}
3965
Benjamin Kramerfc638c12017-07-24 16:18:09 +00003966// Max number of memory uses to look at before aborting the search to conserve
3967// compile time.
3968static constexpr int MaxMemoryUsesToScan = 20;
3969
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003970/// Recursively walk all the uses of I until we find a memory use.
3971/// If we find an obviously non-foldable instruction, return true.
Chandler Carruthc8925912013-01-05 02:09:22 +00003972/// Add the ultimately found memory instructions to MemoryUses.
Eric Christopher11e4df72015-02-26 22:38:43 +00003973static bool FindAllMemoryUses(
3974 Instruction *I,
3975 SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
Benjamin Kramerfc638c12017-07-24 16:18:09 +00003976 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetLowering &TLI,
3977 const TargetRegisterInfo &TRI, int SeenInsts = 0) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003978 // If we already considered this instruction, we're done.
David Blaikie70573dc2014-11-19 07:49:26 +00003979 if (!ConsideredInsts.insert(I).second)
Chandler Carruthc8925912013-01-05 02:09:22 +00003980 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003981
Chandler Carruthc8925912013-01-05 02:09:22 +00003982 // If this is an obviously unfoldable instruction, bail out.
3983 if (!MightBeFoldableInst(I))
3984 return true;
3985
Philip Reamesac115ed2016-03-09 23:13:12 +00003986 const bool OptSize = I->getFunction()->optForSize();
3987
Chandler Carruthc8925912013-01-05 02:09:22 +00003988 // Loop over all the uses, recursively processing them.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003989 for (Use &U : I->uses()) {
Benjamin Kramerfc638c12017-07-24 16:18:09 +00003990 // Conservatively return true if we're seeing a large number or a deep chain
3991 // of users. This avoids excessive compilation times in pathological cases.
3992 if (SeenInsts++ >= MaxMemoryUsesToScan)
3993 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00003994
Benjamin Kramerfc638c12017-07-24 16:18:09 +00003995 Instruction *UserI = cast<Instruction>(U.getUser());
Chandler Carruthcdf47882014-03-09 03:16:01 +00003996 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
3997 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
Chandler Carruthc8925912013-01-05 02:09:22 +00003998 continue;
3999 }
Stephen Lin837bba12013-07-15 17:55:02 +00004000
Chandler Carruthcdf47882014-03-09 03:16:01 +00004001 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
4002 unsigned opNo = U.getOperandNo();
Matt Arsenault02d915b2017-03-15 22:35:20 +00004003 if (opNo != StoreInst::getPointerOperandIndex())
4004 return true; // Storing addr, not into addr.
Chandler Carruthc8925912013-01-05 02:09:22 +00004005 MemoryUses.push_back(std::make_pair(SI, opNo));
4006 continue;
4007 }
Stephen Lin837bba12013-07-15 17:55:02 +00004008
Matt Arsenault02d915b2017-03-15 22:35:20 +00004009 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UserI)) {
4010 unsigned opNo = U.getOperandNo();
4011 if (opNo != AtomicRMWInst::getPointerOperandIndex())
4012 return true; // Storing addr, not into addr.
4013 MemoryUses.push_back(std::make_pair(RMW, opNo));
4014 continue;
4015 }
4016
4017 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(UserI)) {
4018 unsigned opNo = U.getOperandNo();
4019 if (opNo != AtomicCmpXchgInst::getPointerOperandIndex())
4020 return true; // Storing addr, not into addr.
4021 MemoryUses.push_back(std::make_pair(CmpX, opNo));
4022 continue;
4023 }
4024
Chandler Carruthcdf47882014-03-09 03:16:01 +00004025 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
Philip Reamesac115ed2016-03-09 23:13:12 +00004026 // If this is a cold call, we can sink the addressing calculation into
4027 // the cold path. See optimizeCallInst
4028 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
4029 continue;
Junmo Park6098cbb2016-03-11 07:05:32 +00004030
Chandler Carruthc8925912013-01-05 02:09:22 +00004031 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
4032 if (!IA) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004033
Chandler Carruthc8925912013-01-05 02:09:22 +00004034 // If this is a memory operand, we're cool, otherwise bail out.
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004035 if (!IsOperandAMemoryOperand(CI, IA, I, TLI, TRI))
Chandler Carruthc8925912013-01-05 02:09:22 +00004036 return true;
4037 continue;
4038 }
Stephen Lin837bba12013-07-15 17:55:02 +00004039
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004040 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI, TRI,
4041 SeenInsts))
Chandler Carruthc8925912013-01-05 02:09:22 +00004042 return true;
4043 }
4044
4045 return false;
4046}
4047
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00004048/// Return true if Val is already known to be live at the use site that we're
4049/// folding it into. If so, there is no cost to include it in the addressing
4050/// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
4051/// instruction already.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004052bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
Chandler Carruthc8925912013-01-05 02:09:22 +00004053 Value *KnownLive2) {
4054 // If Val is either of the known-live values, we know it is live!
Craig Topperc0196b12014-04-14 00:51:57 +00004055 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
Chandler Carruthc8925912013-01-05 02:09:22 +00004056 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004057
Chandler Carruthc8925912013-01-05 02:09:22 +00004058 // All values other than instructions and arguments (e.g. constants) are live.
4059 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004060
Chandler Carruthc8925912013-01-05 02:09:22 +00004061 // If Val is a constant sized alloca in the entry block, it is live, this is
4062 // true because it is just a reference to the stack/frame pointer, which is
4063 // live for the whole function.
4064 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
4065 if (AI->isStaticAlloca())
4066 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004067
Chandler Carruthc8925912013-01-05 02:09:22 +00004068 // Check to see if this value is already used in the memory instruction's
4069 // block. If so, it's already live into the block at the very least, so we
4070 // can reasonably fold it.
4071 return Val->isUsedInBasicBlock(MemoryInst->getParent());
4072}
4073
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004074/// It is possible for the addressing mode of the machine to fold the specified
4075/// instruction into a load or store that ultimately uses it.
4076/// However, the specified instruction has multiple uses.
4077/// Given this, it may actually increase register pressure to fold it
4078/// into the load. For example, consider this code:
Chandler Carruthc8925912013-01-05 02:09:22 +00004079///
4080/// X = ...
4081/// Y = X+1
4082/// use(Y) -> nonload/store
4083/// Z = Y+1
4084/// load Z
4085///
4086/// In this case, Y has multiple uses, and can be folded into the load of Z
4087/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
4088/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
4089/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
4090/// number of computations either.
4091///
4092/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
4093/// X was live across 'load Z' for other reasons, we actually *would* want to
4094/// fold the addressing mode in the Z case. This would make Y die earlier.
4095bool AddressingModeMatcher::
Sanjay Patelfc580a62015-09-21 23:03:16 +00004096isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
Chandler Carruthc8925912013-01-05 02:09:22 +00004097 ExtAddrMode &AMAfter) {
4098 if (IgnoreProfitability) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004099
Chandler Carruthc8925912013-01-05 02:09:22 +00004100 // AMBefore is the addressing mode before this instruction was folded into it,
4101 // and AMAfter is the addressing mode after the instruction was folded. Get
4102 // the set of registers referenced by AMAfter and subtract out those
4103 // referenced by AMBefore: this is the set of values which folding in this
4104 // address extends the lifetime of.
4105 //
4106 // Note that there are only two potential values being referenced here,
4107 // BaseReg and ScaleReg (global addresses are always available, as are any
4108 // folded immediates).
4109 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
Stephen Lin837bba12013-07-15 17:55:02 +00004110
Chandler Carruthc8925912013-01-05 02:09:22 +00004111 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
4112 // lifetime wasn't extended by adding this instruction.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004113 if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00004114 BaseReg = nullptr;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004115 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00004116 ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00004117
4118 // If folding this instruction (and it's subexprs) didn't extend any live
4119 // ranges, we're ok with it.
Craig Topperc0196b12014-04-14 00:51:57 +00004120 if (!BaseReg && !ScaledReg)
Chandler Carruthc8925912013-01-05 02:09:22 +00004121 return true;
4122
Philip Reamesac115ed2016-03-09 23:13:12 +00004123 // If all uses of this instruction can have the address mode sunk into them,
4124 // we can remove the addressing mode and effectively trade one live register
4125 // for another (at worst.) In this context, folding an addressing mode into
Junmo Park6098cbb2016-03-11 07:05:32 +00004126 // the use is just a particularly nice way of sinking it.
Chandler Carruthc8925912013-01-05 02:09:22 +00004127 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
4128 SmallPtrSet<Instruction*, 16> ConsideredInsts;
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004129 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI, TRI))
Chandler Carruthc8925912013-01-05 02:09:22 +00004130 return false; // Has a non-memory, non-foldable use!
Stephen Lin837bba12013-07-15 17:55:02 +00004131
Chandler Carruthc8925912013-01-05 02:09:22 +00004132 // Now that we know that all uses of this instruction are part of a chain of
4133 // computation involving only operations that could theoretically be folded
Philip Reamesac115ed2016-03-09 23:13:12 +00004134 // into a memory use, loop over each of these memory operation uses and see
4135 // if they could *actually* fold the instruction. The assumption is that
4136 // addressing modes are cheap and that duplicating the computation involved
4137 // many times is worthwhile, even on a fastpath. For sinking candidates
4138 // (i.e. cold call sites), this serves as a way to prevent excessive code
4139 // growth since most architectures have some reasonable small and fast way to
4140 // compute an effective address. (i.e LEA on x86)
Chandler Carruthc8925912013-01-05 02:09:22 +00004141 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
4142 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
4143 Instruction *User = MemoryUses[i].first;
4144 unsigned OpNo = MemoryUses[i].second;
Stephen Lin837bba12013-07-15 17:55:02 +00004145
Chandler Carruthc8925912013-01-05 02:09:22 +00004146 // Get the access type of this use. If the use isn't a pointer, we don't
4147 // know what it accesses.
4148 Value *Address = User->getOperand(OpNo);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004149 PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
4150 if (!AddrTy)
Chandler Carruthc8925912013-01-05 02:09:22 +00004151 return false;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004152 Type *AddressAccessTy = AddrTy->getElementType();
4153 unsigned AS = AddrTy->getAddressSpace();
Stephen Lin837bba12013-07-15 17:55:02 +00004154
Chandler Carruthc8925912013-01-05 02:09:22 +00004155 // Do a match against the root of this address, ignoring profitability. This
4156 // will tell us if the addressing mode for the memory operation will
4157 // *actually* cover the shared instruction.
4158 ExtAddrMode Result;
Quentin Colombet5a69dda2014-02-11 01:59:02 +00004159 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4160 TPT.getRestorationPoint();
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004161 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, TRI,
4162 AddressAccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004163 MemoryInst, Result, InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004164 PromotedInsts, TPT);
Chandler Carruthc8925912013-01-05 02:09:22 +00004165 Matcher.IgnoreProfitability = true;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004166 bool Success = Matcher.matchAddr(Address, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00004167 (void)Success; assert(Success && "Couldn't select *anything*?");
4168
Quentin Colombet5a69dda2014-02-11 01:59:02 +00004169 // The match was to check the profitability, the changes made are not
4170 // part of the original matcher. Therefore, they should be dropped
4171 // otherwise the original matcher will not present the right state.
4172 TPT.rollback(LastKnownGood);
4173
Chandler Carruthc8925912013-01-05 02:09:22 +00004174 // If the match didn't cover I, then it won't be shared by it.
David Majnemer0d955d02016-08-11 22:21:41 +00004175 if (!is_contained(MatchedAddrModeInsts, I))
Chandler Carruthc8925912013-01-05 02:09:22 +00004176 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00004177
Chandler Carruthc8925912013-01-05 02:09:22 +00004178 MatchedAddrModeInsts.clear();
4179 }
Stephen Lin837bba12013-07-15 17:55:02 +00004180
Chandler Carruthc8925912013-01-05 02:09:22 +00004181 return true;
4182}
4183
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004184/// Return true if the specified values are defined in a
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004185/// different basic block than BB.
4186static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
4187 if (Instruction *I = dyn_cast<Instruction>(V))
4188 return I->getParent() != BB;
4189 return false;
4190}
4191
Philip Reamesac115ed2016-03-09 23:13:12 +00004192/// Sink addressing mode computation immediate before MemoryInst if doing so
4193/// can be done without increasing register pressure. The need for the
4194/// register pressure constraint means this can end up being an all or nothing
4195/// decision for all uses of the same addressing computation.
4196///
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004197/// Load and Store Instructions often have addressing modes that can do
4198/// significant amounts of computation. As such, instruction selection will try
4199/// to get the load or store to do as much computation as possible for the
4200/// program. The problem is that isel can only see within a single block. As
4201/// such, we sink as much legal addressing mode work into the block as possible.
Chris Lattner728f9022008-11-25 07:09:13 +00004202///
4203/// This method is used to optimize both load/store and inline asms with memory
Philip Reamesac115ed2016-03-09 23:13:12 +00004204/// operands. It's also used to sink addressing computations feeding into cold
4205/// call sites into their (cold) basic block.
4206///
4207/// The motivation for handling sinking into cold blocks is that doing so can
4208/// both enable other address mode sinking (by satisfying the register pressure
4209/// constraint above), and reduce register pressure globally (by removing the
4210/// addressing mode computation from the fast path entirely.).
Sanjay Patelfc580a62015-09-21 23:03:16 +00004211bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004212 Type *AccessTy, unsigned AddrSpace) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00004213 Value *Repl = Addr;
Nadav Rotem465834c2012-07-24 10:51:42 +00004214
4215 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004216 // unprofitable PRE transformations.
Cameron Zwarich43cecb12011-01-03 06:33:01 +00004217 SmallVector<Value*, 8> worklist;
4218 SmallPtrSet<Value*, 16> Visited;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004219 worklist.push_back(Addr);
Nadav Rotem465834c2012-07-24 10:51:42 +00004220
John Brawneb83c752017-10-03 13:04:15 +00004221 // Use a worklist to iteratively look through PHI and select nodes, and
4222 // ensure that the addressing mode obtained from the non-PHI/select roots of
John Brawn736bf002017-10-03 13:08:22 +00004223 // the graph are compatible.
John Brawneb83c752017-10-03 13:04:15 +00004224 bool PhiOrSelectSeen = false;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004225 SmallVector<Instruction*, 16> AddrModeInsts;
Serguei Katkovaee63752017-11-05 07:59:02 +00004226 const SimplifyQuery SQ(*DL, TLInfo);
4227 AddressingModeCombiner AddrModes(SQ, { Addr, MemoryInst->getParent() });
Jun Bum Limdee55652017-04-03 19:20:07 +00004228 TypePromotionTransaction TPT(RemovedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004229 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4230 TPT.getRestorationPoint();
Owen Anderson8ba5f392010-11-27 08:15:55 +00004231 while (!worklist.empty()) {
4232 Value *V = worklist.back();
4233 worklist.pop_back();
Nadav Rotem465834c2012-07-24 10:51:42 +00004234
Serguei Katkov4ea855e2017-07-19 04:49:17 +00004235 // We allow traversing cyclic Phi nodes.
4236 // In case of success after this loop we ensure that traversing through
4237 // Phi nodes ends up with all cases to compute address of the form
4238 // BaseGV + Base + Scale * Index + Offset
4239 // where Scale and Offset are constans and BaseGV, Base and Index
4240 // are exactly the same Values in all cases.
4241 // It means that BaseGV, Scale and Offset dominate our memory instruction
4242 // and have the same value as they had in address computation represented
4243 // as Phi. So we can safely sink address computation to memory instruction.
4244 if (!Visited.insert(V).second)
4245 continue;
Nadav Rotem465834c2012-07-24 10:51:42 +00004246
Owen Anderson8ba5f392010-11-27 08:15:55 +00004247 // For a PHI node, push all of its incoming values.
4248 if (PHINode *P = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00004249 for (Value *IncValue : P->incoming_values())
4250 worklist.push_back(IncValue);
John Brawneb83c752017-10-03 13:04:15 +00004251 PhiOrSelectSeen = true;
4252 continue;
4253 }
4254 // Similar for select.
4255 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
4256 worklist.push_back(SI->getFalseValue());
4257 worklist.push_back(SI->getTrueValue());
4258 PhiOrSelectSeen = true;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004259 continue;
4260 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004261
Philip Reamesac115ed2016-03-09 23:13:12 +00004262 // For non-PHIs, determine the addressing mode being computed. Note that
4263 // the result may differ depending on what other uses our candidate
4264 // addressing instructions might have.
Serguei Katkova6fba3d2017-07-18 05:16:38 +00004265 AddrModeInsts.clear();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004266 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
Serguei Katkova6fba3d2017-07-18 05:16:38 +00004267 V, AccessTy, AddrSpace, MemoryInst, AddrModeInsts, *TLI, *TRI,
4268 InsertedInsts, PromotedInsts, TPT);
John Brawn736bf002017-10-03 13:08:22 +00004269 NewAddrMode.OriginalValue = V;
Cameron Zwarich13c885d2011-03-05 08:12:26 +00004270
John Brawn736bf002017-10-03 13:08:22 +00004271 if (!AddrModes.addNewAddrMode(NewAddrMode))
4272 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004273 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004274
John Brawn736bf002017-10-03 13:08:22 +00004275 // Try to combine the AddrModes we've collected. If we couldn't collect any,
4276 // or we have multiple but either couldn't combine them or combining them
4277 // wouldn't do anything useful, bail out now.
4278 if (!AddrModes.combineAddrModes()) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004279 TPT.rollback(LastKnownGood);
4280 return false;
4281 }
4282 TPT.commit();
Nadav Rotem465834c2012-07-24 10:51:42 +00004283
John Brawn736bf002017-10-03 13:08:22 +00004284 // Get the combined AddrMode (or the only AddrMode, if we only had one).
4285 ExtAddrMode AddrMode = AddrModes.getAddrMode();
4286
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004287 // If all the instructions matched are already in this BB, don't do anything.
John Brawneb83c752017-10-03 13:04:15 +00004288 // If we saw a Phi node then it is not local definitely, and if we saw a select
4289 // then we want to push the address calculation past it even if it's already
4290 // in this BB.
4291 if (!PhiOrSelectSeen && none_of(AddrModeInsts, [&](Value *V) {
Justin Lebar838c7f52016-11-21 22:49:11 +00004292 return IsNonLocalValue(V, MemoryInst->getParent());
Serguei Katkov0b7b59a2017-07-11 06:24:44 +00004293 })) {
David Greene74e2d492010-01-05 01:27:11 +00004294 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004295 return false;
4296 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004297
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004298 // Insert this computation right after this user. Since our caller is
4299 // scanning from the top of the BB to the bottom, reuse of the expr are
4300 // guaranteed to happen later.
Devang Patelc10e52a2011-09-06 18:49:53 +00004301 IRBuilder<> Builder(MemoryInst);
Eric Christopherc1ea1492008-09-24 05:32:41 +00004302
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004303 // Now that we determined the addressing expression we want to use and know
4304 // that we have to sink it into this block. Check to see if we have already
Simon Dardis230f4532017-11-24 16:45:28 +00004305 // done this for some other load/store instr in this block. If so, reuse
4306 // the computation. Before attempting reuse, check if the address is valid
4307 // as it may have been erased.
4308
4309 WeakTrackingVH SunkAddrVH = SunkAddrs[Addr];
4310
4311 Value * SunkAddr = SunkAddrVH.pointsToAliveValue() ? SunkAddrVH : nullptr;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004312 if (SunkAddr) {
David Greene74e2d492010-01-05 01:27:11 +00004313 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00004314 << *MemoryInst << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004315 if (SunkAddr->getType() != Addr->getType())
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004316 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
Eric Christopherfccff372015-01-27 01:01:38 +00004317 } else if (AddrSinkUsingGEPs ||
David Blaikie8ad9a972018-03-28 22:28:50 +00004318 (!AddrSinkUsingGEPs.getNumOccurrences() && TM && TTI->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}