blob: d9f0ae38e3a0fdac9084e2f701bbaf0accb8b216 [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 Blaikie31b98d22018-06-04 21:23:21 +000033#include "llvm/Transforms/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
Haicheng Wu0aae2bc2018-05-10 18:27:36 +0000219static cl::opt<bool>
220 EnableGEPOffsetSplit("cgp-split-large-offset-gep", cl::Hidden,
221 cl::init(true),
222 cl::desc("Enable splitting large offset of GEP."));
223
Eric Christopherc1ea1492008-09-24 05:32:41 +0000224namespace {
Eugene Zelenko900b6332017-08-29 22:32:07 +0000225
Guozhi Wei8c17f9a2018-08-15 22:08:26 +0000226enum ExtType {
227 ZeroExtension, // Zero extension has been seen.
228 SignExtension, // Sign extension has been seen.
229 BothExtension // This extension type is used if we saw sext after
230 // ZeroExtension had been set, or if we saw zext after
231 // SignExtension had been set. It makes the type
232 // information of a promoted instruction invalid.
233};
234
Eugene Zelenko900b6332017-08-29 22:32:07 +0000235using SetOfInstrs = SmallPtrSet<Instruction *, 16>;
Guozhi Wei8c17f9a2018-08-15 22:08:26 +0000236using TypeIsSExt = PointerIntPair<Type *, 2, ExtType>;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000237using InstrToOrigTy = DenseMap<Instruction *, TypeIsSExt>;
238using SExts = SmallVector<Instruction *, 16>;
239using ValueToSExts = DenseMap<Value *, SExts>;
240
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000241class TypePromotionTransaction;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000242
Chris Lattner2dd09db2009-09-02 06:11:42 +0000243 class CodeGenPrepare : public FunctionPass {
Eugene Zelenko900b6332017-08-29 22:32:07 +0000244 const TargetMachine *TM = nullptr;
Igor Laevsky3be81ba2017-02-07 13:27:20 +0000245 const TargetSubtargetInfo *SubtargetInfo;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000246 const TargetLowering *TLI = nullptr;
Igor Laevsky3be81ba2017-02-07 13:27:20 +0000247 const TargetRegisterInfo *TRI;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000248 const TargetTransformInfo *TTI = nullptr;
Chad Rosierc24b86f2011-12-01 03:08:23 +0000249 const TargetLibraryInfo *TLInfo;
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000250 const LoopInfo *LI;
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000251 std::unique_ptr<BlockFrequencyInfo> BFI;
252 std::unique_ptr<BranchProbabilityInfo> BPI;
Nadav Rotem465834c2012-07-24 10:51:42 +0000253
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000254 /// As we scan instructions optimizing them, this is the next instruction
255 /// to optimize. Transforms that can invalidate this should update it.
Chris Lattner7a277142011-01-15 07:14:54 +0000256 BasicBlock::iterator CurInstIterator;
Evan Cheng3b3de7c2008-12-19 18:03:11 +0000257
Evan Cheng0663f232011-03-21 01:19:09 +0000258 /// Keeps track of non-local addresses that have been sunk into a block.
259 /// This allows us to avoid inserting duplicate code for blocks with
Simon Dardis230f4532017-11-24 16:45:28 +0000260 /// multiple load/stores of the same address. The usage of WeakTrackingVH
261 /// enables SunkAddrs to be treated as a cache whose entries can be
262 /// invalidated if a sunken address computation has been erased.
263 ValueMap<Value*, WeakTrackingVH> SunkAddrs;
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000264
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000265 /// Keeps track of all instructions inserted for the current function.
266 SetOfInstrs InsertedInsts;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000267
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000268 /// Keeps track of the type of the related instruction before their
269 /// promotion for the current function.
270 InstrToOrigTy PromotedInsts;
271
Jun Bum Limdee55652017-04-03 19:20:07 +0000272 /// Keep track of instructions removed during promotion.
273 SetOfInstrs RemovedInsts;
274
275 /// Keep track of sext chains based on their initial value.
276 DenseMap<Value *, Instruction *> SeenChainsForSExt;
277
Haicheng Wu0aae2bc2018-05-10 18:27:36 +0000278 /// Keep track of GEPs accessing the same data structures such as structs or
279 /// arrays that are candidates to be split later because of their large
280 /// size.
David Greene27e87c2018-09-12 10:19:10 +0000281 MapVector<
Haicheng Wu0aae2bc2018-05-10 18:27:36 +0000282 AssertingVH<Value>,
283 SmallVector<std::pair<AssertingVH<GetElementPtrInst>, int64_t>, 32>>
284 LargeOffsetGEPMap;
285
286 /// Keep track of new GEP base after splitting the GEPs having large offset.
287 SmallSet<AssertingVH<Value>, 2> NewGEPBases;
288
289 /// Map serial numbers to Large offset GEPs.
290 DenseMap<AssertingVH<GetElementPtrInst>, int> LargeOffsetGEPID;
291
Jun Bum Limdee55652017-04-03 19:20:07 +0000292 /// Keep track of SExt promoted.
293 ValueToSExts ValToSExtendedUses;
294
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000295 /// True if CFG is modified in any way.
Devang Patel8f606d72011-03-24 15:35:25 +0000296 bool ModifiedDT;
Evan Cheng0663f232011-03-21 01:19:09 +0000297
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000298 /// True if optimizing for size.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000299 bool OptSize;
300
Mehdi Amini4fe37982015-07-07 18:45:17 +0000301 /// DataLayout for the Function being processed.
Eugene Zelenko900b6332017-08-29 22:32:07 +0000302 const DataLayout *DL = nullptr;
Mehdi Amini4fe37982015-07-07 18:45:17 +0000303
Chris Lattnerf2836d12007-03-31 04:06:36 +0000304 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +0000305 static char ID; // Pass identification, replacement for typeid
Eugene Zelenko900b6332017-08-29 22:32:07 +0000306
307 CodeGenPrepare() : FunctionPass(ID) {
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000308 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
309 }
Eugene Zelenko900b6332017-08-29 22:32:07 +0000310
Craig Topper4584cd52014-03-07 09:26:03 +0000311 bool runOnFunction(Function &F) override;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000312
Mehdi Amini117296c2016-10-01 02:56:57 +0000313 StringRef getPassName() const override { return "CodeGen Prepare"; }
Evan Cheng99cafb12012-12-21 01:48:14 +0000314
Craig Topper4584cd52014-03-07 09:26:03 +0000315 void getAnalysisUsage(AnalysisUsage &AU) const override {
George Burgess IVd4febd12016-03-22 21:25:08 +0000316 // FIXME: When we can selectively preserve passes, preserve the domtree.
Dehao Chen302b69c2016-10-18 20:42:47 +0000317 AU.addRequired<ProfileSummaryInfoWrapperPass>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000318 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000319 AU.addRequired<TargetTransformInfoWrapperPass>();
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000320 AU.addRequired<LoopInfoWrapperPass>();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000321 }
322
Chris Lattnerf2836d12007-03-31 04:06:36 +0000323 private:
James Y Knight72f76bf2018-11-07 15:24:12 +0000324 template <typename F>
325 void resetIteratorIfInvalidatedWhileCalling(BasicBlock *BB, F f) {
326 // Substituting can cause recursive simplifications, which can invalidate
327 // our iterator. Use a WeakTrackingVH to hold onto it in case this
328 // happens.
329 Value *CurValue = &*CurInstIterator;
330 WeakTrackingVH IterHandle(CurValue);
331
332 f();
333
334 // If the iterator instruction was recursively deleted, start over at the
335 // start of the block.
336 if (IterHandle != CurValue) {
337 CurInstIterator = BB->begin();
338 SunkAddrs.clear();
339 }
340 }
341
Sanjay Patelfc580a62015-09-21 23:03:16 +0000342 bool eliminateFallThrough(Function &F);
343 bool eliminateMostlyEmptyBlocks(Function &F);
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000344 BasicBlock *findDestBlockOfMergeableEmptyBlock(BasicBlock *BB);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000345 bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
346 void eliminateMostlyEmptyBlock(BasicBlock *BB);
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000347 bool isMergingEmptyBlockProfitable(BasicBlock *BB, BasicBlock *DestBB,
348 bool isPreheader);
Sanjay Patel3b8974b2017-06-08 20:00:09 +0000349 bool optimizeBlock(BasicBlock &BB, bool &ModifiedDT);
350 bool optimizeInst(Instruction *I, bool &ModifiedDT);
Fangrui Songcb0bab82018-07-16 18:51:40 +0000351 bool optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
352 Type *AccessTy, unsigned AddrSpace);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000353 bool optimizeInlineAsmInst(CallInst *CS);
Sanjay Patel3b8974b2017-06-08 20:00:09 +0000354 bool optimizeCallInst(CallInst *CI, bool &ModifiedDT);
Jun Bum Limdee55652017-04-03 19:20:07 +0000355 bool optimizeExt(Instruction *&I);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000356 bool optimizeExtUses(Instruction *I);
Fangrui Songcb0bab82018-07-16 18:51:40 +0000357 bool optimizeLoadExt(LoadInst *Load);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000358 bool optimizeSelectInst(SelectInst *SI);
Fangrui Songcb0bab82018-07-16 18:51:40 +0000359 bool optimizeShuffleVectorInst(ShuffleVectorInst *SVI);
360 bool optimizeSwitchInst(SwitchInst *SI);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000361 bool optimizeExtractElementInst(Instruction *Inst);
362 bool dupRetToEnableTailCallOpts(BasicBlock *BB);
363 bool placeDbgValues(Function &F);
Jun Bum Lim42301012017-03-17 19:05:21 +0000364 bool canFormExtLd(const SmallVectorImpl<Instruction *> &MovedExts,
365 LoadInst *&LI, Instruction *&Inst, bool HasPromoted);
366 bool tryToPromoteExts(TypePromotionTransaction &TPT,
367 const SmallVectorImpl<Instruction *> &Exts,
368 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
369 unsigned CreatedInstsCost = 0);
Jun Bum Limdee55652017-04-03 19:20:07 +0000370 bool mergeSExts(Function &F);
Haicheng Wu0aae2bc2018-05-10 18:27:36 +0000371 bool splitLargeGEPOffsets();
Jun Bum Limdee55652017-04-03 19:20:07 +0000372 bool performAddressTypePromotion(
373 Instruction *&Inst,
374 bool AllowPromotionWithoutCommonHeader,
375 bool HasPromoted, TypePromotionTransaction &TPT,
376 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000377 bool splitBranchCondition(Function &F);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000378 bool simplifyOffsetableRelocate(Instruction &I);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000379 };
Eugene Zelenko900b6332017-08-29 22:32:07 +0000380
381} // end anonymous namespace
Devang Patel09f162c2007-05-01 21:15:47 +0000382
Devang Patel8c78a0b2007-05-03 01:11:54 +0000383char CodeGenPrepare::ID = 0;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000384
Matthias Braun1527baa2017-05-25 21:26:32 +0000385INITIALIZE_PASS_BEGIN(CodeGenPrepare, DEBUG_TYPE,
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000386 "Optimize for code generation", false, false)
Dehao Chen302b69c2016-10-18 20:42:47 +0000387INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
Matthias Braun1527baa2017-05-25 21:26:32 +0000388INITIALIZE_PASS_END(CodeGenPrepare, DEBUG_TYPE,
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000389 "Optimize for code generation", false, false)
Chris Lattnerf2836d12007-03-31 04:06:36 +0000390
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000391FunctionPass *llvm::createCodeGenPreparePass() { return new CodeGenPrepare(); }
Chris Lattnerf2836d12007-03-31 04:06:36 +0000392
Chris Lattnerf2836d12007-03-31 04:06:36 +0000393bool CodeGenPrepare::runOnFunction(Function &F) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000394 if (skipFunction(F))
Paul Robinson7c99ec52014-03-31 17:43:35 +0000395 return false;
396
Mehdi Amini4fe37982015-07-07 18:45:17 +0000397 DL = &F.getParent()->getDataLayout();
398
Chris Lattnerf2836d12007-03-31 04:06:36 +0000399 bool EverMadeChange = false;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000400 // Clear per function information.
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000401 InsertedInsts.clear();
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000402 PromotedInsts.clear();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000403
Devang Patel8f606d72011-03-24 15:35:25 +0000404 ModifiedDT = false;
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000405 if (auto *TPC = getAnalysisIfAvailable<TargetPassConfig>()) {
406 TM = &TPC->getTM<TargetMachine>();
Igor Laevsky3be81ba2017-02-07 13:27:20 +0000407 SubtargetInfo = TM->getSubtargetImpl(F);
408 TLI = SubtargetInfo->getTargetLowering();
409 TRI = SubtargetInfo->getRegisterInfo();
410 }
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000411 TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000412 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000413 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Teresa Johnsona4ce3bf2017-12-20 17:53:10 +0000414 BPI.reset(new BranchProbabilityInfo(F, *LI));
415 BFI.reset(new BlockFrequencyInfo(F, *BPI, *LI));
Sanjay Patel82d91dd2015-08-11 19:39:36 +0000416 OptSize = F.optForSize();
Evan Cheng0663f232011-03-21 01:19:09 +0000417
Easwaran Raman0d55b552017-11-14 19:31:51 +0000418 ProfileSummaryInfo *PSI =
Vedant Kumare7b789b2018-11-19 05:23:16 +0000419 &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
Dehao Chen302b69c2016-10-18 20:42:47 +0000420 if (ProfileGuidedSectionPrefix) {
Teresa Johnsona4ce3bf2017-12-20 17:53:10 +0000421 if (PSI->isFunctionHotInCallGraph(&F, *BFI))
Dehao Chen302b69c2016-10-18 20:42:47 +0000422 F.setSectionPrefix(".hot");
Teresa Johnsona4ce3bf2017-12-20 17:53:10 +0000423 else if (PSI->isFunctionColdInCallGraph(&F, *BFI))
Teresa Johnson720d9b42017-05-09 01:43:24 +0000424 F.setSectionPrefix(".unlikely");
Dehao Chen302b69c2016-10-18 20:42:47 +0000425 }
426
Preston Gurdcdf540d2012-09-04 18:22:17 +0000427 /// This optimization identifies DIV instructions that can be
428 /// profitably bypassed and carried out with a shorter, faster divide.
Easwaran Raman0d55b552017-11-14 19:31:51 +0000429 if (!OptSize && !PSI->hasHugeWorkingSetSize() && TLI &&
430 TLI->isSlowDivBypassed()) {
Preston Gurd0d67f512012-10-04 21:33:40 +0000431 const DenseMap<unsigned int, unsigned int> &BypassWidths =
432 TLI->getBypassSlowDivWidths();
Eric Christopher49a7d6c2016-01-04 23:18:58 +0000433 BasicBlock* BB = &*F.begin();
434 while (BB != nullptr) {
435 // bypassSlowDivision may create new BBs, but we don't want to reapply the
436 // optimization to those blocks.
437 BasicBlock* Next = BB->getNextNode();
438 EverMadeChange |= bypassSlowDivision(BB, BypassWidths);
439 BB = Next;
440 }
Preston Gurdcdf540d2012-09-04 18:22:17 +0000441 }
442
443 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerc3748562007-04-02 01:35:34 +0000444 // unconditional branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000445 EverMadeChange |= eliminateMostlyEmptyBlocks(F);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000446
Geoff Berry5d534b62017-02-21 18:53:14 +0000447 if (!DisableBranchOpts)
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000448 EverMadeChange |= splitBranchCondition(F);
Tim Northovercea0abb2014-03-29 08:22:29 +0000449
Michael Kuperstein13bf8a22017-02-28 00:11:34 +0000450 // Split some critical edges where one of the sources is an indirect branch,
451 // to help generate sane code for PHIs involving such edges.
Hiroshi Yamauchi9364fa32017-12-04 20:36:01 +0000452 EverMadeChange |= SplitIndirectBrCriticalEdges(F);
Michael Kuperstein13bf8a22017-02-28 00:11:34 +0000453
Chris Lattnerc3748562007-04-02 01:35:34 +0000454 bool MadeChange = true;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000455 while (MadeChange) {
456 MadeChange = false;
Hans Wennborg02fbc712012-09-19 07:48:16 +0000457 for (Function::iterator I = F.begin(); I != F.end(); ) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000458 BasicBlock *BB = &*I++;
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000459 bool ModifiedDTOnIteration = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +0000460 MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000461
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000462 // Restart BB iteration if the dominator tree of the Function was changed
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000463 if (ModifiedDTOnIteration)
464 break;
Evan Cheng0663f232011-03-21 01:19:09 +0000465 }
Jun Bum Limdee55652017-04-03 19:20:07 +0000466 if (EnableTypePromotionMerge && !ValToSExtendedUses.empty())
467 MadeChange |= mergeSExts(F);
Haicheng Wu0aae2bc2018-05-10 18:27:36 +0000468 if (!LargeOffsetGEPMap.empty())
469 MadeChange |= splitLargeGEPOffsets();
Jun Bum Limdee55652017-04-03 19:20:07 +0000470
471 // Really free removed instructions during promotion.
472 for (Instruction *I : RemovedInsts)
Reid Kleckner96ab8722017-05-18 17:24:10 +0000473 I->deleteValue();
Jun Bum Limdee55652017-04-03 19:20:07 +0000474
Chris Lattnerf2836d12007-03-31 04:06:36 +0000475 EverMadeChange |= MadeChange;
Peter Collingbourneabd820a2018-10-23 21:23:18 +0000476 SeenChainsForSExt.clear();
477 ValToSExtendedUses.clear();
478 RemovedInsts.clear();
479 LargeOffsetGEPMap.clear();
480 LargeOffsetGEPID.clear();
Chris Lattnerf2836d12007-03-31 04:06:36 +0000481 }
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000482
483 SunkAddrs.clear();
484
Cameron Zwarich338d3622011-03-11 21:52:04 +0000485 if (!DisableBranchOpts) {
486 MadeChange = false;
David Stenberg23bba562018-07-02 14:23:48 +0000487 // Use a set vector to get deterministic iteration order. The order the
488 // blocks are removed may affect whether or not PHI nodes in successors
489 // are removed.
490 SmallSetVector<BasicBlock*, 8> WorkList;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +0000491 for (BasicBlock &BB : F) {
492 SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
493 MadeChange |= ConstantFoldTerminator(&BB, true);
Bill Wendling97b93592012-03-04 10:46:01 +0000494 if (!MadeChange) continue;
495
496 for (SmallVectorImpl<BasicBlock*>::iterator
497 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
498 if (pred_begin(*II) == pred_end(*II))
499 WorkList.insert(*II);
500 }
501
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000502 // Delete the dead blocks and any of their dead successors.
Bill Wendlingab417b62012-12-06 00:30:20 +0000503 MadeChange |= !WorkList.empty();
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000504 while (!WorkList.empty()) {
David Stenberg23bba562018-07-02 14:23:48 +0000505 BasicBlock *BB = WorkList.pop_back_val();
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000506 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
507
508 DeleteDeadBlock(BB);
Stephen Lin837bba12013-07-15 17:55:02 +0000509
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000510 for (SmallVectorImpl<BasicBlock*>::iterator
511 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
512 if (pred_begin(*II) == pred_end(*II))
513 WorkList.insert(*II);
514 }
Cameron Zwarich338d3622011-03-11 21:52:04 +0000515
Nadav Rotem70409992012-08-14 05:19:07 +0000516 // Merge pairs of basic blocks with unconditional branches, connected by
517 // a single edge.
518 if (EverMadeChange || MadeChange)
Sanjay Patelfc580a62015-09-21 23:03:16 +0000519 MadeChange |= eliminateFallThrough(F);
Nadav Rotem70409992012-08-14 05:19:07 +0000520
Cameron Zwarich338d3622011-03-11 21:52:04 +0000521 EverMadeChange |= MadeChange;
522 }
523
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000524 if (!DisableGCOpts) {
525 SmallVector<Instruction *, 2> Statepoints;
526 for (BasicBlock &BB : F)
527 for (Instruction &I : BB)
528 if (isStatepoint(I))
529 Statepoints.push_back(&I);
530 for (auto &I : Statepoints)
531 EverMadeChange |= simplifyOffsetableRelocate(*I);
532 }
533
Vedant Kumar30406fd2018-08-21 23:43:08 +0000534 // Do this last to clean up use-before-def scenarios introduced by other
535 // preparatory transforms.
536 EverMadeChange |= placeDbgValues(F);
537
Chris Lattnerf2836d12007-03-31 04:06:36 +0000538 return EverMadeChange;
539}
540
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000541/// Merge basic blocks which are connected by a single edge, where one of the
542/// basic blocks has a single successor pointing to the other basic block,
543/// which has a single predecessor.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000544bool CodeGenPrepare::eliminateFallThrough(Function &F) {
Nadav Rotem70409992012-08-14 05:19:07 +0000545 bool Changed = false;
546 // Scan all of the blocks in the function, except for the entry block.
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000547 // Use a temporary array to avoid iterator being invalidated when
548 // deleting blocks.
549 SmallVector<WeakTrackingVH, 16> Blocks;
550 for (auto &Block : llvm::make_range(std::next(F.begin()), F.end()))
551 Blocks.push_back(&Block);
552
553 for (auto &Block : Blocks) {
554 auto *BB = cast_or_null<BasicBlock>(Block);
555 if (!BB)
556 continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000557 // If the destination block has a single pred, then this is a trivial
558 // edge, just collapse it.
559 BasicBlock *SinglePred = BB->getSinglePredecessor();
560
Evan Cheng64a223a2012-09-28 23:58:57 +0000561 // Don't merge if BB's address is taken.
562 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000563
564 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
565 if (Term && !Term->isConditional()) {
566 Changed = true;
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000567 LLVM_DEBUG(dbgs() << "To merge:\n" << *BB << "\n\n\n");
Nadav Rotem70409992012-08-14 05:19:07 +0000568
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000569 // Merge BB into SinglePred and delete it.
570 MergeBlockIntoPredecessor(BB);
Nadav Rotem70409992012-08-14 05:19:07 +0000571 }
572 }
573 return Changed;
574}
575
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000576/// Find a destination block from BB if BB is mergeable empty block.
577BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) {
578 // If this block doesn't end with an uncond branch, ignore it.
579 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
580 if (!BI || !BI->isUnconditional())
581 return nullptr;
582
583 // If the instruction before the branch (skipping debug info) isn't a phi
584 // node, then other stuff is happening here.
585 BasicBlock::iterator BBI = BI->getIterator();
586 if (BBI != BB->begin()) {
587 --BBI;
588 while (isa<DbgInfoIntrinsic>(BBI)) {
589 if (BBI == BB->begin())
590 break;
591 --BBI;
592 }
593 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
594 return nullptr;
595 }
596
597 // Do not break infinite loops.
598 BasicBlock *DestBB = BI->getSuccessor(0);
599 if (DestBB == BB)
600 return nullptr;
601
602 if (!canMergeBlocks(BB, DestBB))
603 DestBB = nullptr;
604
605 return DestBB;
606}
607
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000608/// Eliminate blocks that contain only PHI nodes, debug info directives, and an
609/// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
610/// edges in ways that are non-optimal for isel. Start by eliminating these
611/// blocks so we can split them the way we want them.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000612bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000613 SmallPtrSet<BasicBlock *, 16> Preheaders;
614 SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end());
615 while (!LoopList.empty()) {
616 Loop *L = LoopList.pop_back_val();
617 LoopList.insert(LoopList.end(), L->begin(), L->end());
618 if (BasicBlock *Preheader = L->getLoopPreheader())
619 Preheaders.insert(Preheader);
620 }
621
Chris Lattnerc3748562007-04-02 01:35:34 +0000622 bool MadeChange = false;
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000623 // Copy blocks into a temporary array to avoid iterator invalidation issues
624 // as we remove them.
Chris Lattnerc3748562007-04-02 01:35:34 +0000625 // Note that this intentionally skips the entry block.
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000626 SmallVector<WeakTrackingVH, 16> Blocks;
627 for (auto &Block : llvm::make_range(std::next(F.begin()), F.end()))
628 Blocks.push_back(&Block);
629
630 for (auto &Block : Blocks) {
631 BasicBlock *BB = cast_or_null<BasicBlock>(Block);
632 if (!BB)
633 continue;
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000634 BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB);
635 if (!DestBB ||
636 !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.count(BB)))
Chris Lattnerc3748562007-04-02 01:35:34 +0000637 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000638
Sanjay Patelfc580a62015-09-21 23:03:16 +0000639 eliminateMostlyEmptyBlock(BB);
Chris Lattnerc3748562007-04-02 01:35:34 +0000640 MadeChange = true;
641 }
642 return MadeChange;
643}
644
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000645bool CodeGenPrepare::isMergingEmptyBlockProfitable(BasicBlock *BB,
646 BasicBlock *DestBB,
647 bool isPreheader) {
648 // Do not delete loop preheaders if doing so would create a critical edge.
649 // Loop preheaders can be good locations to spill registers. If the
650 // preheader is deleted and we create a critical edge, registers may be
651 // spilled in the loop body instead.
652 if (!DisablePreheaderProtect && isPreheader &&
653 !(BB->getSinglePredecessor() &&
654 BB->getSinglePredecessor()->getSingleSuccessor()))
655 return false;
656
657 // Try to skip merging if the unique predecessor of BB is terminated by a
658 // switch or indirect branch instruction, and BB is used as an incoming block
659 // of PHIs in DestBB. In such case, merging BB and DestBB would cause ISel to
660 // add COPY instructions in the predecessor of BB instead of BB (if it is not
661 // merged). Note that the critical edge created by merging such blocks wont be
662 // split in MachineSink because the jump table is not analyzable. By keeping
663 // such empty block (BB), ISel will place COPY instructions in BB, not in the
664 // predecessor of BB.
665 BasicBlock *Pred = BB->getUniquePredecessor();
666 if (!Pred ||
667 !(isa<SwitchInst>(Pred->getTerminator()) ||
668 isa<IndirectBrInst>(Pred->getTerminator())))
669 return true;
670
Jonas Devlieghere42243df2018-08-07 12:14:01 +0000671 if (BB->getTerminator() != BB->getFirstNonPHIOrDbg())
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000672 return true;
673
674 // We use a simple cost heuristic which determine skipping merging is
675 // profitable if the cost of skipping merging is less than the cost of
676 // merging : Cost(skipping merging) < Cost(merging BB), where the
677 // Cost(skipping merging) is Freq(BB) * (Cost(Copy) + Cost(Branch)), and
678 // the Cost(merging BB) is Freq(Pred) * Cost(Copy).
679 // Assuming Cost(Copy) == Cost(Branch), we could simplify it to :
680 // Freq(Pred) / Freq(BB) > 2.
681 // Note that if there are multiple empty blocks sharing the same incoming
682 // value for the PHIs in the DestBB, we consider them together. In such
683 // case, Cost(merging BB) will be the sum of their frequencies.
684
685 if (!isa<PHINode>(DestBB->begin()))
686 return true;
687
688 SmallPtrSet<BasicBlock *, 16> SameIncomingValueBBs;
689
690 // Find all other incoming blocks from which incoming values of all PHIs in
691 // DestBB are the same as the ones from BB.
692 for (pred_iterator PI = pred_begin(DestBB), E = pred_end(DestBB); PI != E;
693 ++PI) {
694 BasicBlock *DestBBPred = *PI;
695 if (DestBBPred == BB)
696 continue;
697
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000698 if (llvm::all_of(DestBB->phis(), [&](const PHINode &DestPN) {
699 return DestPN.getIncomingValueForBlock(BB) ==
700 DestPN.getIncomingValueForBlock(DestBBPred);
701 }))
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000702 SameIncomingValueBBs.insert(DestBBPred);
703 }
704
705 // See if all BB's incoming values are same as the value from Pred. In this
706 // case, no reason to skip merging because COPYs are expected to be place in
707 // Pred already.
708 if (SameIncomingValueBBs.count(Pred))
709 return true;
710
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000711 BlockFrequency PredFreq = BFI->getBlockFreq(Pred);
712 BlockFrequency BBFreq = BFI->getBlockFreq(BB);
713
714 for (auto SameValueBB : SameIncomingValueBBs)
715 if (SameValueBB->getUniquePredecessor() == Pred &&
716 DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB))
717 BBFreq += BFI->getBlockFreq(SameValueBB);
718
719 return PredFreq.getFrequency() <=
720 BBFreq.getFrequency() * FreqRatioToSkipMerge;
721}
722
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000723/// Return true if we can merge BB into DestBB if there is a single
724/// unconditional branch between them, and BB contains no other non-phi
Chris Lattnerc3748562007-04-02 01:35:34 +0000725/// instructions.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000726bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
Chris Lattnerc3748562007-04-02 01:35:34 +0000727 const BasicBlock *DestBB) const {
728 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
729 // the successor. If there are more complex condition (e.g. preheaders),
730 // don't mess around with them.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000731 for (const PHINode &PN : BB->phis()) {
732 for (const User *U : PN.users()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000733 const Instruction *UI = cast<Instruction>(U);
734 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
Chris Lattnerc3748562007-04-02 01:35:34 +0000735 return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000736 // If User is inside DestBB block and it is a PHINode then check
737 // incoming value. If incoming value is not from BB then this is
Devang Pateld3208522007-04-25 00:37:04 +0000738 // a complex condition (e.g. preheaders) we want to avoid here.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000739 if (UI->getParent() == DestBB) {
740 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
Devang Pateld3208522007-04-25 00:37:04 +0000741 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
742 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
743 if (Insn && Insn->getParent() == BB &&
744 Insn->getParent() != UPN->getIncomingBlock(I))
745 return false;
746 }
747 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000748 }
749 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000750
Chris Lattnerc3748562007-04-02 01:35:34 +0000751 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
752 // and DestBB may have conflicting incoming values for the block. If so, we
753 // can't merge the block.
754 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
755 if (!DestBBPN) return true; // no conflict.
Eric Christopherc1ea1492008-09-24 05:32:41 +0000756
Chris Lattnerc3748562007-04-02 01:35:34 +0000757 // Collect the preds of BB.
Chris Lattner8201a9b2007-11-06 22:07:40 +0000758 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerc3748562007-04-02 01:35:34 +0000759 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
760 // It is faster to get preds from a PHI than with pred_iterator.
761 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
762 BBPreds.insert(BBPN->getIncomingBlock(i));
763 } else {
764 BBPreds.insert(pred_begin(BB), pred_end(BB));
765 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000766
Chris Lattnerc3748562007-04-02 01:35:34 +0000767 // Walk the preds of DestBB.
768 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
769 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
770 if (BBPreds.count(Pred)) { // Common predecessor?
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000771 for (const PHINode &PN : DestBB->phis()) {
772 const Value *V1 = PN.getIncomingValueForBlock(Pred);
773 const Value *V2 = PN.getIncomingValueForBlock(BB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000774
Chris Lattnerc3748562007-04-02 01:35:34 +0000775 // If V2 is a phi node in BB, look up what the mapped value will be.
776 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
777 if (V2PN->getParent() == BB)
778 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000779
Chris Lattnerc3748562007-04-02 01:35:34 +0000780 // If there is a conflict, bail out.
781 if (V1 != V2) return false;
782 }
783 }
784 }
785
786 return true;
787}
788
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000789/// Eliminate a basic block that has only phi's and an unconditional branch in
790/// it.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000791void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000792 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
793 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000794
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000795 LLVM_DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n"
796 << *BB << *DestBB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000797
Chris Lattnerc3748562007-04-02 01:35:34 +0000798 // If the destination block has a single pred, then this is a trivial edge,
799 // just collapse it.
Chris Lattner4059f432008-11-27 19:29:14 +0000800 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattner8a172da2008-11-28 19:54:49 +0000801 if (SinglePred != DestBB) {
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000802 assert(SinglePred == BB &&
803 "Single predecessor not the same as predecessor");
804 // Merge DestBB into SinglePred/BB and delete it.
805 MergeBlockIntoPredecessor(DestBB);
806 // Note: BB(=SinglePred) will not be deleted on this path.
807 // DestBB(=its single successor) is the one that was deleted.
808 LLVM_DEBUG(dbgs() << "AFTER:\n" << *SinglePred << "\n\n\n");
Chris Lattner8a172da2008-11-28 19:54:49 +0000809 return;
810 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000811 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000812
Chris Lattnerc3748562007-04-02 01:35:34 +0000813 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
814 // to handle the new incoming edges it is about to have.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000815 for (PHINode &PN : DestBB->phis()) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000816 // Remove the incoming value for BB, and remember it.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000817 Value *InVal = PN.removeIncomingValue(BB, false);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000818
Chris Lattnerc3748562007-04-02 01:35:34 +0000819 // Two options: either the InVal is a phi node defined in BB or it is some
820 // value that dominates BB.
821 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
822 if (InValPhi && InValPhi->getParent() == BB) {
823 // Add all of the input values of the input PHI as inputs of this phi.
824 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000825 PN.addIncoming(InValPhi->getIncomingValue(i),
826 InValPhi->getIncomingBlock(i));
Chris Lattnerc3748562007-04-02 01:35:34 +0000827 } else {
828 // Otherwise, add one instance of the dominating value for each edge that
829 // we will be adding.
830 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
831 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000832 PN.addIncoming(InVal, BBPN->getIncomingBlock(i));
Chris Lattnerc3748562007-04-02 01:35:34 +0000833 } else {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000834 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000835 PN.addIncoming(InVal, *PI);
Chris Lattnerc3748562007-04-02 01:35:34 +0000836 }
837 }
838 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000839
Chris Lattnerc3748562007-04-02 01:35:34 +0000840 // The PHIs are now updated, change everything that refers to BB to use
841 // DestBB and remove BB.
842 BB->replaceAllUsesWith(DestBB);
843 BB->eraseFromParent();
Cameron Zwarichced753f2011-01-05 17:27:27 +0000844 ++NumBlocksElim;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000845
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000846 LLVM_DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerc3748562007-04-02 01:35:34 +0000847}
848
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000849// Computes a map of base pointer relocation instructions to corresponding
850// derived pointer relocation instructions given a vector of all relocate calls
851static void computeBaseDerivedRelocateMap(
Manuel Jacob83eefa62016-01-05 04:03:00 +0000852 const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
853 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>>
854 &RelocateInstMap) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000855 // Collect information in two maps: one primarily for locating the base object
856 // while filling the second map; the second map is the final structure holding
857 // a mapping between Base and corresponding Derived relocate calls
Manuel Jacob83eefa62016-01-05 04:03:00 +0000858 DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap;
859 for (auto *ThisRelocate : AllRelocateCalls) {
860 auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
861 ThisRelocate->getDerivedPtrIndex());
862 RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000863 }
864 for (auto &Item : RelocateIdxMap) {
865 std::pair<unsigned, unsigned> Key = Item.first;
866 if (Key.first == Key.second)
867 // Base relocation: nothing to insert
868 continue;
869
Manuel Jacob83eefa62016-01-05 04:03:00 +0000870 GCRelocateInst *I = Item.second;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000871 auto BaseKey = std::make_pair(Key.first, Key.first);
Sanjoy Dasb8186762015-02-27 02:24:16 +0000872
873 // We're iterating over RelocateIdxMap so we cannot modify it.
874 auto MaybeBase = RelocateIdxMap.find(BaseKey);
875 if (MaybeBase == RelocateIdxMap.end())
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000876 // TODO: We might want to insert a new base object relocate and gep off
877 // that, if there are enough derived object relocates.
878 continue;
Sanjoy Dasb8186762015-02-27 02:24:16 +0000879
880 RelocateInstMap[MaybeBase->second].push_back(I);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000881 }
882}
883
884// Accepts a GEP and extracts the operands into a vector provided they're all
885// small integer constants
886static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
887 SmallVectorImpl<Value *> &OffsetV) {
888 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
889 // Only accept small constant integer operands
890 auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
891 if (!Op || Op->getZExtValue() > 20)
892 return false;
893 }
894
895 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
896 OffsetV.push_back(GEP->getOperand(i));
897 return true;
898}
899
900// Takes a RelocatedBase (base pointer relocation instruction) and Targets to
901// replace, computes a replacement, and affects it.
902static bool
Manuel Jacob83eefa62016-01-05 04:03:00 +0000903simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase,
904 const SmallVectorImpl<GCRelocateInst *> &Targets) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000905 bool MadeChange = false;
Serguei Katkov9e5604d2017-08-17 05:48:30 +0000906 // We must ensure the relocation of derived pointer is defined after
907 // relocation of base pointer. If we find a relocation corresponding to base
908 // defined earlier than relocation of base then we move relocation of base
909 // right before found relocation. We consider only relocation in the same
910 // basic block as relocation of base. Relocations from other basic block will
911 // be skipped by optimization and we do not care about them.
912 for (auto R = RelocatedBase->getParent()->getFirstInsertionPt();
913 &*R != RelocatedBase; ++R)
914 if (auto RI = dyn_cast<GCRelocateInst>(R))
915 if (RI->getStatepoint() == RelocatedBase->getStatepoint())
916 if (RI->getBasePtrIndex() == RelocatedBase->getBasePtrIndex()) {
917 RelocatedBase->moveBefore(RI);
918 break;
919 }
920
Manuel Jacob83eefa62016-01-05 04:03:00 +0000921 for (GCRelocateInst *ToReplace : Targets) {
922 assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000923 "Not relocating a derived object of the original base object");
Manuel Jacob83eefa62016-01-05 04:03:00 +0000924 if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000925 // A duplicate relocate call. TODO: coalesce duplicates.
926 continue;
927 }
928
Igor Laevskyf637b4a2015-11-03 18:37:40 +0000929 if (RelocatedBase->getParent() != ToReplace->getParent()) {
930 // Base and derived relocates are in different basic blocks.
931 // In this case transform is only valid when base dominates derived
932 // relocate. However it would be too expensive to check dominance
933 // for each such relocate, so we skip the whole transformation.
934 continue;
935 }
936
Manuel Jacob83eefa62016-01-05 04:03:00 +0000937 Value *Base = ToReplace->getBasePtr();
938 auto Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000939 if (!Derived || Derived->getPointerOperand() != Base)
940 continue;
941
942 SmallVector<Value *, 2> OffsetV;
943 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
944 continue;
945
946 // Create a Builder and replace the target callsite with a gep
Sanjay Patel545a4562016-01-20 18:59:16 +0000947 assert(RelocatedBase->getNextNode() &&
948 "Should always have one since it's not a terminator");
Sanjoy Das3d705e32015-05-11 23:47:30 +0000949
950 // Insert after RelocatedBase
951 IRBuilder<> Builder(RelocatedBase->getNextNode());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000952 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
Sanjoy Das89c54912015-05-11 18:49:34 +0000953
954 // If gc_relocate does not match the actual type, cast it to the right type.
955 // In theory, there must be a bitcast after gc_relocate if the type does not
956 // match, and we should reuse it to get the derived pointer. But it could be
957 // cases like this:
958 // bb1:
959 // ...
960 // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
961 // br label %merge
962 //
963 // bb2:
964 // ...
965 // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
966 // br label %merge
967 //
968 // merge:
969 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
970 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
971 //
972 // In this case, we can not find the bitcast any more. So we insert a new bitcast
973 // no matter there is already one or not. In this way, we can handle all cases, and
974 // the extra bitcast should be optimized away in later passes.
Manuel Jacob5b90b142015-12-19 18:38:42 +0000975 Value *ActualRelocatedBase = RelocatedBase;
Sanjoy Das89c54912015-05-11 18:49:34 +0000976 if (RelocatedBase->getType() != Base->getType()) {
977 ActualRelocatedBase =
Manuel Jacob5b90b142015-12-19 18:38:42 +0000978 Builder.CreateBitCast(RelocatedBase, Base->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +0000979 }
David Blaikie68d535c2015-03-24 22:38:16 +0000980 Value *Replacement = Builder.CreateGEP(
Sanjoy Das89c54912015-05-11 18:49:34 +0000981 Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000982 Replacement->takeName(ToReplace);
Sanjoy Das89c54912015-05-11 18:49:34 +0000983 // If the newly generated derived pointer's type does not match the original derived
984 // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
Manuel Jacob5b90b142015-12-19 18:38:42 +0000985 Value *ActualReplacement = Replacement;
986 if (Replacement->getType() != ToReplace->getType()) {
Sanjoy Das89c54912015-05-11 18:49:34 +0000987 ActualReplacement =
Manuel Jacob5b90b142015-12-19 18:38:42 +0000988 Builder.CreateBitCast(Replacement, ToReplace->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +0000989 }
990 ToReplace->replaceAllUsesWith(ActualReplacement);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000991 ToReplace->eraseFromParent();
992
993 MadeChange = true;
994 }
995 return MadeChange;
996}
997
998// Turns this:
999//
1000// %base = ...
1001// %ptr = gep %base + 15
1002// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1003// %base' = relocate(%tok, i32 4, i32 4)
1004// %ptr' = relocate(%tok, i32 4, i32 5)
1005// %val = load %ptr'
1006//
1007// into this:
1008//
1009// %base = ...
1010// %ptr = gep %base + 15
1011// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1012// %base' = gc.relocate(%tok, i32 4, i32 4)
1013// %ptr' = gep %base' + 15
1014// %val = load %ptr'
1015bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
1016 bool MadeChange = false;
Manuel Jacob83eefa62016-01-05 04:03:00 +00001017 SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001018
1019 for (auto *U : I.users())
Manuel Jacob83eefa62016-01-05 04:03:00 +00001020 if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001021 // Collect all the relocate calls associated with a statepoint
Manuel Jacob83eefa62016-01-05 04:03:00 +00001022 AllRelocateCalls.push_back(Relocate);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001023
1024 // We need atleast one base pointer relocation + one derived pointer
1025 // relocation to mangle
1026 if (AllRelocateCalls.size() < 2)
1027 return false;
1028
1029 // RelocateInstMap is a mapping from the base relocate instruction to the
1030 // corresponding derived relocate instructions
Manuel Jacob83eefa62016-01-05 04:03:00 +00001031 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001032 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
1033 if (RelocateInstMap.empty())
1034 return false;
1035
1036 for (auto &Item : RelocateInstMap)
1037 // Item.first is the RelocatedBase to offset against
1038 // Item.second is the vector of Targets to replace
1039 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
1040 return MadeChange;
1041}
1042
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001043/// SinkCast - Sink the specified cast instruction into its user blocks
1044static bool SinkCast(CastInst *CI) {
Chris Lattnerf2836d12007-03-31 04:06:36 +00001045 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001046
Chris Lattnerf2836d12007-03-31 04:06:36 +00001047 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001048 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001049
Chris Lattnerf2836d12007-03-31 04:06:36 +00001050 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001051 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Chris Lattnerf2836d12007-03-31 04:06:36 +00001052 UI != E; ) {
1053 Use &TheUse = UI.getUse();
1054 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +00001055
Chris Lattnerf2836d12007-03-31 04:06:36 +00001056 // Figure out which BB this cast is used in. For PHI's this is the
1057 // appropriate predecessor block.
1058 BasicBlock *UserBB = User->getParent();
1059 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001060 UserBB = PN->getIncomingBlock(TheUse);
Chris Lattnerf2836d12007-03-31 04:06:36 +00001061 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001062
Chris Lattnerf2836d12007-03-31 04:06:36 +00001063 // Preincrement use iterator so we don't invalidate it.
1064 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001065
David Majnemer0c80e2e2016-04-27 19:36:38 +00001066 // The first insertion point of a block containing an EH pad is after the
1067 // pad. If the pad is the user, we cannot sink the cast past the pad.
1068 if (User->isEHPad())
1069 continue;
1070
Andrew Kaylord0430e82015-11-23 19:16:15 +00001071 // If the block selected to receive the cast is an EH pad that does not
1072 // allow non-PHI instructions before the terminator, we can't sink the
1073 // cast.
1074 if (UserBB->getTerminator()->isEHPad())
1075 continue;
1076
Chris Lattnerf2836d12007-03-31 04:06:36 +00001077 // If this user is in the same block as the cast, don't change the cast.
1078 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001079
Chris Lattnerf2836d12007-03-31 04:06:36 +00001080 // If we have already inserted a cast into this block, use it.
1081 CastInst *&InsertedCast = InsertedCasts[UserBB];
1082
1083 if (!InsertedCast) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00001084 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001085 assert(InsertPt != UserBB->end());
1086 InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
1087 CI->getType(), "", &*InsertPt);
Vedant Kumar9374c042018-05-23 22:03:48 +00001088 InsertedCast->setDebugLoc(CI->getDebugLoc());
Chris Lattnerf2836d12007-03-31 04:06:36 +00001089 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001090
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001091 // Replace a use of the cast with a use of the new cast.
Chris Lattnerf2836d12007-03-31 04:06:36 +00001092 TheUse = InsertedCast;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001093 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +00001094 ++NumCastUses;
Chris Lattnerf2836d12007-03-31 04:06:36 +00001095 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001096
Chris Lattnerf2836d12007-03-31 04:06:36 +00001097 // If we removed all uses, nuke the cast.
Duncan Sandsafa84da42008-01-20 16:51:46 +00001098 if (CI->use_empty()) {
Adrian Prantl261ac8b2017-11-03 21:55:03 +00001099 salvageDebugInfo(*CI);
Chris Lattnerf2836d12007-03-31 04:06:36 +00001100 CI->eraseFromParent();
Duncan Sandsafa84da42008-01-20 16:51:46 +00001101 MadeChange = true;
1102 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001103
Chris Lattnerf2836d12007-03-31 04:06:36 +00001104 return MadeChange;
1105}
1106
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001107/// If the specified cast instruction is a noop copy (e.g. it's casting from
1108/// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
1109/// reduce the number of virtual registers that must be created and coalesced.
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001110///
1111/// Return true if any changes are made.
Mehdi Amini44ede332015-07-09 02:09:04 +00001112static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
1113 const DataLayout &DL) {
Justin Lebar3e50a5b2016-11-21 22:49:15 +00001114 // Sink only "cheap" (or nop) address-space casts. This is a weaker condition
1115 // than sinking only nop casts, but is helpful on some platforms.
1116 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(CI)) {
1117 if (!TLI.isCheapAddrSpaceCast(ASC->getSrcAddressSpace(),
1118 ASC->getDestAddressSpace()))
1119 return false;
1120 }
1121
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001122 // If this is a noop copy,
Mehdi Amini44ede332015-07-09 02:09:04 +00001123 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
1124 EVT DstVT = TLI.getValueType(DL, CI->getType());
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001125
1126 // This is an fp<->int conversion?
1127 if (SrcVT.isInteger() != DstVT.isInteger())
1128 return false;
1129
1130 // If this is an extension, it will be a zero or sign extension, which
1131 // isn't a noop.
1132 if (SrcVT.bitsLT(DstVT)) return false;
1133
1134 // If these values will be promoted, find out what they will be promoted
1135 // to. This helps us consider truncates on PPC as noop copies when they
1136 // are.
1137 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
1138 TargetLowering::TypePromoteInteger)
1139 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
1140 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
1141 TargetLowering::TypePromoteInteger)
1142 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
1143
1144 // If, after promotion, these are the same types, this is a noop copy.
1145 if (SrcVT != DstVT)
1146 return false;
1147
1148 return SinkCast(CI);
1149}
1150
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001151/// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if
1152/// possible.
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001153///
1154/// Return true if any changes were made.
1155static bool CombineUAddWithOverflow(CmpInst *CI) {
1156 Value *A, *B;
1157 Instruction *AddI;
1158 if (!match(CI,
1159 m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI))))
1160 return false;
1161
1162 Type *Ty = AddI->getType();
1163 if (!isa<IntegerType>(Ty))
1164 return false;
1165
1166 // We don't want to move around uses of condition values this late, so we we
1167 // check if it is legal to create the call to the intrinsic in the basic
1168 // block containing the icmp:
1169
1170 if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse())
1171 return false;
1172
1173#ifndef NDEBUG
1174 // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
1175 // for now:
1176 if (AddI->hasOneUse())
1177 assert(*AddI->user_begin() == CI && "expected!");
1178#endif
1179
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001180 Module *M = CI->getModule();
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001181 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
1182
1183 auto *InsertPt = AddI->hasOneUse() ? CI : AddI;
1184
Vedant Kumara85ca3d2018-08-22 18:15:03 +00001185 DebugLoc Loc = CI->getDebugLoc();
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001186 auto *UAddWithOverflow =
1187 CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt);
Vedant Kumara85ca3d2018-08-22 18:15:03 +00001188 UAddWithOverflow->setDebugLoc(Loc);
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001189 auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt);
Vedant Kumara85ca3d2018-08-22 18:15:03 +00001190 UAdd->setDebugLoc(Loc);
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001191 auto *Overflow =
1192 ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt);
Vedant Kumara85ca3d2018-08-22 18:15:03 +00001193 Overflow->setDebugLoc(Loc);
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001194
1195 CI->replaceAllUsesWith(Overflow);
1196 AddI->replaceAllUsesWith(UAdd);
1197 CI->eraseFromParent();
1198 AddI->eraseFromParent();
1199 return true;
1200}
1201
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001202/// Sink the given CmpInst into user blocks to reduce the number of virtual
1203/// registers that must be created and coalesced. This is a clear win except on
1204/// targets with multiple condition code registers (PowerPC), where it might
1205/// lose; some adjustment may be wanted there.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001206///
1207/// Return true if any changes are made.
Peter Zotov8efe38a2016-04-03 19:32:13 +00001208static bool SinkCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001209 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001210
Peter Zotov0b6d7bc2016-04-03 16:36:17 +00001211 // Avoid sinking soft-FP comparisons, since this can move them into a loop.
Peter Zotov8efe38a2016-04-03 19:32:13 +00001212 if (TLI && TLI->useSoftFloat() && isa<FCmpInst>(CI))
Peter Zotov0b6d7bc2016-04-03 16:36:17 +00001213 return false;
1214
1215 // Only insert a cmp in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001216 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001217
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001218 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001219 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001220 UI != E; ) {
1221 Use &TheUse = UI.getUse();
1222 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +00001223
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001224 // Preincrement use iterator so we don't invalidate it.
1225 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001226
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001227 // Don't bother for PHI nodes.
1228 if (isa<PHINode>(User))
1229 continue;
1230
1231 // Figure out which BB this cmp is used in.
1232 BasicBlock *UserBB = User->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001233
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001234 // If this user is in the same block as the cmp, don't change the cmp.
1235 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001236
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001237 // If we have already inserted a cmp into this block, use it.
1238 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
1239
1240 if (!InsertedCmp) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00001241 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001242 assert(InsertPt != UserBB->end());
Eric Christopherc1ea1492008-09-24 05:32:41 +00001243 InsertedCmp =
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001244 CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
1245 CI->getOperand(0), CI->getOperand(1), "", &*InsertPt);
Wolfgang Piebe51bede2016-10-06 21:43:45 +00001246 // Propagate the debug info.
1247 InsertedCmp->setDebugLoc(CI->getDebugLoc());
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001248 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001249
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001250 // Replace a use of the cmp with a use of the new cmp.
1251 TheUse = InsertedCmp;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001252 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +00001253 ++NumCmpUses;
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001254 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001255
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001256 // If we removed all uses, nuke the cmp.
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001257 if (CI->use_empty()) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001258 CI->eraseFromParent();
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001259 MadeChange = true;
1260 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001261
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001262 return MadeChange;
1263}
1264
Peter Zotovf87e5502016-04-03 17:11:53 +00001265static bool OptimizeCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
Peter Zotov8efe38a2016-04-03 19:32:13 +00001266 if (SinkCmpExpression(CI, TLI))
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001267 return true;
1268
1269 if (CombineUAddWithOverflow(CI))
1270 return true;
1271
1272 return false;
1273}
1274
Geoff Berry5d534b62017-02-21 18:53:14 +00001275/// Duplicate and sink the given 'and' instruction into user blocks where it is
1276/// used in a compare to allow isel to generate better code for targets where
1277/// this operation can be combined.
1278///
1279/// Return true if any changes are made.
1280static bool sinkAndCmp0Expression(Instruction *AndI,
1281 const TargetLowering &TLI,
1282 SetOfInstrs &InsertedInsts) {
1283 // Double-check that we're not trying to optimize an instruction that was
1284 // already optimized by some other part of this pass.
1285 assert(!InsertedInsts.count(AndI) &&
1286 "Attempting to optimize already optimized and instruction");
1287 (void) InsertedInsts;
1288
1289 // Nothing to do for single use in same basic block.
1290 if (AndI->hasOneUse() &&
1291 AndI->getParent() == cast<Instruction>(*AndI->user_begin())->getParent())
1292 return false;
1293
1294 // Try to avoid cases where sinking/duplicating is likely to increase register
1295 // pressure.
1296 if (!isa<ConstantInt>(AndI->getOperand(0)) &&
1297 !isa<ConstantInt>(AndI->getOperand(1)) &&
1298 AndI->getOperand(0)->hasOneUse() && AndI->getOperand(1)->hasOneUse())
1299 return false;
1300
1301 for (auto *U : AndI->users()) {
1302 Instruction *User = cast<Instruction>(U);
1303
1304 // Only sink for and mask feeding icmp with 0.
1305 if (!isa<ICmpInst>(User))
1306 return false;
1307
1308 auto *CmpC = dyn_cast<ConstantInt>(User->getOperand(1));
1309 if (!CmpC || !CmpC->isZero())
1310 return false;
1311 }
1312
1313 if (!TLI.isMaskAndCmp0FoldingBeneficial(*AndI))
1314 return false;
1315
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001316 LLVM_DEBUG(dbgs() << "found 'and' feeding only icmp 0;\n");
1317 LLVM_DEBUG(AndI->getParent()->dump());
Geoff Berry5d534b62017-02-21 18:53:14 +00001318
1319 // Push the 'and' into the same block as the icmp 0. There should only be
1320 // one (icmp (and, 0)) in each block, since CSE/GVN should have removed any
1321 // others, so we don't need to keep track of which BBs we insert into.
1322 for (Value::user_iterator UI = AndI->user_begin(), E = AndI->user_end();
1323 UI != E; ) {
1324 Use &TheUse = UI.getUse();
1325 Instruction *User = cast<Instruction>(*UI);
1326
1327 // Preincrement use iterator so we don't invalidate it.
1328 ++UI;
1329
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001330 LLVM_DEBUG(dbgs() << "sinking 'and' use: " << *User << "\n");
Geoff Berry5d534b62017-02-21 18:53:14 +00001331
1332 // Keep the 'and' in the same place if the use is already in the same block.
1333 Instruction *InsertPt =
1334 User->getParent() == AndI->getParent() ? AndI : User;
1335 Instruction *InsertedAnd =
1336 BinaryOperator::Create(Instruction::And, AndI->getOperand(0),
1337 AndI->getOperand(1), "", InsertPt);
1338 // Propagate the debug info.
1339 InsertedAnd->setDebugLoc(AndI->getDebugLoc());
1340
1341 // Replace a use of the 'and' with a use of the new 'and'.
1342 TheUse = InsertedAnd;
1343 ++NumAndUses;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001344 LLVM_DEBUG(User->getParent()->dump());
Geoff Berry5d534b62017-02-21 18:53:14 +00001345 }
1346
1347 // We removed all uses, nuke the and.
1348 AndI->eraseFromParent();
1349 return true;
1350}
1351
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001352/// Check if the candidates could be combined with a shift instruction, which
1353/// includes:
Yi Jiangd069f632014-04-21 19:34:27 +00001354/// 1. Truncate instruction
1355/// 2. And instruction and the imm is a mask of the low bits:
1356/// imm & (imm+1) == 0
Benjamin Kramer322053c2014-04-27 14:54:59 +00001357static bool isExtractBitsCandidateUse(Instruction *User) {
Yi Jiangd069f632014-04-21 19:34:27 +00001358 if (!isa<TruncInst>(User)) {
1359 if (User->getOpcode() != Instruction::And ||
1360 !isa<ConstantInt>(User->getOperand(1)))
1361 return false;
1362
Quentin Colombetd4f44692014-04-22 01:20:34 +00001363 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
Yi Jiangd069f632014-04-21 19:34:27 +00001364
Quentin Colombetd4f44692014-04-22 01:20:34 +00001365 if ((Cimm & (Cimm + 1)).getBoolValue())
Yi Jiangd069f632014-04-21 19:34:27 +00001366 return false;
1367 }
1368 return true;
1369}
1370
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001371/// Sink both shift and truncate instruction to the use of truncate's BB.
Benjamin Kramer322053c2014-04-27 14:54:59 +00001372static bool
Yi Jiangd069f632014-04-21 19:34:27 +00001373SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
1374 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
Mehdi Amini44ede332015-07-09 02:09:04 +00001375 const TargetLowering &TLI, const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001376 BasicBlock *UserBB = User->getParent();
1377 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
1378 TruncInst *TruncI = dyn_cast<TruncInst>(User);
1379 bool MadeChange = false;
1380
1381 for (Value::user_iterator TruncUI = TruncI->user_begin(),
1382 TruncE = TruncI->user_end();
1383 TruncUI != TruncE;) {
1384
1385 Use &TruncTheUse = TruncUI.getUse();
1386 Instruction *TruncUser = cast<Instruction>(*TruncUI);
1387 // Preincrement use iterator so we don't invalidate it.
1388
1389 ++TruncUI;
1390
1391 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
1392 if (!ISDOpcode)
1393 continue;
1394
Tim Northovere2239ff2014-07-29 10:20:22 +00001395 // If the use is actually a legal node, there will not be an
1396 // implicit truncate.
1397 // FIXME: always querying the result type is just an
1398 // approximation; some nodes' legality is determined by the
1399 // operand or other means. There's no good way to find out though.
Ahmed Bougacha0788d492014-11-12 22:16:55 +00001400 if (TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00001401 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
Yi Jiangd069f632014-04-21 19:34:27 +00001402 continue;
1403
1404 // Don't bother for PHI nodes.
1405 if (isa<PHINode>(TruncUser))
1406 continue;
1407
1408 BasicBlock *TruncUserBB = TruncUser->getParent();
1409
1410 if (UserBB == TruncUserBB)
1411 continue;
1412
1413 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
1414 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
1415
1416 if (!InsertedShift && !InsertedTrunc) {
1417 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001418 assert(InsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001419 // Sink the shift
1420 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001421 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1422 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001423 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001424 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1425 "", &*InsertPt);
Vedant Kumar1b02dad2018-09-15 04:08:52 +00001426 InsertedShift->setDebugLoc(ShiftI->getDebugLoc());
Yi Jiangd069f632014-04-21 19:34:27 +00001427
1428 // Sink the trunc
1429 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
1430 TruncInsertPt++;
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001431 assert(TruncInsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001432
1433 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001434 TruncI->getType(), "", &*TruncInsertPt);
Vedant Kumar1b02dad2018-09-15 04:08:52 +00001435 InsertedTrunc->setDebugLoc(TruncI->getDebugLoc());
Yi Jiangd069f632014-04-21 19:34:27 +00001436
1437 MadeChange = true;
1438
1439 TruncTheUse = InsertedTrunc;
1440 }
1441 }
1442 return MadeChange;
1443}
1444
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001445/// Sink the shift *right* instruction into user blocks if the uses could
1446/// potentially be combined with this shift instruction and generate BitExtract
1447/// instruction. It will only be applied if the architecture supports BitExtract
1448/// instruction. Here is an example:
Yi Jiangd069f632014-04-21 19:34:27 +00001449/// BB1:
1450/// %x.extract.shift = lshr i64 %arg1, 32
1451/// BB2:
1452/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
1453/// ==>
1454///
1455/// BB2:
1456/// %x.extract.shift.1 = lshr i64 %arg1, 32
1457/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
1458///
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00001459/// CodeGen will recognize the pattern in BB2 and generate BitExtract
Yi Jiangd069f632014-04-21 19:34:27 +00001460/// instruction.
1461/// Return true if any changes are made.
1462static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
Mehdi Amini44ede332015-07-09 02:09:04 +00001463 const TargetLowering &TLI,
1464 const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001465 BasicBlock *DefBB = ShiftI->getParent();
1466
1467 /// Only insert instructions in each block once.
1468 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
1469
Mehdi Amini44ede332015-07-09 02:09:04 +00001470 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
Yi Jiangd069f632014-04-21 19:34:27 +00001471
1472 bool MadeChange = false;
1473 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
1474 UI != E;) {
1475 Use &TheUse = UI.getUse();
1476 Instruction *User = cast<Instruction>(*UI);
1477 // Preincrement use iterator so we don't invalidate it.
1478 ++UI;
1479
1480 // Don't bother for PHI nodes.
1481 if (isa<PHINode>(User))
1482 continue;
1483
1484 if (!isExtractBitsCandidateUse(User))
1485 continue;
1486
1487 BasicBlock *UserBB = User->getParent();
1488
1489 if (UserBB == DefBB) {
1490 // If the shift and truncate instruction are in the same BB. The use of
1491 // the truncate(TruncUse) may still introduce another truncate if not
1492 // legal. In this case, we would like to sink both shift and truncate
1493 // instruction to the BB of TruncUse.
1494 // for example:
1495 // BB1:
1496 // i64 shift.result = lshr i64 opnd, imm
1497 // trunc.result = trunc shift.result to i16
1498 //
1499 // BB2:
1500 // ----> We will have an implicit truncate here if the architecture does
1501 // not have i16 compare.
1502 // cmp i16 trunc.result, opnd2
1503 //
1504 if (isa<TruncInst>(User) && shiftIsLegal
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00001505 // If the type of the truncate is legal, no truncate will be
Yi Jiangd069f632014-04-21 19:34:27 +00001506 // introduced in other basic blocks.
Mehdi Amini44ede332015-07-09 02:09:04 +00001507 &&
1508 (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
Yi Jiangd069f632014-04-21 19:34:27 +00001509 MadeChange =
Mehdi Amini44ede332015-07-09 02:09:04 +00001510 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
Yi Jiangd069f632014-04-21 19:34:27 +00001511
1512 continue;
1513 }
1514 // If we have already inserted a shift into this block, use it.
1515 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
1516
1517 if (!InsertedShift) {
1518 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001519 assert(InsertPt != UserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001520
1521 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001522 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1523 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001524 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001525 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1526 "", &*InsertPt);
Vedant Kumar1b02dad2018-09-15 04:08:52 +00001527 InsertedShift->setDebugLoc(ShiftI->getDebugLoc());
Yi Jiangd069f632014-04-21 19:34:27 +00001528
1529 MadeChange = true;
1530 }
1531
1532 // Replace a use of the shift with a use of the new shift.
1533 TheUse = InsertedShift;
1534 }
1535
1536 // If we removed all uses, nuke the shift.
Vedant Kumar1b02dad2018-09-15 04:08:52 +00001537 if (ShiftI->use_empty()) {
1538 salvageDebugInfo(*ShiftI);
Yi Jiangd069f632014-04-21 19:34:27 +00001539 ShiftI->eraseFromParent();
Vedant Kumar1b02dad2018-09-15 04:08:52 +00001540 }
Yi Jiangd069f632014-04-21 19:34:27 +00001541
1542 return MadeChange;
1543}
1544
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001545/// If counting leading or trailing zeros is an expensive operation and a zero
1546/// input is defined, add a check for zero to avoid calling the intrinsic.
1547///
1548/// We want to transform:
1549/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
1550///
1551/// into:
1552/// entry:
1553/// %cmpz = icmp eq i64 %A, 0
1554/// br i1 %cmpz, label %cond.end, label %cond.false
1555/// cond.false:
1556/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
1557/// br label %cond.end
1558/// cond.end:
1559/// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
1560///
1561/// If the transform is performed, return true and set ModifiedDT to true.
1562static bool despeculateCountZeros(IntrinsicInst *CountZeros,
1563 const TargetLowering *TLI,
1564 const DataLayout *DL,
1565 bool &ModifiedDT) {
1566 if (!TLI || !DL)
1567 return false;
1568
1569 // If a zero input is undefined, it doesn't make sense to despeculate that.
1570 if (match(CountZeros->getOperand(1), m_One()))
1571 return false;
1572
1573 // If it's cheap to speculate, there's nothing to do.
1574 auto IntrinsicID = CountZeros->getIntrinsicID();
1575 if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) ||
1576 (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz()))
1577 return false;
1578
1579 // Only handle legal scalar cases. Anything else requires too much work.
1580 Type *Ty = CountZeros->getType();
1581 unsigned SizeInBits = Ty->getPrimitiveSizeInBits();
Jun Bum Limbe11bdc2016-05-13 18:38:35 +00001582 if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSizeInBits())
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001583 return false;
1584
1585 // The intrinsic will be sunk behind a compare against zero and branch.
1586 BasicBlock *StartBlock = CountZeros->getParent();
1587 BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
1588
1589 // Create another block after the count zero intrinsic. A PHI will be added
1590 // in this block to select the result of the intrinsic or the bit-width
1591 // constant if the input to the intrinsic is zero.
1592 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
1593 BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
1594
1595 // Set up a builder to create a compare, conditional branch, and PHI.
1596 IRBuilder<> Builder(CountZeros->getContext());
1597 Builder.SetInsertPoint(StartBlock->getTerminator());
1598 Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
1599
1600 // Replace the unconditional branch that was created by the first split with
1601 // a compare against zero and a conditional branch.
1602 Value *Zero = Constant::getNullValue(Ty);
1603 Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz");
1604 Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
1605 StartBlock->getTerminator()->eraseFromParent();
1606
1607 // Create a PHI in the end block to select either the output of the intrinsic
1608 // or the bit width of the operand.
1609 Builder.SetInsertPoint(&EndBlock->front());
1610 PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
1611 CountZeros->replaceAllUsesWith(PN);
1612 Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
1613 PN->addIncoming(BitWidth, StartBlock);
1614 PN->addIncoming(CountZeros, CallBlock);
1615
1616 // We are explicitly handling the zero case, so we can set the intrinsic's
1617 // undefined zero argument to 'true'. This will also prevent reprocessing the
1618 // intrinsic; we only despeculate when a zero input is defined.
1619 CountZeros->setArgOperand(1, Builder.getTrue());
1620 ModifiedDT = true;
1621 return true;
1622}
1623
Sanjay Patel3b8974b2017-06-08 20:00:09 +00001624bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool &ModifiedDT) {
Chris Lattner7a277142011-01-15 07:14:54 +00001625 BasicBlock *BB = CI->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00001626
Chris Lattner7a277142011-01-15 07:14:54 +00001627 // Lower inline assembly if we can.
1628 // If we found an inline asm expession, and if the target knows how to
1629 // lower it to normal LLVM code, do so now.
1630 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
1631 if (TLI->ExpandInlineAsm(CI)) {
1632 // Avoid invalidating the iterator.
1633 CurInstIterator = BB->begin();
1634 // Avoid processing instructions out of order, which could cause
1635 // reuse before a value is defined.
1636 SunkAddrs.clear();
1637 return true;
1638 }
1639 // Sink address computing for memory operands into the block.
Sanjay Patelfc580a62015-09-21 23:03:16 +00001640 if (optimizeInlineAsmInst(CI))
Chris Lattner7a277142011-01-15 07:14:54 +00001641 return true;
1642 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001643
John Brawn0dbcd652015-03-18 12:01:59 +00001644 // Align the pointer arguments to this call if the target thinks it's a good
1645 // idea
1646 unsigned MinSize, PrefAlign;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001647 if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
John Brawn0dbcd652015-03-18 12:01:59 +00001648 for (auto &Arg : CI->arg_operands()) {
1649 // We want to align both objects whose address is used directly and
1650 // objects whose address is used in casts and GEPs, though it only makes
1651 // sense for GEPs if the offset is a multiple of the desired alignment and
1652 // if size - offset meets the size threshold.
1653 if (!Arg->getType()->isPointerTy())
1654 continue;
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00001655 APInt Offset(DL->getIndexSizeInBits(
Mehdi Amini4fe37982015-07-07 18:45:17 +00001656 cast<PointerType>(Arg->getType())->getAddressSpace()),
1657 0);
1658 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
John Brawn0dbcd652015-03-18 12:01:59 +00001659 uint64_t Offset2 = Offset.getLimitedValue();
John Brawne8fd6c82015-04-13 10:47:39 +00001660 if ((Offset2 & (PrefAlign-1)) != 0)
1661 continue;
John Brawn0dbcd652015-03-18 12:01:59 +00001662 AllocaInst *AI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001663 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
1664 DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
John Brawn0dbcd652015-03-18 12:01:59 +00001665 AI->setAlignment(PrefAlign);
John Brawne8fd6c82015-04-13 10:47:39 +00001666 // Global variables can only be aligned if they are defined in this
1667 // object (i.e. they are uniquely initialized in this object), and
1668 // over-aligning global variables that have an explicit section is
1669 // forbidden.
1670 GlobalVariable *GV;
James Y Knightac03dca2016-01-15 16:33:06 +00001671 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
Tim Northover918f0502016-07-18 18:28:52 +00001672 GV->getPointerAlignment(*DL) < PrefAlign &&
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001673 DL->getTypeAllocSize(GV->getValueType()) >=
Mehdi Amini4fe37982015-07-07 18:45:17 +00001674 MinSize + Offset2)
John Brawne8fd6c82015-04-13 10:47:39 +00001675 GV->setAlignment(PrefAlign);
John Brawn0dbcd652015-03-18 12:01:59 +00001676 }
1677 // If this is a memcpy (or similar) then we may be able to improve the
1678 // alignment
1679 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
Daniel Neilsonbe58a222018-01-31 17:24:53 +00001680 unsigned DestAlign = getKnownAlignment(MI->getDest(), *DL);
1681 if (DestAlign > MI->getDestAlignment())
1682 MI->setDestAlignment(DestAlign);
1683 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
1684 unsigned SrcAlign = getKnownAlignment(MTI->getSource(), *DL);
1685 if (SrcAlign > MTI->getSourceAlignment())
1686 MTI->setSourceAlignment(SrcAlign);
1687 }
John Brawn0dbcd652015-03-18 12:01:59 +00001688 }
1689 }
1690
Philip Reamesac115ed2016-03-09 23:13:12 +00001691 // If we have a cold call site, try to sink addressing computation into the
1692 // cold block. This interacts with our handling for loads and stores to
1693 // ensure that we can fold all uses of a potential addressing computation
1694 // into their uses. TODO: generalize this to work over profiling data
1695 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
1696 for (auto &Arg : CI->arg_operands()) {
1697 if (!Arg->getType()->isPointerTy())
1698 continue;
1699 unsigned AS = Arg->getType()->getPointerAddressSpace();
1700 return optimizeMemoryInst(CI, Arg, Arg->getType(), AS);
1701 }
Junmo Park6098cbb2016-03-11 07:05:32 +00001702
Eric Christopher4b7948e2010-03-11 02:41:03 +00001703 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001704 if (II) {
1705 switch (II->getIntrinsicID()) {
1706 default: break;
1707 case Intrinsic::objectsize: {
1708 // Lower all uses of llvm.objectsize.*
George Burgess IV3f089142016-12-20 23:46:36 +00001709 ConstantInt *RetVal =
1710 lowerObjectSizeCall(II, *DL, TLInfo, /*MustSucceed=*/true);
Nadav Rotem465834c2012-07-24 10:51:42 +00001711
James Y Knight72f76bf2018-11-07 15:24:12 +00001712 resetIteratorIfInvalidatedWhileCalling(BB, [&]() {
1713 replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
1714 });
1715 return true;
1716 }
1717 case Intrinsic::is_constant: {
1718 // If is_constant hasn't folded away yet, lower it to false now.
1719 Constant *RetVal = ConstantInt::get(II->getType(), 0);
1720 resetIteratorIfInvalidatedWhileCalling(BB, [&]() {
1721 replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
1722 });
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001723 return true;
Chris Lattner86d56c62011-01-18 20:53:04 +00001724 }
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001725 case Intrinsic::aarch64_stlxr:
1726 case Intrinsic::aarch64_stxr: {
1727 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
1728 if (!ExtVal || !ExtVal->hasOneUse() ||
1729 ExtVal->getParent() == CI->getParent())
1730 return false;
1731 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
1732 ExtVal->moveBefore(CI);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00001733 // Mark this instruction as "inserted by CGP", so that other
1734 // optimizations don't touch it.
1735 InsertedInsts.insert(ExtVal);
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001736 return true;
1737 }
Piotr Padlewski5dde8092018-05-03 11:03:01 +00001738 case Intrinsic::launder_invariant_group:
Krzysztof Pszeniczny2bfe7592018-10-19 19:02:16 +00001739 case Intrinsic::strip_invariant_group: {
1740 Value *ArgVal = II->getArgOperand(0);
1741 auto it = LargeOffsetGEPMap.find(II);
1742 if (it != LargeOffsetGEPMap.end()) {
1743 // Merge entries in LargeOffsetGEPMap to reflect the RAUW.
1744 // Make sure not to have to deal with iterator invalidation
1745 // after possibly adding ArgVal to LargeOffsetGEPMap.
1746 auto GEPs = std::move(it->second);
1747 LargeOffsetGEPMap[ArgVal].append(GEPs.begin(), GEPs.end());
1748 LargeOffsetGEPMap.erase(II);
1749 }
1750
1751 II->replaceAllUsesWith(ArgVal);
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00001752 II->eraseFromParent();
1753 return true;
Krzysztof Pszeniczny2bfe7592018-10-19 19:02:16 +00001754 }
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001755 case Intrinsic::cttz:
1756 case Intrinsic::ctlz:
1757 // If counting zeros is expensive, try to avoid it.
1758 return despeculateCountZeros(II, TLI, DL, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001759 }
Eric Christopher4b7948e2010-03-11 02:41:03 +00001760
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001761 if (TLI) {
1762 SmallVector<Value*, 2> PtrOps;
1763 Type *AccessTy;
Matt Arsenault1672b1b2017-02-08 07:09:03 +00001764 if (TLI->getAddrModeArguments(II, PtrOps, AccessTy))
1765 while (!PtrOps.empty()) {
1766 Value *PtrVal = PtrOps.pop_back_val();
1767 unsigned AS = PtrVal->getType()->getPointerAddressSpace();
1768 if (optimizeMemoryInst(II, PtrVal, AccessTy, AS))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001769 return true;
Matt Arsenault1672b1b2017-02-08 07:09:03 +00001770 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001771 }
Pete Cooper615fd892012-03-13 20:59:56 +00001772 }
1773
Eric Christopher4b7948e2010-03-11 02:41:03 +00001774 // From here on out we're working with named functions.
Craig Topperc0196b12014-04-14 00:51:57 +00001775 if (!CI->getCalledFunction()) return false;
Devang Patel0da52502011-05-26 21:51:06 +00001776
Benjamin Kramer7b88a492010-03-12 09:27:41 +00001777 // Lower all default uses of _chk calls. This is very similar
1778 // to what InstCombineCalls does, but here we are only lowering calls
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001779 // to fortified library functions (e.g. __memcpy_chk) that have the default
1780 // "don't know" as the objectsize. Anything else should be left alone.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001781 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001782 if (Value *V = Simplifier.optimizeCall(CI)) {
1783 CI->replaceAllUsesWith(V);
1784 CI->eraseFromParent();
1785 return true;
1786 }
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001787
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001788 return false;
Eric Christopher4b7948e2010-03-11 02:41:03 +00001789}
Chris Lattner1b93be52011-01-15 07:25:29 +00001790
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001791/// Look for opportunities to duplicate return instructions to the predecessor
1792/// to enable tail call optimizations. The case it is currently looking for is:
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001793/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001794/// bb0:
1795/// %tmp0 = tail call i32 @f0()
1796/// br label %return
1797/// bb1:
1798/// %tmp1 = tail call i32 @f1()
1799/// br label %return
1800/// bb2:
1801/// %tmp2 = tail call i32 @f2()
1802/// br label %return
1803/// return:
1804/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
1805/// ret i32 %retval
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001806/// @endcode
Evan Cheng0663f232011-03-21 01:19:09 +00001807///
1808/// =>
1809///
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001810/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001811/// bb0:
1812/// %tmp0 = tail call i32 @f0()
1813/// ret i32 %tmp0
1814/// bb1:
1815/// %tmp1 = tail call i32 @f1()
1816/// ret i32 %tmp1
1817/// bb2:
1818/// %tmp2 = tail call i32 @f2()
1819/// ret i32 %tmp2
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001820/// @endcode
Sanjay Patelfc580a62015-09-21 23:03:16 +00001821bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich47e71752011-03-24 04:51:51 +00001822 if (!TLI)
1823 return false;
1824
Michael Kuperstein71321562016-09-07 20:29:49 +00001825 ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator());
1826 if (!RetI)
Benjamin Kramer455fa352012-11-23 19:17:06 +00001827 return false;
1828
Craig Topperc0196b12014-04-14 00:51:57 +00001829 PHINode *PN = nullptr;
1830 BitCastInst *BCI = nullptr;
Michael Kuperstein71321562016-09-07 20:29:49 +00001831 Value *V = RetI->getReturnValue();
Evan Cheng249716e2012-07-27 21:21:26 +00001832 if (V) {
1833 BCI = dyn_cast<BitCastInst>(V);
1834 if (BCI)
1835 V = BCI->getOperand(0);
1836
1837 PN = dyn_cast<PHINode>(V);
1838 if (!PN)
1839 return false;
1840 }
Evan Cheng0663f232011-03-21 01:19:09 +00001841
Cameron Zwarich4649f172011-03-24 04:52:10 +00001842 if (PN && PN->getParent() != BB)
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001843 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00001844
Cameron Zwarich4649f172011-03-24 04:52:10 +00001845 // Make sure there are no instructions between the PHI and return, or that the
1846 // return is the first instruction in the block.
1847 if (PN) {
1848 BasicBlock::iterator BI = BB->begin();
1849 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng249716e2012-07-27 21:21:26 +00001850 if (&*BI == BCI)
1851 // Also skip over the bitcast.
1852 ++BI;
Michael Kuperstein71321562016-09-07 20:29:49 +00001853 if (&*BI != RetI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001854 return false;
1855 } else {
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001856 BasicBlock::iterator BI = BB->begin();
1857 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
Michael Kuperstein71321562016-09-07 20:29:49 +00001858 if (&*BI != RetI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001859 return false;
1860 }
Evan Cheng0663f232011-03-21 01:19:09 +00001861
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001862 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
1863 /// call.
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00001864 const Function *F = BB->getParent();
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001865 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich4649f172011-03-24 04:52:10 +00001866 if (PN) {
1867 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
1868 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
1869 // Make sure the phi value is indeed produced by the tail call.
1870 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00001871 TLI->mayBeEmittedAsTailCall(CI) &&
1872 attributesPermitTailCall(F, CI, RetI, *TLI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00001873 TailCalls.push_back(CI);
1874 }
1875 } else {
1876 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001877 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
David Blaikie70573dc2014-11-19 07:49:26 +00001878 if (!VisitedBBs.insert(*PI).second)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001879 continue;
1880
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001881 BasicBlock::InstListType &InstList = (*PI)->getInstList();
Cameron Zwarich4649f172011-03-24 04:52:10 +00001882 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
1883 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001884 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
1885 if (RI == RE)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001886 continue;
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001887
Cameron Zwarich4649f172011-03-24 04:52:10 +00001888 CallInst *CI = dyn_cast<CallInst>(&*RI);
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00001889 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI) &&
1890 attributesPermitTailCall(F, CI, RetI, *TLI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00001891 TailCalls.push_back(CI);
1892 }
Evan Cheng0663f232011-03-21 01:19:09 +00001893 }
1894
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001895 bool Changed = false;
1896 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
1897 CallInst *CI = TailCalls[i];
1898 CallSite CS(CI);
1899
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001900 // Make sure the call instruction is followed by an unconditional branch to
1901 // the return block.
1902 BasicBlock *CallBB = CI->getParent();
1903 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
1904 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
1905 continue;
1906
1907 // Duplicate the return into CallBB.
Michael Kuperstein71321562016-09-07 20:29:49 +00001908 (void)FoldReturnIntoUncondBranch(RetI, BB, CallBB);
Devang Patel8f606d72011-03-24 15:35:25 +00001909 ModifiedDT = Changed = true;
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001910 ++NumRetsDup;
1911 }
1912
1913 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng64a223a2012-09-28 23:58:57 +00001914 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001915 BB->eraseFromParent();
1916
1917 return Changed;
Evan Cheng0663f232011-03-21 01:19:09 +00001918}
1919
Chris Lattner728f9022008-11-25 07:09:13 +00001920//===----------------------------------------------------------------------===//
Chris Lattner728f9022008-11-25 07:09:13 +00001921// Memory Optimization
1922//===----------------------------------------------------------------------===//
1923
Chandler Carruthc8925912013-01-05 02:09:22 +00001924namespace {
1925
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001926/// This is an extended version of TargetLowering::AddrMode
Chandler Carruthc8925912013-01-05 02:09:22 +00001927/// which holds actual Value*'s for register values.
Chandler Carruth95f83e02013-01-07 15:14:13 +00001928struct ExtAddrMode : public TargetLowering::AddrMode {
Eugene Zelenko900b6332017-08-29 22:32:07 +00001929 Value *BaseReg = nullptr;
1930 Value *ScaledReg = nullptr;
John Brawn736bf002017-10-03 13:08:22 +00001931 Value *OriginalValue = nullptr;
1932
1933 enum FieldName {
1934 NoField = 0x00,
1935 BaseRegField = 0x01,
1936 BaseGVField = 0x02,
1937 BaseOffsField = 0x04,
1938 ScaledRegField = 0x08,
1939 ScaleField = 0x10,
1940 MultipleFields = 0xff
1941 };
Eugene Zelenko900b6332017-08-29 22:32:07 +00001942
1943 ExtAddrMode() = default;
1944
Chandler Carruthc8925912013-01-05 02:09:22 +00001945 void print(raw_ostream &OS) const;
1946 void dump() const;
Stephen Lin837bba12013-07-15 17:55:02 +00001947
John Brawn736bf002017-10-03 13:08:22 +00001948 FieldName compare(const ExtAddrMode &other) {
1949 // First check that the types are the same on each field, as differing types
1950 // is something we can't cope with later on.
1951 if (BaseReg && other.BaseReg &&
1952 BaseReg->getType() != other.BaseReg->getType())
1953 return MultipleFields;
1954 if (BaseGV && other.BaseGV &&
1955 BaseGV->getType() != other.BaseGV->getType())
1956 return MultipleFields;
1957 if (ScaledReg && other.ScaledReg &&
1958 ScaledReg->getType() != other.ScaledReg->getType())
1959 return MultipleFields;
1960
1961 // Check each field to see if it differs.
1962 unsigned Result = NoField;
1963 if (BaseReg != other.BaseReg)
1964 Result |= BaseRegField;
1965 if (BaseGV != other.BaseGV)
1966 Result |= BaseGVField;
1967 if (BaseOffs != other.BaseOffs)
1968 Result |= BaseOffsField;
1969 if (ScaledReg != other.ScaledReg)
1970 Result |= ScaledRegField;
1971 // Don't count 0 as being a different scale, because that actually means
1972 // unscaled (which will already be counted by having no ScaledReg).
1973 if (Scale && other.Scale && Scale != other.Scale)
1974 Result |= ScaleField;
1975
1976 if (countPopulation(Result) > 1)
1977 return MultipleFields;
1978 else
1979 return static_cast<FieldName>(Result);
1980 }
1981
John Brawn4b476482017-11-27 11:29:15 +00001982 // An AddrMode is trivial if it involves no calculation i.e. it is just a base
1983 // with no offset.
John Brawn736bf002017-10-03 13:08:22 +00001984 bool isTrivial() {
John Brawn4b476482017-11-27 11:29:15 +00001985 // An AddrMode is (BaseGV + BaseReg + BaseOffs + ScaleReg * Scale) so it is
1986 // trivial if at most one of these terms is nonzero, except that BaseGV and
1987 // BaseReg both being zero actually means a null pointer value, which we
1988 // consider to be 'non-zero' here.
1989 return !BaseOffs && !Scale && !(BaseGV && BaseReg);
Chandler Carruthc8925912013-01-05 02:09:22 +00001990 }
John Brawn70cdb5b2017-11-24 14:10:45 +00001991
1992 Value *GetFieldAsValue(FieldName Field, Type *IntPtrTy) {
1993 switch (Field) {
1994 default:
1995 return nullptr;
1996 case BaseRegField:
1997 return BaseReg;
1998 case BaseGVField:
1999 return BaseGV;
2000 case ScaledRegField:
2001 return ScaledReg;
2002 case BaseOffsField:
2003 return ConstantInt::get(IntPtrTy, BaseOffs);
2004 }
2005 }
2006
2007 void SetCombinedField(FieldName Field, Value *V,
2008 const SmallVectorImpl<ExtAddrMode> &AddrModes) {
2009 switch (Field) {
2010 default:
2011 llvm_unreachable("Unhandled fields are expected to be rejected earlier");
2012 break;
2013 case ExtAddrMode::BaseRegField:
2014 BaseReg = V;
2015 break;
2016 case ExtAddrMode::BaseGVField:
2017 // A combined BaseGV is an Instruction, not a GlobalValue, so it goes
2018 // in the BaseReg field.
2019 assert(BaseReg == nullptr);
2020 BaseReg = V;
2021 BaseGV = nullptr;
2022 break;
2023 case ExtAddrMode::ScaledRegField:
2024 ScaledReg = V;
2025 // If we have a mix of scaled and unscaled addrmodes then we want scale
2026 // to be the scale and not zero.
2027 if (!Scale)
2028 for (const ExtAddrMode &AM : AddrModes)
2029 if (AM.Scale) {
2030 Scale = AM.Scale;
2031 break;
2032 }
2033 break;
2034 case ExtAddrMode::BaseOffsField:
2035 // The offset is no longer a constant, so it goes in ScaledReg with a
2036 // scale of 1.
2037 assert(ScaledReg == nullptr);
2038 ScaledReg = V;
2039 Scale = 1;
2040 BaseOffs = 0;
2041 break;
2042 }
2043 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002044};
2045
Eugene Zelenko900b6332017-08-29 22:32:07 +00002046} // end anonymous namespace
2047
Eli Friedmanc1f1f852013-09-10 23:09:24 +00002048#ifndef NDEBUG
2049static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
2050 AM.print(OS);
2051 return OS;
2052}
2053#endif
2054
Aaron Ballman615eb472017-10-15 14:32:27 +00002055#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruthc8925912013-01-05 02:09:22 +00002056void ExtAddrMode::print(raw_ostream &OS) const {
2057 bool NeedPlus = false;
2058 OS << "[";
2059 if (BaseGV) {
2060 OS << (NeedPlus ? " + " : "")
2061 << "GV:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002062 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002063 NeedPlus = true;
2064 }
2065
Richard Trieuc0f91212014-05-30 03:15:17 +00002066 if (BaseOffs) {
2067 OS << (NeedPlus ? " + " : "")
2068 << BaseOffs;
2069 NeedPlus = true;
2070 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002071
2072 if (BaseReg) {
2073 OS << (NeedPlus ? " + " : "")
2074 << "Base:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002075 BaseReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002076 NeedPlus = true;
2077 }
2078 if (Scale) {
2079 OS << (NeedPlus ? " + " : "")
2080 << Scale << "*";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002081 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002082 }
2083
2084 OS << ']';
2085}
2086
Yaron Kereneb2a2542016-01-29 20:50:44 +00002087LLVM_DUMP_METHOD void ExtAddrMode::dump() const {
Chandler Carruthc8925912013-01-05 02:09:22 +00002088 print(dbgs());
2089 dbgs() << '\n';
2090}
2091#endif
2092
Eugene Zelenko900b6332017-08-29 22:32:07 +00002093namespace {
2094
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002095/// This class provides transaction based operation on the IR.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002096/// Every change made through this class is recorded in the internal state and
2097/// can be undone (rollback) until commit is called.
2098class TypePromotionTransaction {
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002099 /// This represents the common interface of the individual transaction.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002100 /// Each class implements the logic for doing one specific modification on
2101 /// the IR via the TypePromotionTransaction.
2102 class TypePromotionAction {
2103 protected:
2104 /// The Instruction modified.
2105 Instruction *Inst;
2106
2107 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002108 /// Constructor of the action.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002109 /// The constructor performs the related action on the IR.
2110 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
2111
Eugene Zelenko900b6332017-08-29 22:32:07 +00002112 virtual ~TypePromotionAction() = default;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002113
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002114 /// Undo the modification done by this action.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002115 /// When this method is called, the IR must be in the same state as it was
2116 /// before this action was applied.
2117 /// \pre Undoing the action works if and only if the IR is in the exact same
2118 /// state as it was directly after this action was applied.
2119 virtual void undo() = 0;
2120
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002121 /// Advocate every change made by this action.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002122 /// When the results on the IR of the action are to be kept, it is important
2123 /// to call this function, otherwise hidden information may be kept forever.
2124 virtual void commit() {
2125 // Nothing to be done, this action is not doing anything.
2126 }
2127 };
2128
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002129 /// Utility to remember the position of an instruction.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002130 class InsertionHandler {
2131 /// Position of an instruction.
2132 /// Either an instruction:
2133 /// - Is the first in a basic block: BB is used.
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00002134 /// - Has a previous instruction: PrevInst is used.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002135 union {
2136 Instruction *PrevInst;
2137 BasicBlock *BB;
2138 } Point;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002139
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002140 /// Remember whether or not the instruction had a previous instruction.
2141 bool HasPrevInstruction;
2142
2143 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002144 /// Record the position of \p Inst.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002145 InsertionHandler(Instruction *Inst) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002146 BasicBlock::iterator It = Inst->getIterator();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002147 HasPrevInstruction = (It != (Inst->getParent()->begin()));
2148 if (HasPrevInstruction)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002149 Point.PrevInst = &*--It;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002150 else
2151 Point.BB = Inst->getParent();
2152 }
2153
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002154 /// Insert \p Inst at the recorded position.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002155 void insert(Instruction *Inst) {
2156 if (HasPrevInstruction) {
2157 if (Inst->getParent())
2158 Inst->removeFromParent();
2159 Inst->insertAfter(Point.PrevInst);
2160 } else {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002161 Instruction *Position = &*Point.BB->getFirstInsertionPt();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002162 if (Inst->getParent())
2163 Inst->moveBefore(Position);
2164 else
2165 Inst->insertBefore(Position);
2166 }
2167 }
2168 };
2169
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002170 /// Move an instruction before another.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002171 class InstructionMoveBefore : public TypePromotionAction {
2172 /// Original position of the instruction.
2173 InsertionHandler Position;
2174
2175 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002176 /// Move \p Inst before \p Before.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002177 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
2178 : TypePromotionAction(Inst), Position(Inst) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002179 LLVM_DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before
2180 << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002181 Inst->moveBefore(Before);
2182 }
2183
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002184 /// Move the instruction back to its original position.
Craig Topper4584cd52014-03-07 09:26:03 +00002185 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002186 LLVM_DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002187 Position.insert(Inst);
2188 }
2189 };
2190
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002191 /// Set the operand of an instruction with a new value.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002192 class OperandSetter : public TypePromotionAction {
2193 /// Original operand of the instruction.
2194 Value *Origin;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002195
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002196 /// Index of the modified instruction.
2197 unsigned Idx;
2198
2199 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002200 /// Set \p Idx operand of \p Inst with \p NewVal.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002201 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
2202 : TypePromotionAction(Inst), Idx(Idx) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002203 LLVM_DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
2204 << "for:" << *Inst << "\n"
2205 << "with:" << *NewVal << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002206 Origin = Inst->getOperand(Idx);
2207 Inst->setOperand(Idx, NewVal);
2208 }
2209
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002210 /// Restore the original value of the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002211 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002212 LLVM_DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
2213 << "for: " << *Inst << "\n"
2214 << "with: " << *Origin << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002215 Inst->setOperand(Idx, Origin);
2216 }
2217 };
2218
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002219 /// Hide the operands of an instruction.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002220 /// Do as if this instruction was not using any of its operands.
2221 class OperandsHider : public TypePromotionAction {
2222 /// The list of original operands.
2223 SmallVector<Value *, 4> OriginalValues;
2224
2225 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002226 /// Remove \p Inst from the uses of the operands of \p Inst.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002227 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002228 LLVM_DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002229 unsigned NumOpnds = Inst->getNumOperands();
2230 OriginalValues.reserve(NumOpnds);
2231 for (unsigned It = 0; It < NumOpnds; ++It) {
2232 // Save the current operand.
2233 Value *Val = Inst->getOperand(It);
2234 OriginalValues.push_back(Val);
2235 // Set a dummy one.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002236 // We could use OperandSetter here, but that would imply an overhead
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002237 // that we are not willing to pay.
2238 Inst->setOperand(It, UndefValue::get(Val->getType()));
2239 }
2240 }
2241
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002242 /// Restore the original list of uses.
Craig Topper4584cd52014-03-07 09:26:03 +00002243 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002244 LLVM_DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002245 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
2246 Inst->setOperand(It, OriginalValues[It]);
2247 }
2248 };
2249
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002250 /// Build a truncate instruction.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002251 class TruncBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002252 Value *Val;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002253
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002254 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002255 /// Build a truncate instruction of \p Opnd producing a \p Ty
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002256 /// result.
2257 /// trunc Opnd to Ty.
2258 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
2259 IRBuilder<> Builder(Opnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00002260 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002261 LLVM_DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002262 }
2263
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002264 /// Get the built value.
Quentin Colombetac55b152014-09-16 22:36:07 +00002265 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002266
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002267 /// Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002268 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002269 LLVM_DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
Quentin Colombetac55b152014-09-16 22:36:07 +00002270 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2271 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002272 }
2273 };
2274
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002275 /// Build a sign extension instruction.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002276 class SExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002277 Value *Val;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002278
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002279 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002280 /// Build a sign extension instruction of \p Opnd producing a \p Ty
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002281 /// result.
2282 /// sext Opnd to Ty.
2283 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002284 : TypePromotionAction(InsertPt) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002285 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002286 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002287 LLVM_DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002288 }
2289
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002290 /// Get the built value.
Quentin Colombetac55b152014-09-16 22:36:07 +00002291 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002292
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002293 /// Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002294 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002295 LLVM_DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
Quentin Colombetac55b152014-09-16 22:36:07 +00002296 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2297 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002298 }
2299 };
2300
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002301 /// Build a zero extension instruction.
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002302 class ZExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002303 Value *Val;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002304
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002305 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002306 /// Build a zero extension instruction of \p Opnd producing a \p Ty
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002307 /// result.
2308 /// zext Opnd to Ty.
2309 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002310 : TypePromotionAction(InsertPt) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002311 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002312 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002313 LLVM_DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002314 }
2315
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002316 /// Get the built value.
Quentin Colombetac55b152014-09-16 22:36:07 +00002317 Value *getBuiltValue() { return Val; }
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002318
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002319 /// Remove the built instruction.
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002320 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002321 LLVM_DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
Quentin Colombetac55b152014-09-16 22:36:07 +00002322 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2323 IVal->eraseFromParent();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002324 }
2325 };
2326
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002327 /// Mutate an instruction to another type.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002328 class TypeMutator : public TypePromotionAction {
2329 /// Record the original type.
2330 Type *OrigTy;
2331
2332 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002333 /// Mutate the type of \p Inst into \p NewTy.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002334 TypeMutator(Instruction *Inst, Type *NewTy)
2335 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002336 LLVM_DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
2337 << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002338 Inst->mutateType(NewTy);
2339 }
2340
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002341 /// Mutate the instruction back to its original type.
Craig Topper4584cd52014-03-07 09:26:03 +00002342 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002343 LLVM_DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
2344 << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002345 Inst->mutateType(OrigTy);
2346 }
2347 };
2348
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002349 /// Replace the uses of an instruction by another instruction.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002350 class UsesReplacer : public TypePromotionAction {
2351 /// Helper structure to keep track of the replaced uses.
2352 struct InstructionAndIdx {
2353 /// The instruction using the instruction.
2354 Instruction *Inst;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002355
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002356 /// The index where this instruction is used for Inst.
2357 unsigned Idx;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002358
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002359 InstructionAndIdx(Instruction *Inst, unsigned Idx)
2360 : Inst(Inst), Idx(Idx) {}
2361 };
2362
2363 /// Keep track of the original uses (pair Instruction, Index).
2364 SmallVector<InstructionAndIdx, 4> OriginalUses;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002365
2366 using use_iterator = SmallVectorImpl<InstructionAndIdx>::iterator;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002367
2368 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002369 /// Replace all the use of \p Inst by \p New.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002370 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002371 LLVM_DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
2372 << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002373 // Record the original uses.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002374 for (Use &U : Inst->uses()) {
2375 Instruction *UserI = cast<Instruction>(U.getUser());
2376 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002377 }
2378 // Now, we can replace the uses.
2379 Inst->replaceAllUsesWith(New);
2380 }
2381
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002382 /// Reassign the original uses of Inst to Inst.
Craig Topper4584cd52014-03-07 09:26:03 +00002383 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002384 LLVM_DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002385 for (use_iterator UseIt = OriginalUses.begin(),
2386 EndIt = OriginalUses.end();
2387 UseIt != EndIt; ++UseIt) {
2388 UseIt->Inst->setOperand(UseIt->Idx, Inst);
2389 }
2390 }
2391 };
2392
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002393 /// Remove an instruction from the IR.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002394 class InstructionRemover : public TypePromotionAction {
2395 /// Original position of the instruction.
2396 InsertionHandler Inserter;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002397
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002398 /// Helper structure to hide all the link to the instruction. In other
2399 /// words, this helps to do as if the instruction was removed.
2400 OperandsHider Hider;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002401
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002402 /// Keep track of the uses replaced, if any.
Eugene Zelenko900b6332017-08-29 22:32:07 +00002403 UsesReplacer *Replacer = nullptr;
2404
Jun Bum Limdee55652017-04-03 19:20:07 +00002405 /// Keep track of instructions removed.
2406 SetOfInstrs &RemovedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002407
2408 public:
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00002409 /// Remove all reference of \p Inst and optionally replace all its
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002410 /// uses with New.
Jun Bum Limdee55652017-04-03 19:20:07 +00002411 /// \p RemovedInsts Keep track of the instructions removed by this Action.
Craig Topperc0196b12014-04-14 00:51:57 +00002412 /// \pre If !Inst->use_empty(), then New != nullptr
Jun Bum Limdee55652017-04-03 19:20:07 +00002413 InstructionRemover(Instruction *Inst, SetOfInstrs &RemovedInsts,
2414 Value *New = nullptr)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002415 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
Eugene Zelenko900b6332017-08-29 22:32:07 +00002416 RemovedInsts(RemovedInsts) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002417 if (New)
2418 Replacer = new UsesReplacer(Inst, New);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002419 LLVM_DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
Jun Bum Limdee55652017-04-03 19:20:07 +00002420 RemovedInsts.insert(Inst);
2421 /// The instructions removed here will be freed after completing
2422 /// optimizeBlock() for all blocks as we need to keep track of the
2423 /// removed instructions during promotion.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002424 Inst->removeFromParent();
2425 }
2426
Alexander Kornienkof817c1c2015-04-11 02:11:45 +00002427 ~InstructionRemover() override { delete Replacer; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002428
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002429 /// Resurrect the instruction and reassign it to the proper uses if
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002430 /// new value was provided when build this action.
Craig Topper4584cd52014-03-07 09:26:03 +00002431 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002432 LLVM_DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002433 Inserter.insert(Inst);
2434 if (Replacer)
2435 Replacer->undo();
2436 Hider.undo();
Jun Bum Limdee55652017-04-03 19:20:07 +00002437 RemovedInsts.erase(Inst);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002438 }
2439 };
2440
2441public:
2442 /// Restoration point.
2443 /// The restoration point is a pointer to an action instead of an iterator
2444 /// because the iterator may be invalidated but not the pointer.
Eugene Zelenko900b6332017-08-29 22:32:07 +00002445 using ConstRestorationPt = const TypePromotionAction *;
Jun Bum Limdee55652017-04-03 19:20:07 +00002446
2447 TypePromotionTransaction(SetOfInstrs &RemovedInsts)
2448 : RemovedInsts(RemovedInsts) {}
2449
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002450 /// Advocate every changes made in that transaction.
2451 void commit();
Eugene Zelenko900b6332017-08-29 22:32:07 +00002452
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002453 /// Undo all the changes made after the given point.
2454 void rollback(ConstRestorationPt Point);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002455
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002456 /// Get the current restoration point.
2457 ConstRestorationPt getRestorationPoint() const;
2458
2459 /// \name API for IR modification with state keeping to support rollback.
2460 /// @{
2461 /// Same as Instruction::setOperand.
2462 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002463
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002464 /// Same as Instruction::eraseFromParent.
Craig Topperc0196b12014-04-14 00:51:57 +00002465 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002466
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002467 /// Same as Value::replaceAllUsesWith.
2468 void replaceAllUsesWith(Instruction *Inst, Value *New);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002469
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002470 /// Same as Value::mutateType.
2471 void mutateType(Instruction *Inst, Type *NewTy);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002472
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002473 /// Same as IRBuilder::createTrunc.
Quentin Colombetac55b152014-09-16 22:36:07 +00002474 Value *createTrunc(Instruction *Opnd, Type *Ty);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002475
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002476 /// Same as IRBuilder::createSExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002477 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002478
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002479 /// Same as IRBuilder::createZExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002480 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002481
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002482 /// Same as Instruction::moveBefore.
2483 void moveBefore(Instruction *Inst, Instruction *Before);
2484 /// @}
2485
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002486private:
2487 /// The ordered list of actions made so far.
David Blaikie7620b312014-04-15 06:17:44 +00002488 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002489
2490 using CommitPt = SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator;
2491
Jun Bum Limdee55652017-04-03 19:20:07 +00002492 SetOfInstrs &RemovedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002493};
2494
Eugene Zelenko900b6332017-08-29 22:32:07 +00002495} // end anonymous namespace
2496
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002497void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
2498 Value *NewVal) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00002499 Actions.push_back(llvm::make_unique<TypePromotionTransaction::OperandSetter>(
2500 Inst, Idx, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002501}
2502
2503void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
2504 Value *NewVal) {
2505 Actions.push_back(
Eugene Zelenko900b6332017-08-29 22:32:07 +00002506 llvm::make_unique<TypePromotionTransaction::InstructionRemover>(
2507 Inst, RemovedInsts, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002508}
2509
2510void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
2511 Value *New) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00002512 Actions.push_back(
2513 llvm::make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002514}
2515
2516void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00002517 Actions.push_back(
2518 llvm::make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002519}
2520
Quentin Colombetac55b152014-09-16 22:36:07 +00002521Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
2522 Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002523 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002524 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002525 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002526 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002527}
2528
Quentin Colombetac55b152014-09-16 22:36:07 +00002529Value *TypePromotionTransaction::createSExt(Instruction *Inst,
2530 Value *Opnd, Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002531 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002532 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002533 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002534 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002535}
2536
Quentin Colombetac55b152014-09-16 22:36:07 +00002537Value *TypePromotionTransaction::createZExt(Instruction *Inst,
2538 Value *Opnd, Type *Ty) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002539 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002540 Value *Val = Ptr->getBuiltValue();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002541 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002542 return Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002543}
2544
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002545void TypePromotionTransaction::moveBefore(Instruction *Inst,
2546 Instruction *Before) {
2547 Actions.push_back(
Eugene Zelenko900b6332017-08-29 22:32:07 +00002548 llvm::make_unique<TypePromotionTransaction::InstructionMoveBefore>(
2549 Inst, Before));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002550}
2551
2552TypePromotionTransaction::ConstRestorationPt
2553TypePromotionTransaction::getRestorationPoint() const {
David Blaikie7620b312014-04-15 06:17:44 +00002554 return !Actions.empty() ? Actions.back().get() : nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002555}
2556
2557void TypePromotionTransaction::commit() {
2558 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
David Blaikie7620b312014-04-15 06:17:44 +00002559 ++It)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002560 (*It)->commit();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002561 Actions.clear();
2562}
2563
2564void TypePromotionTransaction::rollback(
2565 TypePromotionTransaction::ConstRestorationPt Point) {
David Blaikie7620b312014-04-15 06:17:44 +00002566 while (!Actions.empty() && Point != Actions.back().get()) {
2567 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002568 Curr->undo();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002569 }
2570}
2571
Eugene Zelenko900b6332017-08-29 22:32:07 +00002572namespace {
2573
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002574/// A helper class for matching addressing modes.
Chandler Carruthc8925912013-01-05 02:09:22 +00002575///
2576/// This encapsulates the logic for matching the target-legal addressing modes.
2577class AddressingModeMatcher {
2578 SmallVectorImpl<Instruction*> &AddrModeInsts;
2579 const TargetLowering &TLI;
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002580 const TargetRegisterInfo &TRI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00002581 const DataLayout &DL;
Chandler Carruthc8925912013-01-05 02:09:22 +00002582
2583 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
2584 /// the memory instruction that we're computing this address for.
2585 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002586 unsigned AddrSpace;
Chandler Carruthc8925912013-01-05 02:09:22 +00002587 Instruction *MemoryInst;
Stephen Lin837bba12013-07-15 17:55:02 +00002588
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002589 /// This is the addressing mode that we're building up. This is
Chandler Carruthc8925912013-01-05 02:09:22 +00002590 /// part of the return value of this addressing mode matching stuff.
2591 ExtAddrMode &AddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002592
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002593 /// The instructions inserted by other CodeGenPrepare optimizations.
2594 const SetOfInstrs &InsertedInsts;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002595
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002596 /// A map from the instructions to their type before promotion.
2597 InstrToOrigTy &PromotedInsts;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002598
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002599 /// The ongoing transaction where every action should be registered.
2600 TypePromotionTransaction &TPT;
2601
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00002602 // A GEP which has too large offset to be folded into the addressing mode.
2603 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP;
2604
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002605 /// This is set to true when we should not do profitability checks.
2606 /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
Chandler Carruthc8925912013-01-05 02:09:22 +00002607 bool IgnoreProfitability;
Stephen Lin837bba12013-07-15 17:55:02 +00002608
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00002609 AddressingModeMatcher(
2610 SmallVectorImpl<Instruction *> &AMI, const TargetLowering &TLI,
2611 const TargetRegisterInfo &TRI, Type *AT, unsigned AS, Instruction *MI,
2612 ExtAddrMode &AM, const SetOfInstrs &InsertedInsts,
2613 InstrToOrigTy &PromotedInsts, TypePromotionTransaction &TPT,
2614 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP)
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002615 : AddrModeInsts(AMI), TLI(TLI), TRI(TRI),
Mehdi Amini4fe37982015-07-07 18:45:17 +00002616 DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
2617 MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00002618 PromotedInsts(PromotedInsts), TPT(TPT), LargeOffsetGEP(LargeOffsetGEP) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002619 IgnoreProfitability = false;
2620 }
Stephen Lin837bba12013-07-15 17:55:02 +00002621
Eugene Zelenko900b6332017-08-29 22:32:07 +00002622public:
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002623 /// Find the maximal addressing mode that a load/store of V can fold,
Chandler Carruthc8925912013-01-05 02:09:22 +00002624 /// give an access type of AccessTy. This returns a list of involved
2625 /// instructions in AddrModeInsts.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002626 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002627 /// optimizations.
2628 /// \p PromotedInsts maps the instructions to their type before promotion.
2629 /// \p The ongoing transaction where every action should be registered.
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00002630 static ExtAddrMode
2631 Match(Value *V, Type *AccessTy, unsigned AS, Instruction *MemoryInst,
2632 SmallVectorImpl<Instruction *> &AddrModeInsts,
2633 const TargetLowering &TLI, const TargetRegisterInfo &TRI,
2634 const SetOfInstrs &InsertedInsts, InstrToOrigTy &PromotedInsts,
2635 TypePromotionTransaction &TPT,
2636 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002637 ExtAddrMode Result;
2638
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00002639 bool Success = AddressingModeMatcher(AddrModeInsts, TLI, TRI, AccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002640 MemoryInst, Result, InsertedInsts,
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00002641 PromotedInsts, TPT, LargeOffsetGEP)
2642 .matchAddr(V, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00002643 (void)Success; assert(Success && "Couldn't select *anything*?");
2644 return Result;
2645 }
Eugene Zelenko900b6332017-08-29 22:32:07 +00002646
Chandler Carruthc8925912013-01-05 02:09:22 +00002647private:
Sanjay Patelfc580a62015-09-21 23:03:16 +00002648 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
Fangrui Songcb0bab82018-07-16 18:51:40 +00002649 bool matchAddr(Value *Addr, unsigned Depth);
2650 bool matchOperationAddr(User *AddrInst, unsigned Opcode, unsigned Depth,
Craig Topperc0196b12014-04-14 00:51:57 +00002651 bool *MovedAway = nullptr);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002652 bool isProfitableToFoldIntoAddressingMode(Instruction *I,
Chandler Carruthc8925912013-01-05 02:09:22 +00002653 ExtAddrMode &AMBefore,
2654 ExtAddrMode &AMAfter);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002655 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
2656 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
Quentin Colombet867c5502014-02-14 22:23:22 +00002657 Value *PromotedOperand) const;
Chandler Carruthc8925912013-01-05 02:09:22 +00002658};
2659
Ali Tamurd482b012018-11-12 21:43:43 +00002660class PhiNodeSet;
2661
2662/// An iterator for PhiNodeSet.
2663class PhiNodeSetIterator {
2664 PhiNodeSet * const Set;
2665 size_t CurrentIndex = 0;
2666
2667public:
2668 /// The constructor. Start should point to either a valid element, or be equal
2669 /// to the size of the underlying SmallVector of the PhiNodeSet.
2670 PhiNodeSetIterator(PhiNodeSet * const Set, size_t Start);
2671 PHINode * operator*() const;
2672 PhiNodeSetIterator& operator++();
2673 bool operator==(const PhiNodeSetIterator &RHS) const;
2674 bool operator!=(const PhiNodeSetIterator &RHS) const;
2675};
2676
2677/// Keeps a set of PHINodes.
2678///
2679/// This is a minimal set implementation for a specific use case:
2680/// It is very fast when there are very few elements, but also provides good
2681/// performance when there are many. It is similar to SmallPtrSet, but also
2682/// provides iteration by insertion order, which is deterministic and stable
2683/// across runs. It is also similar to SmallSetVector, but provides removing
2684/// elements in O(1) time. This is achieved by not actually removing the element
2685/// from the underlying vector, so comes at the cost of using more memory, but
2686/// that is fine, since PhiNodeSets are used as short lived objects.
2687class PhiNodeSet {
2688 friend class PhiNodeSetIterator;
2689
2690 using MapType = SmallDenseMap<PHINode *, size_t, 32>;
2691 using iterator = PhiNodeSetIterator;
2692
2693 /// Keeps the elements in the order of their insertion in the underlying
2694 /// vector. To achieve constant time removal, it never deletes any element.
2695 SmallVector<PHINode *, 32> NodeList;
2696
2697 /// Keeps the elements in the underlying set implementation. This (and not the
2698 /// NodeList defined above) is the source of truth on whether an element
2699 /// is actually in the collection.
2700 MapType NodeMap;
2701
2702 /// Points to the first valid (not deleted) element when the set is not empty
2703 /// and the value is not zero. Equals to the size of the underlying vector
2704 /// when the set is empty. When the value is 0, as in the beginning, the
2705 /// first element may or may not be valid.
2706 size_t FirstValidElement = 0;
2707
2708public:
2709 /// Inserts a new element to the collection.
2710 /// \returns true if the element is actually added, i.e. was not in the
2711 /// collection before the operation.
2712 bool insert(PHINode *Ptr) {
2713 if (NodeMap.insert(std::make_pair(Ptr, NodeList.size())).second) {
2714 NodeList.push_back(Ptr);
2715 return true;
2716 }
2717 return false;
2718 }
2719
2720 /// Removes the element from the collection.
2721 /// \returns whether the element is actually removed, i.e. was in the
2722 /// collection before the operation.
2723 bool erase(PHINode *Ptr) {
2724 auto it = NodeMap.find(Ptr);
2725 if (it != NodeMap.end()) {
2726 NodeMap.erase(Ptr);
2727 SkipRemovedElements(FirstValidElement);
2728 return true;
2729 }
2730 return false;
2731 }
2732
2733 /// Removes all elements and clears the collection.
2734 void clear() {
2735 NodeMap.clear();
2736 NodeList.clear();
2737 FirstValidElement = 0;
2738 }
2739
2740 /// \returns an iterator that will iterate the elements in the order of
2741 /// insertion.
2742 iterator begin() {
2743 if (FirstValidElement == 0)
2744 SkipRemovedElements(FirstValidElement);
2745 return PhiNodeSetIterator(this, FirstValidElement);
2746 }
2747
2748 /// \returns an iterator that points to the end of the collection.
2749 iterator end() { return PhiNodeSetIterator(this, NodeList.size()); }
2750
2751 /// Returns the number of elements in the collection.
2752 size_t size() const {
2753 return NodeMap.size();
2754 }
2755
2756 /// \returns 1 if the given element is in the collection, and 0 if otherwise.
2757 size_t count(PHINode *Ptr) const {
2758 return NodeMap.count(Ptr);
2759 }
2760
2761private:
2762 /// Updates the CurrentIndex so that it will point to a valid element.
2763 ///
2764 /// If the element of NodeList at CurrentIndex is valid, it does not
2765 /// change it. If there are no more valid elements, it updates CurrentIndex
2766 /// to point to the end of the NodeList.
2767 void SkipRemovedElements(size_t &CurrentIndex) {
2768 while (CurrentIndex < NodeList.size()) {
2769 auto it = NodeMap.find(NodeList[CurrentIndex]);
2770 // If the element has been deleted and added again later, NodeMap will
2771 // point to a different index, so CurrentIndex will still be invalid.
2772 if (it != NodeMap.end() && it->second == CurrentIndex)
2773 break;
2774 ++CurrentIndex;
2775 }
2776 }
2777};
2778
2779PhiNodeSetIterator::PhiNodeSetIterator(PhiNodeSet *const Set, size_t Start)
2780 : Set(Set), CurrentIndex(Start) {}
2781
2782PHINode * PhiNodeSetIterator::operator*() const {
2783 assert(CurrentIndex < Set->NodeList.size() &&
2784 "PhiNodeSet access out of range");
2785 return Set->NodeList[CurrentIndex];
2786}
2787
2788PhiNodeSetIterator& PhiNodeSetIterator::operator++() {
2789 assert(CurrentIndex < Set->NodeList.size() &&
2790 "PhiNodeSet access out of range");
2791 ++CurrentIndex;
2792 Set->SkipRemovedElements(CurrentIndex);
2793 return *this;
2794}
2795
2796bool PhiNodeSetIterator::operator==(const PhiNodeSetIterator &RHS) const {
2797 return CurrentIndex == RHS.CurrentIndex;
2798}
2799
2800bool PhiNodeSetIterator::operator!=(const PhiNodeSetIterator &RHS) const {
Serge Guelton12c7a962018-11-19 10:05:28 +00002801 return !((*this) == RHS);
Ali Tamurd482b012018-11-12 21:43:43 +00002802}
2803
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002804/// Keep track of simplification of Phi nodes.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002805/// Accept the set of all phi nodes and erase phi node from this set
2806/// if it is simplified.
2807class SimplificationTracker {
2808 DenseMap<Value *, Value *> Storage;
2809 const SimplifyQuery &SQ;
Ali Tamurd482b012018-11-12 21:43:43 +00002810 // Tracks newly created Phi nodes. The elements are iterated by insertion
2811 // order.
2812 PhiNodeSet AllPhiNodes;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002813 // Tracks newly created Select nodes.
2814 SmallPtrSet<SelectInst *, 32> AllSelectNodes;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002815
2816public:
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002817 SimplificationTracker(const SimplifyQuery &sq)
2818 : SQ(sq) {}
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002819
2820 Value *Get(Value *V) {
2821 do {
2822 auto SV = Storage.find(V);
2823 if (SV == Storage.end())
2824 return V;
2825 V = SV->second;
2826 } while (true);
2827 }
2828
2829 Value *Simplify(Value *Val) {
2830 SmallVector<Value *, 32> WorkList;
2831 SmallPtrSet<Value *, 32> Visited;
2832 WorkList.push_back(Val);
2833 while (!WorkList.empty()) {
2834 auto P = WorkList.pop_back_val();
2835 if (!Visited.insert(P).second)
2836 continue;
2837 if (auto *PI = dyn_cast<Instruction>(P))
2838 if (Value *V = SimplifyInstruction(cast<Instruction>(PI), SQ)) {
2839 for (auto *U : PI->users())
2840 WorkList.push_back(cast<Value>(U));
2841 Put(PI, V);
2842 PI->replaceAllUsesWith(V);
2843 if (auto *PHI = dyn_cast<PHINode>(PI))
Ali Tamurd482b012018-11-12 21:43:43 +00002844 AllPhiNodes.erase(PHI);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002845 if (auto *Select = dyn_cast<SelectInst>(PI))
2846 AllSelectNodes.erase(Select);
2847 PI->eraseFromParent();
2848 }
2849 }
2850 return Get(Val);
2851 }
2852
2853 void Put(Value *From, Value *To) {
2854 Storage.insert({ From, To });
2855 }
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002856
2857 void ReplacePhi(PHINode *From, PHINode *To) {
2858 Value* OldReplacement = Get(From);
2859 while (OldReplacement != From) {
2860 From = To;
2861 To = dyn_cast<PHINode>(OldReplacement);
2862 OldReplacement = Get(From);
2863 }
2864 assert(Get(To) == To && "Replacement PHI node is already replaced.");
2865 Put(From, To);
2866 From->replaceAllUsesWith(To);
Ali Tamurd482b012018-11-12 21:43:43 +00002867 AllPhiNodes.erase(From);
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002868 From->eraseFromParent();
2869 }
2870
Ali Tamurd482b012018-11-12 21:43:43 +00002871 PhiNodeSet& newPhiNodes() { return AllPhiNodes; }
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002872
2873 void insertNewPhi(PHINode *PN) { AllPhiNodes.insert(PN); }
2874
2875 void insertNewSelect(SelectInst *SI) { AllSelectNodes.insert(SI); }
2876
2877 unsigned countNewPhiNodes() const { return AllPhiNodes.size(); }
2878
2879 unsigned countNewSelectNodes() const { return AllSelectNodes.size(); }
2880
2881 void destroyNewNodes(Type *CommonType) {
2882 // For safe erasing, replace the uses with dummy value first.
2883 auto Dummy = UndefValue::get(CommonType);
2884 for (auto I : AllPhiNodes) {
2885 I->replaceAllUsesWith(Dummy);
2886 I->eraseFromParent();
2887 }
2888 AllPhiNodes.clear();
2889 for (auto I : AllSelectNodes) {
2890 I->replaceAllUsesWith(Dummy);
2891 I->eraseFromParent();
2892 }
2893 AllSelectNodes.clear();
2894 }
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002895};
2896
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002897/// A helper class for combining addressing modes.
John Brawn736bf002017-10-03 13:08:22 +00002898class AddressingModeCombiner {
Serguei Katkov2673f172018-11-29 06:45:18 +00002899 typedef DenseMap<Value *, Value *> FoldAddrToValueMapping;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002900 typedef std::pair<PHINode *, PHINode *> PHIPair;
2901
John Brawn736bf002017-10-03 13:08:22 +00002902private:
2903 /// The addressing modes we've collected.
2904 SmallVector<ExtAddrMode, 16> AddrModes;
2905
2906 /// The field in which the AddrModes differ, when we have more than one.
2907 ExtAddrMode::FieldName DifferentField = ExtAddrMode::NoField;
2908
2909 /// Are the AddrModes that we have all just equal to their original values?
2910 bool AllAddrModesTrivial = true;
2911
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002912 /// Common Type for all different fields in addressing modes.
2913 Type *CommonType;
2914
2915 /// SimplifyQuery for simplifyInstruction utility.
2916 const SimplifyQuery &SQ;
2917
2918 /// Original Address.
Serguei Katkov2673f172018-11-29 06:45:18 +00002919 Value *Original;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002920
John Brawn736bf002017-10-03 13:08:22 +00002921public:
Serguei Katkov2673f172018-11-29 06:45:18 +00002922 AddressingModeCombiner(const SimplifyQuery &_SQ, Value *OriginalValue)
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002923 : CommonType(nullptr), SQ(_SQ), Original(OriginalValue) {}
2924
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002925 /// Get the combined AddrMode
John Brawn736bf002017-10-03 13:08:22 +00002926 const ExtAddrMode &getAddrMode() const {
2927 return AddrModes[0];
2928 }
2929
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002930 /// Add a new AddrMode if it's compatible with the AddrModes we already
John Brawn736bf002017-10-03 13:08:22 +00002931 /// have.
2932 /// \return True iff we succeeded in doing so.
2933 bool addNewAddrMode(ExtAddrMode &NewAddrMode) {
2934 // Take note of if we have any non-trivial AddrModes, as we need to detect
2935 // when all AddrModes are trivial as then we would introduce a phi or select
2936 // which just duplicates what's already there.
2937 AllAddrModesTrivial = AllAddrModesTrivial && NewAddrMode.isTrivial();
2938
2939 // If this is the first addrmode then everything is fine.
2940 if (AddrModes.empty()) {
2941 AddrModes.emplace_back(NewAddrMode);
2942 return true;
2943 }
2944
2945 // Figure out how different this is from the other address modes, which we
2946 // can do just by comparing against the first one given that we only care
2947 // about the cumulative difference.
2948 ExtAddrMode::FieldName ThisDifferentField =
2949 AddrModes[0].compare(NewAddrMode);
2950 if (DifferentField == ExtAddrMode::NoField)
2951 DifferentField = ThisDifferentField;
2952 else if (DifferentField != ThisDifferentField)
2953 DifferentField = ExtAddrMode::MultipleFields;
2954
Serguei Katkov17e57942018-01-23 12:07:49 +00002955 // If NewAddrMode differs in more than one dimension we cannot handle it.
2956 bool CanHandle = DifferentField != ExtAddrMode::MultipleFields;
2957
2958 // If Scale Field is different then we reject.
2959 CanHandle = CanHandle && DifferentField != ExtAddrMode::ScaleField;
2960
Serguei Katkov4d1dd6b2018-01-09 04:37:06 +00002961 // We also must reject the case when base offset is different and
2962 // scale reg is not null, we cannot handle this case due to merge of
2963 // different offsets will be used as ScaleReg.
Serguei Katkov17e57942018-01-23 12:07:49 +00002964 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseOffsField ||
2965 !NewAddrMode.ScaledReg);
John Brawn736bf002017-10-03 13:08:22 +00002966
Serguei Katkov17e57942018-01-23 12:07:49 +00002967 // We also must reject the case when GV is different and BaseReg installed
2968 // due to we want to use base reg as a merge of GV values.
2969 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseGVField ||
2970 !NewAddrMode.HasBaseReg);
2971
2972 // Even if NewAddMode is the same we still need to collect it due to
2973 // original value is different. And later we will need all original values
2974 // as anchors during finding the common Phi node.
2975 if (CanHandle)
2976 AddrModes.emplace_back(NewAddrMode);
2977 else
2978 AddrModes.clear();
2979
2980 return CanHandle;
John Brawn736bf002017-10-03 13:08:22 +00002981 }
2982
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002983 /// Combine the addressing modes we've collected into a single
John Brawn736bf002017-10-03 13:08:22 +00002984 /// addressing mode.
2985 /// \return True iff we successfully combined them or we only had one so
2986 /// didn't need to combine them anyway.
2987 bool combineAddrModes() {
2988 // If we have no AddrModes then they can't be combined.
2989 if (AddrModes.size() == 0)
2990 return false;
2991
2992 // A single AddrMode can trivially be combined.
Serguei Katkov505359f2017-11-20 05:42:36 +00002993 if (AddrModes.size() == 1 || DifferentField == ExtAddrMode::NoField)
John Brawn736bf002017-10-03 13:08:22 +00002994 return true;
2995
2996 // If the AddrModes we collected are all just equal to the value they are
2997 // derived from then combining them wouldn't do anything useful.
2998 if (AllAddrModesTrivial)
2999 return false;
3000
John Brawn70cdb5b2017-11-24 14:10:45 +00003001 if (!addrModeCombiningAllowed())
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003002 return false;
3003
3004 // Build a map between <original value, basic block where we saw it> to
3005 // value of base register.
Serguei Katkov50364592017-11-29 05:51:26 +00003006 // Bail out if there is no common type.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003007 FoldAddrToValueMapping Map;
Serguei Katkov50364592017-11-29 05:51:26 +00003008 if (!initializeMap(Map))
3009 return false;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003010
3011 Value *CommonValue = findCommon(Map);
3012 if (CommonValue)
John Brawn70cdb5b2017-11-24 14:10:45 +00003013 AddrModes[0].SetCombinedField(DifferentField, CommonValue, AddrModes);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003014 return CommonValue != nullptr;
3015 }
3016
3017private:
Serguei Katkov2673f172018-11-29 06:45:18 +00003018 /// Initialize Map with anchor values. For address seen
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003019 /// we set the value of different field saw in this address.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003020 /// At the same time we find a common type for different field we will
3021 /// use to create new Phi/Select nodes. Keep it in CommonType field.
Serguei Katkov50364592017-11-29 05:51:26 +00003022 /// Return false if there is no common type found.
3023 bool initializeMap(FoldAddrToValueMapping &Map) {
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003024 // Keep track of keys where the value is null. We will need to replace it
3025 // with constant null when we know the common type.
Serguei Katkov2673f172018-11-29 06:45:18 +00003026 SmallVector<Value *, 2> NullValue;
John Brawn70cdb5b2017-11-24 14:10:45 +00003027 Type *IntPtrTy = SQ.DL.getIntPtrType(AddrModes[0].OriginalValue->getType());
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003028 for (auto &AM : AddrModes) {
John Brawn70cdb5b2017-11-24 14:10:45 +00003029 Value *DV = AM.GetFieldAsValue(DifferentField, IntPtrTy);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003030 if (DV) {
Serguei Katkov50364592017-11-29 05:51:26 +00003031 auto *Type = DV->getType();
3032 if (CommonType && CommonType != Type)
3033 return false;
3034 CommonType = Type;
Serguei Katkov2673f172018-11-29 06:45:18 +00003035 Map[AM.OriginalValue] = DV;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003036 } else {
Serguei Katkov2673f172018-11-29 06:45:18 +00003037 NullValue.push_back(AM.OriginalValue);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003038 }
3039 }
3040 assert(CommonType && "At least one non-null value must be!");
Serguei Katkov2673f172018-11-29 06:45:18 +00003041 for (auto *V : NullValue)
3042 Map[V] = Constant::getNullValue(CommonType);
Serguei Katkov50364592017-11-29 05:51:26 +00003043 return true;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003044 }
3045
Serguei Katkov2673f172018-11-29 06:45:18 +00003046 /// We have mapping between value A and other value B where B was a field in
3047 /// addressing mode represented by A. Also we have an original value C
3048 /// representing an address we start with. Traversing from C through phi and
3049 /// selects we ended up with A's in a map. This utility function tries to find
3050 /// a value V which is a field in addressing mode C and traversing through phi
3051 /// nodes and selects we will end up in corresponded values B in a map.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003052 /// The utility will create a new Phi/Selects if needed.
3053 // The simple example looks as follows:
3054 // BB1:
3055 // p1 = b1 + 40
3056 // br cond BB2, BB3
3057 // BB2:
3058 // p2 = b2 + 40
3059 // br BB3
3060 // BB3:
3061 // p = phi [p1, BB1], [p2, BB2]
3062 // v = load p
3063 // Map is
Serguei Katkov2673f172018-11-29 06:45:18 +00003064 // p1 -> b1
3065 // p2 -> b2
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003066 // Request is
Serguei Katkov2673f172018-11-29 06:45:18 +00003067 // p -> ?
3068 // The function tries to find or build phi [b1, BB1], [b2, BB2] in BB3.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003069 Value *findCommon(FoldAddrToValueMapping &Map) {
Eric Christopherd72f78e2018-01-09 23:25:38 +00003070 // Tracks the simplification of newly created phi nodes. The reason we use
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003071 // this mapping is because we will add new created Phi nodes in AddrToBase.
3072 // Simplification of Phi nodes is recursive, so some Phi node may
Serguei Katkov2673f172018-11-29 06:45:18 +00003073 // be simplified after we added it to AddrToBase. In reality this
3074 // simplification is possible only if original phi/selects were not
3075 // simplified yet.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003076 // Using this mapping we can find the current value in AddrToBase.
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003077 SimplificationTracker ST(SQ);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003078
3079 // First step, DFS to create PHI nodes for all intermediate blocks.
3080 // Also fill traverse order for the second step.
Serguei Katkov2673f172018-11-29 06:45:18 +00003081 SmallVector<Value *, 32> TraverseOrder;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003082 InsertPlaceholders(Map, TraverseOrder, ST);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003083
3084 // Second Step, fill new nodes by merged values and simplify if possible.
3085 FillPlaceholders(Map, TraverseOrder, ST);
3086
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003087 if (!AddrSinkNewSelects && ST.countNewSelectNodes() > 0) {
3088 ST.destroyNewNodes(CommonType);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003089 return nullptr;
3090 }
3091
3092 // Now we'd like to match New Phi nodes to existed ones.
3093 unsigned PhiNotMatchedCount = 0;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003094 if (!MatchPhiSet(ST, AddrSinkNewPhis, PhiNotMatchedCount)) {
3095 ST.destroyNewNodes(CommonType);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003096 return nullptr;
3097 }
3098
3099 auto *Result = ST.Get(Map.find(Original)->second);
3100 if (Result) {
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003101 NumMemoryInstsPhiCreated += ST.countNewPhiNodes() + PhiNotMatchedCount;
3102 NumMemoryInstsSelectCreated += ST.countNewSelectNodes();
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003103 }
3104 return Result;
3105 }
3106
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003107 /// Try to match PHI node to Candidate.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003108 /// Matcher tracks the matched Phi nodes.
3109 bool MatchPhiNode(PHINode *PHI, PHINode *Candidate,
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003110 SmallSetVector<PHIPair, 8> &Matcher,
Ali Tamurd482b012018-11-12 21:43:43 +00003111 PhiNodeSet &PhiNodesToMatch) {
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003112 SmallVector<PHIPair, 8> WorkList;
3113 Matcher.insert({ PHI, Candidate });
3114 WorkList.push_back({ PHI, Candidate });
3115 SmallSet<PHIPair, 8> Visited;
3116 while (!WorkList.empty()) {
3117 auto Item = WorkList.pop_back_val();
3118 if (!Visited.insert(Item).second)
3119 continue;
3120 // We iterate over all incoming values to Phi to compare them.
3121 // If values are different and both of them Phi and the first one is a
3122 // Phi we added (subject to match) and both of them is in the same basic
3123 // block then we can match our pair if values match. So we state that
3124 // these values match and add it to work list to verify that.
3125 for (auto B : Item.first->blocks()) {
3126 Value *FirstValue = Item.first->getIncomingValueForBlock(B);
3127 Value *SecondValue = Item.second->getIncomingValueForBlock(B);
3128 if (FirstValue == SecondValue)
3129 continue;
3130
3131 PHINode *FirstPhi = dyn_cast<PHINode>(FirstValue);
3132 PHINode *SecondPhi = dyn_cast<PHINode>(SecondValue);
3133
3134 // One of them is not Phi or
3135 // The first one is not Phi node from the set we'd like to match or
3136 // Phi nodes from different basic blocks then
3137 // we will not be able to match.
3138 if (!FirstPhi || !SecondPhi || !PhiNodesToMatch.count(FirstPhi) ||
3139 FirstPhi->getParent() != SecondPhi->getParent())
3140 return false;
3141
3142 // If we already matched them then continue.
3143 if (Matcher.count({ FirstPhi, SecondPhi }))
3144 continue;
3145 // So the values are different and does not match. So we need them to
3146 // match.
3147 Matcher.insert({ FirstPhi, SecondPhi });
3148 // But me must check it.
3149 WorkList.push_back({ FirstPhi, SecondPhi });
3150 }
3151 }
3152 return true;
3153 }
3154
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003155 /// For the given set of PHI nodes (in the SimplificationTracker) try
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003156 /// to find their equivalents.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003157 /// Returns false if this matching fails and creation of new Phi is disabled.
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003158 bool MatchPhiSet(SimplificationTracker &ST, bool AllowNewPhiNodes,
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003159 unsigned &PhiNotMatchedCount) {
Ali Tamurd482b012018-11-12 21:43:43 +00003160 // Matched and PhiNodesToMatch iterate their elements in a deterministic
3161 // order, so the replacements (ReplacePhi) are also done in a deterministic
3162 // order.
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003163 SmallSetVector<PHIPair, 8> Matched;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003164 SmallPtrSet<PHINode *, 8> WillNotMatch;
Ali Tamurd482b012018-11-12 21:43:43 +00003165 PhiNodeSet &PhiNodesToMatch = ST.newPhiNodes();
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003166 while (PhiNodesToMatch.size()) {
3167 PHINode *PHI = *PhiNodesToMatch.begin();
3168
3169 // Add us, if no Phi nodes in the basic block we do not match.
3170 WillNotMatch.clear();
3171 WillNotMatch.insert(PHI);
3172
3173 // Traverse all Phis until we found equivalent or fail to do that.
3174 bool IsMatched = false;
3175 for (auto &P : PHI->getParent()->phis()) {
3176 if (&P == PHI)
3177 continue;
3178 if ((IsMatched = MatchPhiNode(PHI, &P, Matched, PhiNodesToMatch)))
3179 break;
3180 // If it does not match, collect all Phi nodes from matcher.
3181 // if we end up with no match, them all these Phi nodes will not match
3182 // later.
3183 for (auto M : Matched)
3184 WillNotMatch.insert(M.first);
3185 Matched.clear();
3186 }
3187 if (IsMatched) {
Serguei Katkova20e05b2018-03-12 03:50:07 +00003188 // Replace all matched values and erase them.
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003189 for (auto MV : Matched)
3190 ST.ReplacePhi(MV.first, MV.second);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003191 Matched.clear();
3192 continue;
3193 }
3194 // If we are not allowed to create new nodes then bail out.
3195 if (!AllowNewPhiNodes)
3196 return false;
3197 // Just remove all seen values in matcher. They will not match anything.
3198 PhiNotMatchedCount += WillNotMatch.size();
3199 for (auto *P : WillNotMatch)
Ali Tamurd482b012018-11-12 21:43:43 +00003200 PhiNodesToMatch.erase(P);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003201 }
3202 return true;
3203 }
Serguei Katkov2673f172018-11-29 06:45:18 +00003204 /// Fill the placeholders with values from predecessors and simplify them.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003205 void FillPlaceholders(FoldAddrToValueMapping &Map,
Serguei Katkov2673f172018-11-29 06:45:18 +00003206 SmallVectorImpl<Value *> &TraverseOrder,
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003207 SimplificationTracker &ST) {
3208 while (!TraverseOrder.empty()) {
Serguei Katkov2673f172018-11-29 06:45:18 +00003209 Value *Current = TraverseOrder.pop_back_val();
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003210 assert(Map.find(Current) != Map.end() && "No node to fill!!!");
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003211 Value *V = Map[Current];
3212
3213 if (SelectInst *Select = dyn_cast<SelectInst>(V)) {
3214 // CurrentValue also must be Select.
Serguei Katkov2673f172018-11-29 06:45:18 +00003215 auto *CurrentSelect = cast<SelectInst>(Current);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003216 auto *TrueValue = CurrentSelect->getTrueValue();
Serguei Katkov2673f172018-11-29 06:45:18 +00003217 assert(Map.find(TrueValue) != Map.end() && "No True Value!");
3218 Select->setTrueValue(ST.Get(Map[TrueValue]));
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003219 auto *FalseValue = CurrentSelect->getFalseValue();
Serguei Katkov2673f172018-11-29 06:45:18 +00003220 assert(Map.find(FalseValue) != Map.end() && "No False Value!");
3221 Select->setFalseValue(ST.Get(Map[FalseValue]));
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003222 } else {
3223 // Must be a Phi node then.
3224 PHINode *PHI = cast<PHINode>(V);
Serguei Katkov2673f172018-11-29 06:45:18 +00003225 auto *CurrentPhi = dyn_cast<PHINode>(Current);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003226 // Fill the Phi node with values from predecessors.
Serguei Katkov2673f172018-11-29 06:45:18 +00003227 for (auto B : predecessors(PHI->getParent())) {
3228 Value *PV = CurrentPhi->getIncomingValueForBlock(B);
3229 assert(Map.find(PV) != Map.end() && "No predecessor Value!");
3230 PHI->addIncoming(ST.Get(Map[PV]), B);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003231 }
3232 }
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003233 Map[Current] = ST.Simplify(V);
3234 }
3235 }
3236
Serguei Katkov2673f172018-11-29 06:45:18 +00003237 /// Starting from original value recursively iterates over def-use chain up to
3238 /// known ending values represented in a map. For each traversed phi/select
3239 /// inserts a placeholder Phi or Select.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003240 /// Reports all new created Phi/Select nodes by adding them to set.
Serguei Katkov2673f172018-11-29 06:45:18 +00003241 /// Also reports and order in what values have been traversed.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003242 void InsertPlaceholders(FoldAddrToValueMapping &Map,
Serguei Katkov2673f172018-11-29 06:45:18 +00003243 SmallVectorImpl<Value *> &TraverseOrder,
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003244 SimplificationTracker &ST) {
Serguei Katkov2673f172018-11-29 06:45:18 +00003245 SmallVector<Value *, 32> Worklist;
3246 assert((isa<PHINode>(Original) || isa<SelectInst>(Original)) &&
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003247 "Address must be a Phi or Select node");
3248 auto *Dummy = UndefValue::get(CommonType);
3249 Worklist.push_back(Original);
3250 while (!Worklist.empty()) {
Serguei Katkov2673f172018-11-29 06:45:18 +00003251 Value *Current = Worklist.pop_back_val();
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003252 // if it is already visited or it is an ending value then skip it.
3253 if (Map.find(Current) != Map.end())
3254 continue;
3255 TraverseOrder.push_back(Current);
3256
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003257 // CurrentValue must be a Phi node or select. All others must be covered
3258 // by anchors.
Serguei Katkov2673f172018-11-29 06:45:18 +00003259 if (SelectInst *CurrentSelect = dyn_cast<SelectInst>(Current)) {
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003260 // Is it OK to get metadata from OrigSelect?!
3261 // Create a Select placeholder with dummy value.
Serguei Katkov2673f172018-11-29 06:45:18 +00003262 SelectInst *Select = SelectInst::Create(
3263 CurrentSelect->getCondition(), Dummy, Dummy,
3264 CurrentSelect->getName(), CurrentSelect, CurrentSelect);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003265 Map[Current] = Select;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003266 ST.insertNewSelect(Select);
Serguei Katkov2673f172018-11-29 06:45:18 +00003267 // We are interested in True and False values.
3268 Worklist.push_back(CurrentSelect->getTrueValue());
3269 Worklist.push_back(CurrentSelect->getFalseValue());
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003270 } else {
3271 // It must be a Phi node then.
Serguei Katkov2673f172018-11-29 06:45:18 +00003272 PHINode *CurrentPhi = cast<PHINode>(Current);
3273 unsigned PredCount = CurrentPhi->getNumIncomingValues();
3274 PHINode *PHI =
3275 PHINode::Create(CommonType, PredCount, "sunk_phi", CurrentPhi);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003276 Map[Current] = PHI;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003277 ST.insertNewPhi(PHI);
Serguei Katkov2673f172018-11-29 06:45:18 +00003278 for (Value *P : CurrentPhi->incoming_values())
3279 Worklist.push_back(P);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003280 }
3281 }
John Brawn736bf002017-10-03 13:08:22 +00003282 }
John Brawn70cdb5b2017-11-24 14:10:45 +00003283
3284 bool addrModeCombiningAllowed() {
3285 if (DisableComplexAddrModes)
3286 return false;
3287 switch (DifferentField) {
3288 default:
3289 return false;
3290 case ExtAddrMode::BaseRegField:
3291 return AddrSinkCombineBaseReg;
3292 case ExtAddrMode::BaseGVField:
3293 return AddrSinkCombineBaseGV;
3294 case ExtAddrMode::BaseOffsField:
3295 return AddrSinkCombineBaseOffs;
3296 case ExtAddrMode::ScaledRegField:
3297 return AddrSinkCombineScaledReg;
3298 }
3299 }
John Brawn736bf002017-10-03 13:08:22 +00003300};
Eugene Zelenko900b6332017-08-29 22:32:07 +00003301} // end anonymous namespace
3302
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003303/// Try adding ScaleReg*Scale to the current addressing mode.
Chandler Carruthc8925912013-01-05 02:09:22 +00003304/// Return true and update AddrMode if this addr mode is legal for the target,
3305/// false if not.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003306bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
Chandler Carruthc8925912013-01-05 02:09:22 +00003307 unsigned Depth) {
3308 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
3309 // mode. Just process that directly.
3310 if (Scale == 1)
Sanjay Patelfc580a62015-09-21 23:03:16 +00003311 return matchAddr(ScaleReg, Depth);
Stephen Lin837bba12013-07-15 17:55:02 +00003312
Chandler Carruthc8925912013-01-05 02:09:22 +00003313 // If the scale is 0, it takes nothing to add this.
3314 if (Scale == 0)
3315 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003316
Chandler Carruthc8925912013-01-05 02:09:22 +00003317 // If we already have a scale of this value, we can add to it, otherwise, we
3318 // need an available scale field.
3319 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
3320 return false;
3321
3322 ExtAddrMode TestAddrMode = AddrMode;
3323
3324 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
3325 // [A+B + A*7] -> [B+A*8].
3326 TestAddrMode.Scale += Scale;
3327 TestAddrMode.ScaledReg = ScaleReg;
3328
3329 // If the new address isn't legal, bail out.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003330 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003331 return false;
3332
3333 // It was legal, so commit it.
3334 AddrMode = TestAddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00003335
Chandler Carruthc8925912013-01-05 02:09:22 +00003336 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
3337 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
3338 // X*Scale + C*Scale to addr mode.
Craig Topperc0196b12014-04-14 00:51:57 +00003339 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003340 if (isa<Instruction>(ScaleReg) && // not a constant expr.
3341 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
3342 TestAddrMode.ScaledReg = AddLHS;
3343 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00003344
Chandler Carruthc8925912013-01-05 02:09:22 +00003345 // If this addressing mode is legal, commit it and remember that we folded
3346 // this instruction.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003347 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003348 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
3349 AddrMode = TestAddrMode;
3350 return true;
3351 }
3352 }
3353
3354 // Otherwise, not (x+c)*scale, just return what we have.
3355 return true;
3356}
3357
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003358/// This is a little filter, which returns true if an addressing computation
3359/// involving I might be folded into a load/store accessing it.
3360/// This doesn't need to be perfect, but needs to accept at least
Chandler Carruthc8925912013-01-05 02:09:22 +00003361/// the set of instructions that MatchOperationAddr can.
3362static bool MightBeFoldableInst(Instruction *I) {
3363 switch (I->getOpcode()) {
3364 case Instruction::BitCast:
Eli Benderskyf13a0562014-05-22 00:02:52 +00003365 case Instruction::AddrSpaceCast:
Chandler Carruthc8925912013-01-05 02:09:22 +00003366 // Don't touch identity bitcasts.
3367 if (I->getType() == I->getOperand(0)->getType())
3368 return false;
Vedant Kumarb3091da2018-07-06 20:17:42 +00003369 return I->getType()->isIntOrPtrTy();
Chandler Carruthc8925912013-01-05 02:09:22 +00003370 case Instruction::PtrToInt:
3371 // PtrToInt is always a noop, as we know that the int type is pointer sized.
3372 return true;
3373 case Instruction::IntToPtr:
3374 // We know the input is intptr_t, so this is foldable.
3375 return true;
3376 case Instruction::Add:
3377 return true;
3378 case Instruction::Mul:
3379 case Instruction::Shl:
3380 // Can only handle X*C and X << C.
3381 return isa<ConstantInt>(I->getOperand(1));
3382 case Instruction::GetElementPtr:
3383 return true;
3384 default:
3385 return false;
3386 }
3387}
3388
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003389/// Check whether or not \p Val is a legal instruction for \p TLI.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003390/// \note \p Val is assumed to be the product of some type promotion.
3391/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
3392/// to be legal, as the non-promoted value would have had the same state.
Mehdi Amini44ede332015-07-09 02:09:04 +00003393static bool isPromotedInstructionLegal(const TargetLowering &TLI,
3394 const DataLayout &DL, Value *Val) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003395 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
3396 if (!PromotedInst)
3397 return false;
3398 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
3399 // If the ISDOpcode is undefined, it was undefined before the promotion.
3400 if (!ISDOpcode)
3401 return true;
3402 // Otherwise, check if the promoted instruction is legal or not.
3403 return TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00003404 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003405}
3406
Eugene Zelenko900b6332017-08-29 22:32:07 +00003407namespace {
3408
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003409/// Hepler class to perform type promotion.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003410class TypePromotionHelper {
Guozhi Wei8c17f9a2018-08-15 22:08:26 +00003411 /// Utility function to add a promoted instruction \p ExtOpnd to
3412 /// \p PromotedInsts and record the type of extension we have seen.
3413 static void addPromotedInst(InstrToOrigTy &PromotedInsts,
3414 Instruction *ExtOpnd,
3415 bool IsSExt) {
3416 ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension;
3417 InstrToOrigTy::iterator It = PromotedInsts.find(ExtOpnd);
3418 if (It != PromotedInsts.end()) {
3419 // If the new extension is same as original, the information in
3420 // PromotedInsts[ExtOpnd] is still correct.
3421 if (It->second.getInt() == ExtTy)
3422 return;
3423
3424 // Now the new extension is different from old extension, we make
3425 // the type information invalid by setting extension type to
3426 // BothExtension.
3427 ExtTy = BothExtension;
3428 }
3429 PromotedInsts[ExtOpnd] = TypeIsSExt(ExtOpnd->getType(), ExtTy);
3430 }
3431
3432 /// Utility function to query the original type of instruction \p Opnd
3433 /// with a matched extension type. If the extension doesn't match, we
3434 /// cannot use the information we had on the original type.
3435 /// BothExtension doesn't match any extension type.
3436 static const Type *getOrigType(const InstrToOrigTy &PromotedInsts,
3437 Instruction *Opnd,
3438 bool IsSExt) {
3439 ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension;
3440 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
3441 if (It != PromotedInsts.end() && It->second.getInt() == ExtTy)
3442 return It->second.getPointer();
3443 return nullptr;
3444 }
3445
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003446 /// Utility function to check whether or not a sign or zero extension
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003447 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
3448 /// either using the operands of \p Inst or promoting \p Inst.
3449 /// The type of the extension is defined by \p IsSExt.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003450 /// In other words, check if:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003451 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003452 /// #1 Promotion applies:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003453 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003454 /// #2 Operand reuses:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003455 /// ext opnd1 to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003456 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003457 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
3458 const InstrToOrigTy &PromotedInsts, bool IsSExt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003459
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003460 /// Utility function to determine if \p OpIdx should be promoted when
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003461 /// promoting \p Inst.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003462 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
Rafael Espindola84921b92015-10-24 23:11:13 +00003463 return !(isa<SelectInst>(Inst) && OpIdx == 0);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003464 }
3465
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003466 /// Utility function to promote the operand of \p Ext when this
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003467 /// operand is a promotable trunc or sext or zext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003468 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003469 /// \p CreatedInstsCost[out] contains the cost of all instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003470 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003471 /// Newly added extensions are inserted in \p Exts.
3472 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003473 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003474 /// \return The promoted value which is used instead of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003475 static Value *promoteOperandForTruncAndAnyExt(
3476 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003477 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003478 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003479 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003480
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003481 /// Utility function to promote the operand of \p Ext when this
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003482 /// operand is promotable and is not a supported trunc or sext.
3483 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003484 /// \p CreatedInstsCost[out] contains the cost of all the instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003485 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003486 /// Newly added extensions are inserted in \p Exts.
3487 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003488 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003489 /// \return The promoted value which is used instead of Ext.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003490 static Value *promoteOperandForOther(Instruction *Ext,
3491 TypePromotionTransaction &TPT,
3492 InstrToOrigTy &PromotedInsts,
3493 unsigned &CreatedInstsCost,
3494 SmallVectorImpl<Instruction *> *Exts,
3495 SmallVectorImpl<Instruction *> *Truncs,
3496 const TargetLowering &TLI, bool IsSExt);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003497
3498 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003499 static Value *signExtendOperandForOther(
3500 Instruction *Ext, TypePromotionTransaction &TPT,
3501 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3502 SmallVectorImpl<Instruction *> *Exts,
3503 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3504 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3505 Exts, Truncs, TLI, true);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003506 }
3507
3508 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003509 static Value *zeroExtendOperandForOther(
3510 Instruction *Ext, TypePromotionTransaction &TPT,
3511 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3512 SmallVectorImpl<Instruction *> *Exts,
3513 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3514 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3515 Exts, Truncs, TLI, false);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003516 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003517
3518public:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003519 /// Type for the utility function that promotes the operand of Ext.
Eugene Zelenko900b6332017-08-29 22:32:07 +00003520 using Action = Value *(*)(Instruction *Ext, TypePromotionTransaction &TPT,
3521 InstrToOrigTy &PromotedInsts,
3522 unsigned &CreatedInstsCost,
3523 SmallVectorImpl<Instruction *> *Exts,
3524 SmallVectorImpl<Instruction *> *Truncs,
3525 const TargetLowering &TLI);
3526
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00003527 /// Given a sign/zero extend instruction \p Ext, return the appropriate
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003528 /// action to promote the operand of \p Ext instead of using Ext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003529 /// \return NULL if no promotable action is possible with the current
3530 /// sign extension.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003531 /// \p InsertedInsts keeps track of all the instructions inserted by the
3532 /// other CodeGenPrepare optimizations. This information is important
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003533 /// because we do not want to promote these instructions as CodeGenPrepare
3534 /// will reinsert them later. Thus creating an infinite loop: create/remove.
3535 /// \p PromotedInsts maps the instructions to their type before promotion.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003536 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003537 const TargetLowering &TLI,
3538 const InstrToOrigTy &PromotedInsts);
3539};
3540
Eugene Zelenko900b6332017-08-29 22:32:07 +00003541} // end anonymous namespace
3542
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003543bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003544 Type *ConsideredExtType,
3545 const InstrToOrigTy &PromotedInsts,
3546 bool IsSExt) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003547 // The promotion helper does not know how to deal with vector types yet.
3548 // To be able to fix that, we would need to fix the places where we
3549 // statically extend, e.g., constants and such.
3550 if (Inst->getType()->isVectorTy())
3551 return false;
3552
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003553 // We can always get through zext.
3554 if (isa<ZExtInst>(Inst))
3555 return true;
3556
3557 // sext(sext) is ok too.
3558 if (IsSExt && isa<SExtInst>(Inst))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003559 return true;
3560
3561 // We can get through binary operator, if it is legal. In other words, the
3562 // binary operator must have a nuw or nsw flag.
3563 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
3564 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003565 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
3566 (IsSExt && BinOp->hasNoSignedWrap())))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003567 return true;
3568
Guozhi Weic4c6b542018-06-05 21:03:52 +00003569 // ext(and(opnd, cst)) --> and(ext(opnd), ext(cst))
3570 if ((Inst->getOpcode() == Instruction::And ||
3571 Inst->getOpcode() == Instruction::Or))
3572 return true;
3573
3574 // ext(xor(opnd, cst)) --> xor(ext(opnd), ext(cst))
3575 if (Inst->getOpcode() == Instruction::Xor) {
3576 const ConstantInt *Cst = dyn_cast<ConstantInt>(Inst->getOperand(1));
3577 // Make sure it is not a NOT.
3578 if (Cst && !Cst->getValue().isAllOnesValue())
3579 return true;
3580 }
3581
3582 // zext(shrl(opnd, cst)) --> shrl(zext(opnd), zext(cst))
3583 // It may change a poisoned value into a regular value, like
3584 // zext i32 (shrl i8 %val, 12) --> shrl i32 (zext i8 %val), 12
3585 // poisoned value regular value
3586 // It should be OK since undef covers valid value.
3587 if (Inst->getOpcode() == Instruction::LShr && !IsSExt)
3588 return true;
3589
3590 // and(ext(shl(opnd, cst)), cst) --> and(shl(ext(opnd), ext(cst)), cst)
3591 // It may change a poisoned value into a regular value, like
3592 // zext i32 (shl i8 %val, 12) --> shl i32 (zext i8 %val), 12
3593 // poisoned value regular value
3594 // It should be OK since undef covers valid value.
3595 if (Inst->getOpcode() == Instruction::Shl && Inst->hasOneUse()) {
3596 const Instruction *ExtInst =
3597 dyn_cast<const Instruction>(*Inst->user_begin());
3598 if (ExtInst->hasOneUse()) {
3599 const Instruction *AndInst =
3600 dyn_cast<const Instruction>(*ExtInst->user_begin());
3601 if (AndInst && AndInst->getOpcode() == Instruction::And) {
3602 const ConstantInt *Cst = dyn_cast<ConstantInt>(AndInst->getOperand(1));
3603 if (Cst &&
3604 Cst->getValue().isIntN(Inst->getType()->getIntegerBitWidth()))
3605 return true;
3606 }
3607 }
3608 }
3609
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003610 // Check if we can do the following simplification.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003611 // ext(trunc(opnd)) --> ext(opnd)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003612 if (!isa<TruncInst>(Inst))
3613 return false;
3614
3615 Value *OpndVal = Inst->getOperand(0);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003616 // Check if we can use this operand in the extension.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003617 // If the type is larger than the result type of the extension, we cannot.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003618 if (!OpndVal->getType()->isIntegerTy() ||
3619 OpndVal->getType()->getIntegerBitWidth() >
3620 ConsideredExtType->getIntegerBitWidth())
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003621 return false;
3622
3623 // If the operand of the truncate is not an instruction, we will not have
3624 // any information on the dropped bits.
3625 // (Actually we could for constant but it is not worth the extra logic).
3626 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
3627 if (!Opnd)
3628 return false;
3629
3630 // Check if the source of the type is narrow enough.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003631 // I.e., check that trunc just drops extended bits of the same kind of
3632 // the extension.
3633 // #1 get the type of the operand and check the kind of the extended bits.
Guozhi Wei8c17f9a2018-08-15 22:08:26 +00003634 const Type *OpndType = getOrigType(PromotedInsts, Opnd, IsSExt);
3635 if (OpndType)
3636 ;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003637 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
3638 OpndType = Opnd->getOperand(0)->getType();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003639 else
3640 return false;
3641
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003642 // #2 check that the truncate just drops extended bits.
Rafael Espindola84921b92015-10-24 23:11:13 +00003643 return Inst->getType()->getIntegerBitWidth() >=
3644 OpndType->getIntegerBitWidth();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003645}
3646
3647TypePromotionHelper::Action TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003648 Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003649 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003650 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
3651 "Unexpected instruction type");
3652 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
3653 Type *ExtTy = Ext->getType();
3654 bool IsSExt = isa<SExtInst>(Ext);
3655 // If the operand of the extension is not an instruction, we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003656 // get through.
3657 // If it, check we can get through.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003658 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
Craig Topperc0196b12014-04-14 00:51:57 +00003659 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003660
3661 // Do not promote if the operand has been added by codegenprepare.
3662 // Otherwise, it means we are undoing an optimization that is likely to be
3663 // redone, thus causing potential infinite loop.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003664 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
Craig Topperc0196b12014-04-14 00:51:57 +00003665 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003666
3667 // SExt or Trunc instructions.
3668 // Return the related handler.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003669 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
3670 isa<ZExtInst>(ExtOpnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003671 return promoteOperandForTruncAndAnyExt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003672
3673 // Regular instruction.
3674 // Abort early if we will have to insert non-free instructions.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003675 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
Craig Topperc0196b12014-04-14 00:51:57 +00003676 return nullptr;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003677 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003678}
3679
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003680Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
Eugene Zelenko900b6332017-08-29 22:32:07 +00003681 Instruction *SExt, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003682 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003683 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003684 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003685 // By construction, the operand of SExt is an instruction. Otherwise we cannot
3686 // get through it and this method should not be called.
3687 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
Quentin Colombetac55b152014-09-16 22:36:07 +00003688 Value *ExtVal = SExt;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003689 bool HasMergedNonFreeExt = false;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003690 if (isa<ZExtInst>(SExtOpnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003691 // Replace s|zext(zext(opnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003692 // => zext(opnd).
Quentin Colombet1b274f92015-03-10 21:48:15 +00003693 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00003694 Value *ZExt =
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003695 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
3696 TPT.replaceAllUsesWith(SExt, ZExt);
3697 TPT.eraseInstruction(SExt);
Quentin Colombetac55b152014-09-16 22:36:07 +00003698 ExtVal = ZExt;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003699 } else {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003700 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
3701 // => z|sext(opnd).
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003702 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
3703 }
Quentin Colombet1b274f92015-03-10 21:48:15 +00003704 CreatedInstsCost = 0;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003705
3706 // Remove dead code.
3707 if (SExtOpnd->use_empty())
3708 TPT.eraseInstruction(SExtOpnd);
3709
Quentin Colombet9dcb7242014-09-15 18:26:58 +00003710 // Check if the extension is still needed.
Quentin Colombetac55b152014-09-16 22:36:07 +00003711 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003712 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
Quentin Colombet1b274f92015-03-10 21:48:15 +00003713 if (ExtInst) {
3714 if (Exts)
3715 Exts->push_back(ExtInst);
3716 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
3717 }
Quentin Colombetac55b152014-09-16 22:36:07 +00003718 return ExtVal;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003719 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003720
Quentin Colombet9dcb7242014-09-15 18:26:58 +00003721 // At this point we have: ext ty opnd to ty.
3722 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
3723 Value *NextVal = ExtInst->getOperand(0);
3724 TPT.eraseInstruction(ExtInst, NextVal);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003725 return NextVal;
3726}
3727
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003728Value *TypePromotionHelper::promoteOperandForOther(
3729 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003730 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003731 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003732 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
3733 bool IsSExt) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003734 // By construction, the operand of Ext is an instruction. Otherwise we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003735 // get through it and this method should not be called.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003736 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
Quentin Colombet1b274f92015-03-10 21:48:15 +00003737 CreatedInstsCost = 0;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003738 if (!ExtOpnd->hasOneUse()) {
3739 // ExtOpnd will be promoted.
3740 // All its uses, but Ext, will need to use a truncated value of the
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003741 // promoted version.
3742 // Create the truncate now.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003743 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
Quentin Colombetac55b152014-09-16 22:36:07 +00003744 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
Quentin Colombetac55b152014-09-16 22:36:07 +00003745 // Insert it just after the definition.
Sanjay Patel674d2c22017-08-29 14:07:48 +00003746 ITrunc->moveAfter(ExtOpnd);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003747 if (Truncs)
3748 Truncs->push_back(ITrunc);
Quentin Colombetac55b152014-09-16 22:36:07 +00003749 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003750
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003751 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003752 // Restore the operand of Ext (which has been replaced by the previous call
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003753 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003754 TPT.setOperand(Ext, 0, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003755 }
3756
3757 // Get through the Instruction:
3758 // 1. Update its type.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003759 // 2. Replace the uses of Ext by Inst.
3760 // 3. Extend each operand that needs to be extended.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003761
3762 // Remember the original type of the instruction before promotion.
3763 // This is useful to know that the high bits are sign extended bits.
Guozhi Wei8c17f9a2018-08-15 22:08:26 +00003764 addPromotedInst(PromotedInsts, ExtOpnd, IsSExt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003765 // Step #1.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003766 TPT.mutateType(ExtOpnd, Ext->getType());
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003767 // Step #2.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003768 TPT.replaceAllUsesWith(Ext, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003769 // Step #3.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003770 Instruction *ExtForOpnd = Ext;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003771
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003772 LLVM_DEBUG(dbgs() << "Propagate Ext to operands\n");
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003773 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003774 ++OpIdx) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003775 LLVM_DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003776 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
3777 !shouldExtOperand(ExtOpnd, OpIdx)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003778 LLVM_DEBUG(dbgs() << "No need to propagate\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003779 continue;
3780 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003781 // Check if we can statically extend the operand.
3782 Value *Opnd = ExtOpnd->getOperand(OpIdx);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003783 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003784 LLVM_DEBUG(dbgs() << "Statically extend\n");
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003785 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
3786 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
3787 : Cst->getValue().zext(BitWidth);
3788 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003789 continue;
3790 }
3791 // UndefValue are typed, so we have to statically sign extend them.
3792 if (isa<UndefValue>(Opnd)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003793 LLVM_DEBUG(dbgs() << "Statically extend\n");
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003794 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003795 continue;
3796 }
3797
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00003798 // Otherwise we have to explicitly sign extend the operand.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003799 // Check if Ext was reused to extend an operand.
3800 if (!ExtForOpnd) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003801 // If yes, create a new one.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003802 LLVM_DEBUG(dbgs() << "More operands to ext\n");
Quentin Colombet84f89cc2014-12-22 18:11:52 +00003803 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
3804 : TPT.createZExt(Ext, Opnd, Ext->getType());
3805 if (!isa<Instruction>(ValForExtOpnd)) {
3806 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
3807 continue;
3808 }
3809 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003810 }
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003811 if (Exts)
3812 Exts->push_back(ExtForOpnd);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003813 TPT.setOperand(ExtForOpnd, 0, Opnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003814
3815 // Move the sign extension before the insertion point.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003816 TPT.moveBefore(ExtForOpnd, ExtOpnd);
3817 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
Quentin Colombet1b274f92015-03-10 21:48:15 +00003818 CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003819 // If more sext are required, new instructions will have to be created.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003820 ExtForOpnd = nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003821 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003822 if (ExtForOpnd == Ext) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003823 LLVM_DEBUG(dbgs() << "Extension is useless now\n");
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003824 TPT.eraseInstruction(Ext);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003825 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003826 return ExtOpnd;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003827}
3828
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003829/// Check whether or not promoting an instruction to a wider type is profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003830/// \p NewCost gives the cost of extension instructions created by the
3831/// promotion.
3832/// \p OldCost gives the cost of extension instructions before the promotion
3833/// plus the number of instructions that have been
3834/// matched in the addressing mode the promotion.
Quentin Colombet867c5502014-02-14 22:23:22 +00003835/// \p PromotedOperand is the value that has been promoted.
3836/// \return True if the promotion is profitable, false otherwise.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003837bool AddressingModeMatcher::isPromotionProfitable(
Quentin Colombet1b274f92015-03-10 21:48:15 +00003838 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003839 LLVM_DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost
3840 << '\n');
Quentin Colombet1b274f92015-03-10 21:48:15 +00003841 // The cost of the new extensions is greater than the cost of the
3842 // old extension plus what we folded.
Quentin Colombet867c5502014-02-14 22:23:22 +00003843 // This is not profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003844 if (NewCost > OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003845 return false;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003846 if (NewCost < OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003847 return true;
3848 // The promotion is neutral but it may help folding the sign extension in
3849 // loads for instance.
3850 // Check that we did not create an illegal instruction.
Mehdi Amini44ede332015-07-09 02:09:04 +00003851 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
Quentin Colombet867c5502014-02-14 22:23:22 +00003852}
3853
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003854/// Given an instruction or constant expr, see if we can fold the operation
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003855/// into the addressing mode. If so, update the addressing mode and return
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003856/// true, otherwise return false without modifying AddrMode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003857/// If \p MovedAway is not NULL, it contains the information of whether or
3858/// not AddrInst has to be folded into the addressing mode on success.
3859/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
3860/// because it has been moved away.
3861/// Thus AddrInst must not be added in the matched instructions.
3862/// This state can happen when AddrInst is a sext, since it may be moved away.
3863/// Therefore, AddrInst may not be valid when MovedAway is true and it must
3864/// not be referenced anymore.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003865bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003866 unsigned Depth,
3867 bool *MovedAway) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003868 // Avoid exponential behavior on extremely deep expression trees.
3869 if (Depth >= 5) return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003870
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003871 // By default, all matched instructions stay in place.
3872 if (MovedAway)
3873 *MovedAway = false;
3874
Chandler Carruthc8925912013-01-05 02:09:22 +00003875 switch (Opcode) {
3876 case Instruction::PtrToInt:
3877 // PtrToInt is always a noop, as we know that the int type is pointer sized.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003878 return matchAddr(AddrInst->getOperand(0), Depth);
Mehdi Amini44ede332015-07-09 02:09:04 +00003879 case Instruction::IntToPtr: {
3880 auto AS = AddrInst->getType()->getPointerAddressSpace();
3881 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
Chandler Carruthc8925912013-01-05 02:09:22 +00003882 // This inttoptr is a no-op if the integer type is pointer sized.
Mehdi Amini44ede332015-07-09 02:09:04 +00003883 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
Sanjay Patelfc580a62015-09-21 23:03:16 +00003884 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003885 return false;
Mehdi Amini44ede332015-07-09 02:09:04 +00003886 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003887 case Instruction::BitCast:
3888 // BitCast is always a noop, and we can handle it as long as it is
3889 // int->int or pointer->pointer (we don't want int<->fp or something).
Vedant Kumarb3091da2018-07-06 20:17:42 +00003890 if (AddrInst->getOperand(0)->getType()->isIntOrPtrTy() &&
Chandler Carruthc8925912013-01-05 02:09:22 +00003891 // Don't touch identity bitcasts. These were probably put here by LSR,
3892 // and we don't want to mess around with them. Assume it knows what it
3893 // is doing.
3894 AddrInst->getOperand(0)->getType() != AddrInst->getType())
Sanjay Patelfc580a62015-09-21 23:03:16 +00003895 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003896 return false;
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003897 case Instruction::AddrSpaceCast: {
3898 unsigned SrcAS
3899 = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
3900 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
3901 if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
Sanjay Patelfc580a62015-09-21 23:03:16 +00003902 return matchAddr(AddrInst->getOperand(0), Depth);
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003903 return false;
3904 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003905 case Instruction::Add: {
3906 // Check to see if we can merge in the RHS then the LHS. If so, we win.
3907 ExtAddrMode BackupAddrMode = AddrMode;
3908 unsigned OldSize = AddrModeInsts.size();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003909 // Start a transaction at this point.
3910 // The LHS may match but not the RHS.
3911 // Therefore, we need a higher level restoration point to undo partially
3912 // matched operation.
3913 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3914 TPT.getRestorationPoint();
3915
Sanjay Patelfc580a62015-09-21 23:03:16 +00003916 if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
3917 matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003918 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003919
Chandler Carruthc8925912013-01-05 02:09:22 +00003920 // Restore the old addr mode info.
3921 AddrMode = BackupAddrMode;
3922 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003923 TPT.rollback(LastKnownGood);
Stephen Lin837bba12013-07-15 17:55:02 +00003924
Chandler Carruthc8925912013-01-05 02:09:22 +00003925 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003926 if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
3927 matchAddr(AddrInst->getOperand(1), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003928 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003929
Chandler Carruthc8925912013-01-05 02:09:22 +00003930 // Otherwise we definitely can't merge the ADD in.
3931 AddrMode = BackupAddrMode;
3932 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003933 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003934 break;
3935 }
3936 //case Instruction::Or:
3937 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
3938 //break;
3939 case Instruction::Mul:
3940 case Instruction::Shl: {
3941 // Can only handle X*C and X << C.
3942 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
Philip Reames9c3cbee2017-10-30 23:59:51 +00003943 if (!RHS || RHS->getBitWidth() > 64)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003944 return false;
Chandler Carruthc8925912013-01-05 02:09:22 +00003945 int64_t Scale = RHS->getSExtValue();
3946 if (Opcode == Instruction::Shl)
3947 Scale = 1LL << Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00003948
Sanjay Patelfc580a62015-09-21 23:03:16 +00003949 return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003950 }
3951 case Instruction::GetElementPtr: {
3952 // Scan the GEP. We check it if it contains constant offsets and at most
3953 // one variable offset.
3954 int VariableOperand = -1;
3955 unsigned VariableScale = 0;
Stephen Lin837bba12013-07-15 17:55:02 +00003956
Chandler Carruthc8925912013-01-05 02:09:22 +00003957 int64_t ConstantOffset = 0;
Chandler Carruthc8925912013-01-05 02:09:22 +00003958 gep_type_iterator GTI = gep_type_begin(AddrInst);
3959 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
Peter Collingbourneab85225b2016-12-02 02:24:42 +00003960 if (StructType *STy = GTI.getStructTypeOrNull()) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003961 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruthc8925912013-01-05 02:09:22 +00003962 unsigned Idx =
3963 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
3964 ConstantOffset += SL->getElementOffset(Idx);
3965 } else {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003966 uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
Chandler Carruthc8925912013-01-05 02:09:22 +00003967 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
Simon Pilgrimee82a792018-08-13 12:10:09 +00003968 const APInt &CVal = CI->getValue();
3969 if (CVal.getMinSignedBits() <= 64) {
3970 ConstantOffset += CVal.getSExtValue() * TypeSize;
3971 continue;
3972 }
3973 }
3974 if (TypeSize) { // Scales of zero don't do anything.
Chandler Carruthc8925912013-01-05 02:09:22 +00003975 // We only allow one variable index at the moment.
3976 if (VariableOperand != -1)
3977 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003978
Chandler Carruthc8925912013-01-05 02:09:22 +00003979 // Remember the variable index.
3980 VariableOperand = i;
3981 VariableScale = TypeSize;
3982 }
3983 }
3984 }
Stephen Lin837bba12013-07-15 17:55:02 +00003985
Chandler Carruthc8925912013-01-05 02:09:22 +00003986 // A common case is for the GEP to only do a constant offset. In this case,
3987 // just add it to the disp field and check validity.
3988 if (VariableOperand == -1) {
3989 AddrMode.BaseOffs += ConstantOffset;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003990 if (ConstantOffset == 0 ||
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003991 TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003992 // Check to see if we can fold the base pointer in too.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003993 if (matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003994 return true;
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00003995 } else if (EnableGEPOffsetSplit && isa<GetElementPtrInst>(AddrInst) &&
3996 TLI.shouldConsiderGEPOffsetSplit() && Depth == 0 &&
3997 ConstantOffset > 0) {
3998 // Record GEPs with non-zero offsets as candidates for splitting in the
3999 // event that the offset cannot fit into the r+i addressing mode.
4000 // Simple and common case that only one GEP is used in calculating the
4001 // address for the memory access.
4002 Value *Base = AddrInst->getOperand(0);
4003 auto *BaseI = dyn_cast<Instruction>(Base);
4004 auto *GEP = cast<GetElementPtrInst>(AddrInst);
4005 if (isa<Argument>(Base) || isa<GlobalValue>(Base) ||
4006 (BaseI && !isa<CastInst>(BaseI) &&
4007 !isa<GetElementPtrInst>(BaseI))) {
4008 // If the base is an instruction, make sure the GEP is not in the same
4009 // basic block as the base. If the base is an argument or global
4010 // value, make sure the GEP is not in the entry block. Otherwise,
4011 // instruction selection can undo the split. Also make sure the
4012 // parent block allows inserting non-PHI instructions before the
4013 // terminator.
4014 BasicBlock *Parent =
4015 BaseI ? BaseI->getParent() : &GEP->getFunction()->getEntryBlock();
4016 if (GEP->getParent() != Parent && !Parent->getTerminator()->isEHPad())
4017 LargeOffsetGEP = std::make_pair(GEP, ConstantOffset);
4018 }
Chandler Carruthc8925912013-01-05 02:09:22 +00004019 }
4020 AddrMode.BaseOffs -= ConstantOffset;
4021 return false;
4022 }
4023
4024 // Save the valid addressing mode in case we can't match.
4025 ExtAddrMode BackupAddrMode = AddrMode;
4026 unsigned OldSize = AddrModeInsts.size();
4027
4028 // See if the scale and offset amount is valid for this target.
4029 AddrMode.BaseOffs += ConstantOffset;
4030
4031 // Match the base operand of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004032 if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00004033 // If it couldn't be matched, just stuff the value in a register.
4034 if (AddrMode.HasBaseReg) {
4035 AddrMode = BackupAddrMode;
4036 AddrModeInsts.resize(OldSize);
4037 return false;
4038 }
4039 AddrMode.HasBaseReg = true;
4040 AddrMode.BaseReg = AddrInst->getOperand(0);
4041 }
4042
4043 // Match the remaining variable portion of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004044 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
Chandler Carruthc8925912013-01-05 02:09:22 +00004045 Depth)) {
4046 // If it couldn't be matched, try stuffing the base into a register
4047 // instead of matching it, and retrying the match of the scale.
4048 AddrMode = BackupAddrMode;
4049 AddrModeInsts.resize(OldSize);
4050 if (AddrMode.HasBaseReg)
4051 return false;
4052 AddrMode.HasBaseReg = true;
4053 AddrMode.BaseReg = AddrInst->getOperand(0);
4054 AddrMode.BaseOffs += ConstantOffset;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004055 if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
Chandler Carruthc8925912013-01-05 02:09:22 +00004056 VariableScale, Depth)) {
4057 // If even that didn't work, bail.
4058 AddrMode = BackupAddrMode;
4059 AddrModeInsts.resize(OldSize);
4060 return false;
4061 }
4062 }
4063
4064 return true;
4065 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00004066 case Instruction::SExt:
4067 case Instruction::ZExt: {
4068 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
4069 if (!Ext)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00004070 return false;
Sanjay Patelab60d042014-07-16 21:08:10 +00004071
Quentin Colombetf5485bb2014-11-13 01:44:51 +00004072 // Try to move this ext out of the way of the addressing mode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004073 // Ask for a method for doing so.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00004074 TypePromotionHelper::Action TPH =
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004075 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004076 if (!TPH)
4077 return false;
4078
4079 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4080 TPT.getRestorationPoint();
Quentin Colombet1b274f92015-03-10 21:48:15 +00004081 unsigned CreatedInstsCost = 0;
4082 unsigned ExtCost = !TLI.isExtFree(Ext);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004083 Value *PromotedOperand =
Quentin Colombet1b274f92015-03-10 21:48:15 +00004084 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004085 // SExt has been moved away.
4086 // Thus either it will be rematched later in the recursive calls or it is
4087 // gone. Anyway, we must not fold it into the addressing mode at this point.
4088 // E.g.,
4089 // op = add opnd, 1
Quentin Colombetf5485bb2014-11-13 01:44:51 +00004090 // idx = ext op
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004091 // addr = gep base, idx
4092 // is now:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00004093 // promotedOpnd = ext opnd <- no match here
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004094 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
4095 // addr = gep base, op <- match
4096 if (MovedAway)
4097 *MovedAway = true;
4098
4099 assert(PromotedOperand &&
4100 "TypePromotionHelper should have filtered out those cases");
4101
4102 ExtAddrMode BackupAddrMode = AddrMode;
4103 unsigned OldSize = AddrModeInsts.size();
4104
Sanjay Patelfc580a62015-09-21 23:03:16 +00004105 if (!matchAddr(PromotedOperand, Depth) ||
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00004106 // The total of the new cost is equal to the cost of the created
Quentin Colombet1b274f92015-03-10 21:48:15 +00004107 // instructions.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00004108 // The total of the old cost is equal to the cost of the extension plus
Quentin Colombet1b274f92015-03-10 21:48:15 +00004109 // what we have saved in the addressing mode.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004110 !isPromotionProfitable(CreatedInstsCost,
Quentin Colombet1b274f92015-03-10 21:48:15 +00004111 ExtCost + (AddrModeInsts.size() - OldSize),
Quentin Colombet867c5502014-02-14 22:23:22 +00004112 PromotedOperand)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004113 AddrMode = BackupAddrMode;
4114 AddrModeInsts.resize(OldSize);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004115 LLVM_DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004116 TPT.rollback(LastKnownGood);
4117 return false;
4118 }
4119 return true;
4120 }
Chandler Carruthc8925912013-01-05 02:09:22 +00004121 }
4122 return false;
4123}
4124
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004125/// If we can, try to add the value of 'Addr' into the current addressing mode.
4126/// If Addr can't be added to AddrMode this returns false and leaves AddrMode
4127/// unmodified. This assumes that Addr is either a pointer type or intptr_t
4128/// for the target.
Chandler Carruthc8925912013-01-05 02:09:22 +00004129///
Sanjay Patelfc580a62015-09-21 23:03:16 +00004130bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004131 // Start a transaction at this point that we will rollback if the matching
4132 // fails.
4133 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4134 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00004135 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
4136 // Fold in immediates if legal for the target.
4137 AddrMode.BaseOffs += CI->getSExtValue();
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00004138 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00004139 return true;
4140 AddrMode.BaseOffs -= CI->getSExtValue();
4141 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
4142 // If this is a global variable, try to fold it into the addressing mode.
Craig Topperc0196b12014-04-14 00:51:57 +00004143 if (!AddrMode.BaseGV) {
Chandler Carruthc8925912013-01-05 02:09:22 +00004144 AddrMode.BaseGV = GV;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00004145 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00004146 return true;
Craig Topperc0196b12014-04-14 00:51:57 +00004147 AddrMode.BaseGV = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00004148 }
4149 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
4150 ExtAddrMode BackupAddrMode = AddrMode;
4151 unsigned OldSize = AddrModeInsts.size();
4152
4153 // Check to see if it is possible to fold this operation.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004154 bool MovedAway = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004155 if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00004156 // This instruction may have been moved away. If so, there is nothing
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004157 // to check here.
4158 if (MovedAway)
4159 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00004160 // Okay, it's possible to fold this. Check to see if it is actually
4161 // *profitable* to do so. We use a simple cost model to avoid increasing
4162 // register pressure too much.
4163 if (I->hasOneUse() ||
Sanjay Patelfc580a62015-09-21 23:03:16 +00004164 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00004165 AddrModeInsts.push_back(I);
4166 return true;
4167 }
Stephen Lin837bba12013-07-15 17:55:02 +00004168
Chandler Carruthc8925912013-01-05 02:09:22 +00004169 // It isn't profitable to do this, roll back.
4170 //cerr << "NOT FOLDING: " << *I;
4171 AddrMode = BackupAddrMode;
4172 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004173 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00004174 }
4175 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
Sanjay Patelfc580a62015-09-21 23:03:16 +00004176 if (matchOperationAddr(CE, CE->getOpcode(), Depth))
Chandler Carruthc8925912013-01-05 02:09:22 +00004177 return true;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004178 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00004179 } else if (isa<ConstantPointerNull>(Addr)) {
4180 // Null pointer gets folded without affecting the addressing mode.
4181 return true;
4182 }
4183
4184 // Worse case, the target should support [reg] addressing modes. :)
4185 if (!AddrMode.HasBaseReg) {
4186 AddrMode.HasBaseReg = true;
4187 AddrMode.BaseReg = Addr;
4188 // Still check for legality in case the target supports [imm] but not [i+r].
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00004189 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00004190 return true;
4191 AddrMode.HasBaseReg = false;
Craig Topperc0196b12014-04-14 00:51:57 +00004192 AddrMode.BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00004193 }
4194
4195 // If the base register is already taken, see if we can do [r+r].
4196 if (AddrMode.Scale == 0) {
4197 AddrMode.Scale = 1;
4198 AddrMode.ScaledReg = Addr;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00004199 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00004200 return true;
4201 AddrMode.Scale = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00004202 AddrMode.ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00004203 }
4204 // Couldn't match.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004205 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00004206 return false;
4207}
4208
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004209/// Check to see if all uses of OpVal by the specified inline asm call are due
4210/// to memory operands. If so, return true, otherwise return false.
Chandler Carruthc8925912013-01-05 02:09:22 +00004211static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004212 const TargetLowering &TLI,
4213 const TargetRegisterInfo &TRI) {
Sanjay Patel4137d512017-06-07 14:29:52 +00004214 const Function *F = CI->getFunction();
Eric Christopherd75c00c2015-02-26 22:38:34 +00004215 TargetLowering::AsmOperandInfoVector TargetConstraints =
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004216 TLI.ParseConstraints(F->getParent()->getDataLayout(), &TRI,
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00004217 ImmutableCallSite(CI));
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004218
Chandler Carruthc8925912013-01-05 02:09:22 +00004219 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
4220 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Stephen Lin837bba12013-07-15 17:55:02 +00004221
Chandler Carruthc8925912013-01-05 02:09:22 +00004222 // Compute the constraint code and ConstraintType to use.
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004223 TLI.ComputeConstraintToUse(OpInfo, SDValue());
Chandler Carruthc8925912013-01-05 02:09:22 +00004224
4225 // If this asm operand is our Value*, and if it isn't an indirect memory
4226 // operand, we can't fold it!
4227 if (OpInfo.CallOperandVal == OpVal &&
4228 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
4229 !OpInfo.isIndirect))
4230 return false;
4231 }
4232
4233 return true;
4234}
4235
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004236// Max number of memory uses to look at before aborting the search to conserve
4237// compile time.
4238static constexpr int MaxMemoryUsesToScan = 20;
4239
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004240/// Recursively walk all the uses of I until we find a memory use.
4241/// If we find an obviously non-foldable instruction, return true.
Chandler Carruthc8925912013-01-05 02:09:22 +00004242/// Add the ultimately found memory instructions to MemoryUses.
Eric Christopher11e4df72015-02-26 22:38:43 +00004243static bool FindAllMemoryUses(
4244 Instruction *I,
4245 SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004246 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetLowering &TLI,
4247 const TargetRegisterInfo &TRI, int SeenInsts = 0) {
Chandler Carruthc8925912013-01-05 02:09:22 +00004248 // If we already considered this instruction, we're done.
David Blaikie70573dc2014-11-19 07:49:26 +00004249 if (!ConsideredInsts.insert(I).second)
Chandler Carruthc8925912013-01-05 02:09:22 +00004250 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00004251
Chandler Carruthc8925912013-01-05 02:09:22 +00004252 // If this is an obviously unfoldable instruction, bail out.
4253 if (!MightBeFoldableInst(I))
4254 return true;
4255
Philip Reamesac115ed2016-03-09 23:13:12 +00004256 const bool OptSize = I->getFunction()->optForSize();
4257
Chandler Carruthc8925912013-01-05 02:09:22 +00004258 // Loop over all the uses, recursively processing them.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004259 for (Use &U : I->uses()) {
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004260 // Conservatively return true if we're seeing a large number or a deep chain
4261 // of users. This avoids excessive compilation times in pathological cases.
4262 if (SeenInsts++ >= MaxMemoryUsesToScan)
4263 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00004264
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004265 Instruction *UserI = cast<Instruction>(U.getUser());
Chandler Carruthcdf47882014-03-09 03:16:01 +00004266 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
4267 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
Chandler Carruthc8925912013-01-05 02:09:22 +00004268 continue;
4269 }
Stephen Lin837bba12013-07-15 17:55:02 +00004270
Chandler Carruthcdf47882014-03-09 03:16:01 +00004271 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
4272 unsigned opNo = U.getOperandNo();
Matt Arsenault02d915b2017-03-15 22:35:20 +00004273 if (opNo != StoreInst::getPointerOperandIndex())
4274 return true; // Storing addr, not into addr.
Chandler Carruthc8925912013-01-05 02:09:22 +00004275 MemoryUses.push_back(std::make_pair(SI, opNo));
4276 continue;
4277 }
Stephen Lin837bba12013-07-15 17:55:02 +00004278
Matt Arsenault02d915b2017-03-15 22:35:20 +00004279 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UserI)) {
4280 unsigned opNo = U.getOperandNo();
4281 if (opNo != AtomicRMWInst::getPointerOperandIndex())
4282 return true; // Storing addr, not into addr.
4283 MemoryUses.push_back(std::make_pair(RMW, opNo));
4284 continue;
4285 }
4286
4287 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(UserI)) {
4288 unsigned opNo = U.getOperandNo();
4289 if (opNo != AtomicCmpXchgInst::getPointerOperandIndex())
4290 return true; // Storing addr, not into addr.
4291 MemoryUses.push_back(std::make_pair(CmpX, opNo));
4292 continue;
4293 }
4294
Chandler Carruthcdf47882014-03-09 03:16:01 +00004295 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
Philip Reamesac115ed2016-03-09 23:13:12 +00004296 // If this is a cold call, we can sink the addressing calculation into
4297 // the cold path. See optimizeCallInst
4298 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
4299 continue;
Junmo Park6098cbb2016-03-11 07:05:32 +00004300
Chandler Carruthc8925912013-01-05 02:09:22 +00004301 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
4302 if (!IA) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004303
Chandler Carruthc8925912013-01-05 02:09:22 +00004304 // If this is a memory operand, we're cool, otherwise bail out.
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004305 if (!IsOperandAMemoryOperand(CI, IA, I, TLI, TRI))
Chandler Carruthc8925912013-01-05 02:09:22 +00004306 return true;
4307 continue;
4308 }
Stephen Lin837bba12013-07-15 17:55:02 +00004309
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004310 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI, TRI,
4311 SeenInsts))
Chandler Carruthc8925912013-01-05 02:09:22 +00004312 return true;
4313 }
4314
4315 return false;
4316}
4317
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00004318/// Return true if Val is already known to be live at the use site that we're
4319/// folding it into. If so, there is no cost to include it in the addressing
4320/// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
4321/// instruction already.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004322bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
Chandler Carruthc8925912013-01-05 02:09:22 +00004323 Value *KnownLive2) {
4324 // If Val is either of the known-live values, we know it is live!
Craig Topperc0196b12014-04-14 00:51:57 +00004325 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
Chandler Carruthc8925912013-01-05 02:09:22 +00004326 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004327
Chandler Carruthc8925912013-01-05 02:09:22 +00004328 // All values other than instructions and arguments (e.g. constants) are live.
4329 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004330
Chandler Carruthc8925912013-01-05 02:09:22 +00004331 // If Val is a constant sized alloca in the entry block, it is live, this is
4332 // true because it is just a reference to the stack/frame pointer, which is
4333 // live for the whole function.
4334 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
4335 if (AI->isStaticAlloca())
4336 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004337
Chandler Carruthc8925912013-01-05 02:09:22 +00004338 // Check to see if this value is already used in the memory instruction's
4339 // block. If so, it's already live into the block at the very least, so we
4340 // can reasonably fold it.
4341 return Val->isUsedInBasicBlock(MemoryInst->getParent());
4342}
4343
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004344/// It is possible for the addressing mode of the machine to fold the specified
4345/// instruction into a load or store that ultimately uses it.
4346/// However, the specified instruction has multiple uses.
4347/// Given this, it may actually increase register pressure to fold it
4348/// into the load. For example, consider this code:
Chandler Carruthc8925912013-01-05 02:09:22 +00004349///
4350/// X = ...
4351/// Y = X+1
4352/// use(Y) -> nonload/store
4353/// Z = Y+1
4354/// load Z
4355///
4356/// In this case, Y has multiple uses, and can be folded into the load of Z
4357/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
4358/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
4359/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
4360/// number of computations either.
4361///
4362/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
4363/// X was live across 'load Z' for other reasons, we actually *would* want to
4364/// fold the addressing mode in the Z case. This would make Y die earlier.
4365bool AddressingModeMatcher::
Sanjay Patelfc580a62015-09-21 23:03:16 +00004366isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
Chandler Carruthc8925912013-01-05 02:09:22 +00004367 ExtAddrMode &AMAfter) {
4368 if (IgnoreProfitability) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004369
Chandler Carruthc8925912013-01-05 02:09:22 +00004370 // AMBefore is the addressing mode before this instruction was folded into it,
4371 // and AMAfter is the addressing mode after the instruction was folded. Get
4372 // the set of registers referenced by AMAfter and subtract out those
4373 // referenced by AMBefore: this is the set of values which folding in this
4374 // address extends the lifetime of.
4375 //
4376 // Note that there are only two potential values being referenced here,
4377 // BaseReg and ScaleReg (global addresses are always available, as are any
4378 // folded immediates).
4379 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
Stephen Lin837bba12013-07-15 17:55:02 +00004380
Chandler Carruthc8925912013-01-05 02:09:22 +00004381 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
4382 // lifetime wasn't extended by adding this instruction.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004383 if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00004384 BaseReg = nullptr;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004385 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00004386 ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00004387
4388 // If folding this instruction (and it's subexprs) didn't extend any live
4389 // ranges, we're ok with it.
Craig Topperc0196b12014-04-14 00:51:57 +00004390 if (!BaseReg && !ScaledReg)
Chandler Carruthc8925912013-01-05 02:09:22 +00004391 return true;
4392
Philip Reamesac115ed2016-03-09 23:13:12 +00004393 // If all uses of this instruction can have the address mode sunk into them,
4394 // we can remove the addressing mode and effectively trade one live register
4395 // for another (at worst.) In this context, folding an addressing mode into
Junmo Park6098cbb2016-03-11 07:05:32 +00004396 // the use is just a particularly nice way of sinking it.
Chandler Carruthc8925912013-01-05 02:09:22 +00004397 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
4398 SmallPtrSet<Instruction*, 16> ConsideredInsts;
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004399 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI, TRI))
Chandler Carruthc8925912013-01-05 02:09:22 +00004400 return false; // Has a non-memory, non-foldable use!
Stephen Lin837bba12013-07-15 17:55:02 +00004401
Chandler Carruthc8925912013-01-05 02:09:22 +00004402 // Now that we know that all uses of this instruction are part of a chain of
4403 // computation involving only operations that could theoretically be folded
Philip Reamesac115ed2016-03-09 23:13:12 +00004404 // into a memory use, loop over each of these memory operation uses and see
4405 // if they could *actually* fold the instruction. The assumption is that
4406 // addressing modes are cheap and that duplicating the computation involved
4407 // many times is worthwhile, even on a fastpath. For sinking candidates
4408 // (i.e. cold call sites), this serves as a way to prevent excessive code
4409 // growth since most architectures have some reasonable small and fast way to
4410 // compute an effective address. (i.e LEA on x86)
Chandler Carruthc8925912013-01-05 02:09:22 +00004411 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
4412 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
4413 Instruction *User = MemoryUses[i].first;
4414 unsigned OpNo = MemoryUses[i].second;
Stephen Lin837bba12013-07-15 17:55:02 +00004415
Chandler Carruthc8925912013-01-05 02:09:22 +00004416 // Get the access type of this use. If the use isn't a pointer, we don't
4417 // know what it accesses.
4418 Value *Address = User->getOperand(OpNo);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004419 PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
4420 if (!AddrTy)
Chandler Carruthc8925912013-01-05 02:09:22 +00004421 return false;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004422 Type *AddressAccessTy = AddrTy->getElementType();
4423 unsigned AS = AddrTy->getAddressSpace();
Stephen Lin837bba12013-07-15 17:55:02 +00004424
Chandler Carruthc8925912013-01-05 02:09:22 +00004425 // Do a match against the root of this address, ignoring profitability. This
4426 // will tell us if the addressing mode for the memory operation will
4427 // *actually* cover the shared instruction.
4428 ExtAddrMode Result;
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00004429 std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr,
4430 0);
Quentin Colombet5a69dda2014-02-11 01:59:02 +00004431 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4432 TPT.getRestorationPoint();
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00004433 AddressingModeMatcher Matcher(
4434 MatchedAddrModeInsts, TLI, TRI, AddressAccessTy, AS, MemoryInst, Result,
4435 InsertedInsts, PromotedInsts, TPT, LargeOffsetGEP);
Chandler Carruthc8925912013-01-05 02:09:22 +00004436 Matcher.IgnoreProfitability = true;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004437 bool Success = Matcher.matchAddr(Address, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00004438 (void)Success; assert(Success && "Couldn't select *anything*?");
4439
Quentin Colombet5a69dda2014-02-11 01:59:02 +00004440 // The match was to check the profitability, the changes made are not
4441 // part of the original matcher. Therefore, they should be dropped
4442 // otherwise the original matcher will not present the right state.
4443 TPT.rollback(LastKnownGood);
4444
Chandler Carruthc8925912013-01-05 02:09:22 +00004445 // If the match didn't cover I, then it won't be shared by it.
David Majnemer0d955d02016-08-11 22:21:41 +00004446 if (!is_contained(MatchedAddrModeInsts, I))
Chandler Carruthc8925912013-01-05 02:09:22 +00004447 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00004448
Chandler Carruthc8925912013-01-05 02:09:22 +00004449 MatchedAddrModeInsts.clear();
4450 }
Stephen Lin837bba12013-07-15 17:55:02 +00004451
Chandler Carruthc8925912013-01-05 02:09:22 +00004452 return true;
4453}
4454
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004455/// Return true if the specified values are defined in a
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004456/// different basic block than BB.
4457static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
4458 if (Instruction *I = dyn_cast<Instruction>(V))
4459 return I->getParent() != BB;
4460 return false;
4461}
4462
Philip Reamesac115ed2016-03-09 23:13:12 +00004463/// Sink addressing mode computation immediate before MemoryInst if doing so
4464/// can be done without increasing register pressure. The need for the
4465/// register pressure constraint means this can end up being an all or nothing
4466/// decision for all uses of the same addressing computation.
4467///
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004468/// Load and Store Instructions often have addressing modes that can do
4469/// significant amounts of computation. As such, instruction selection will try
4470/// to get the load or store to do as much computation as possible for the
4471/// program. The problem is that isel can only see within a single block. As
4472/// such, we sink as much legal addressing mode work into the block as possible.
Chris Lattner728f9022008-11-25 07:09:13 +00004473///
4474/// This method is used to optimize both load/store and inline asms with memory
Philip Reamesac115ed2016-03-09 23:13:12 +00004475/// operands. It's also used to sink addressing computations feeding into cold
4476/// call sites into their (cold) basic block.
4477///
4478/// The motivation for handling sinking into cold blocks is that doing so can
4479/// both enable other address mode sinking (by satisfying the register pressure
4480/// constraint above), and reduce register pressure globally (by removing the
4481/// addressing mode computation from the fast path entirely.).
Sanjay Patelfc580a62015-09-21 23:03:16 +00004482bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004483 Type *AccessTy, unsigned AddrSpace) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00004484 Value *Repl = Addr;
Nadav Rotem465834c2012-07-24 10:51:42 +00004485
4486 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004487 // unprofitable PRE transformations.
Cameron Zwarich43cecb12011-01-03 06:33:01 +00004488 SmallVector<Value*, 8> worklist;
4489 SmallPtrSet<Value*, 16> Visited;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004490 worklist.push_back(Addr);
Nadav Rotem465834c2012-07-24 10:51:42 +00004491
John Brawneb83c752017-10-03 13:04:15 +00004492 // Use a worklist to iteratively look through PHI and select nodes, and
4493 // ensure that the addressing mode obtained from the non-PHI/select roots of
John Brawn736bf002017-10-03 13:08:22 +00004494 // the graph are compatible.
John Brawneb83c752017-10-03 13:04:15 +00004495 bool PhiOrSelectSeen = false;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004496 SmallVector<Instruction*, 16> AddrModeInsts;
Serguei Katkovaee63752017-11-05 07:59:02 +00004497 const SimplifyQuery SQ(*DL, TLInfo);
Serguei Katkov2673f172018-11-29 06:45:18 +00004498 AddressingModeCombiner AddrModes(SQ, Addr);
Jun Bum Limdee55652017-04-03 19:20:07 +00004499 TypePromotionTransaction TPT(RemovedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004500 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4501 TPT.getRestorationPoint();
Owen Anderson8ba5f392010-11-27 08:15:55 +00004502 while (!worklist.empty()) {
4503 Value *V = worklist.back();
4504 worklist.pop_back();
Nadav Rotem465834c2012-07-24 10:51:42 +00004505
Serguei Katkov4ea855e2017-07-19 04:49:17 +00004506 // We allow traversing cyclic Phi nodes.
4507 // In case of success after this loop we ensure that traversing through
4508 // Phi nodes ends up with all cases to compute address of the form
4509 // BaseGV + Base + Scale * Index + Offset
4510 // where Scale and Offset are constans and BaseGV, Base and Index
4511 // are exactly the same Values in all cases.
4512 // It means that BaseGV, Scale and Offset dominate our memory instruction
4513 // and have the same value as they had in address computation represented
4514 // as Phi. So we can safely sink address computation to memory instruction.
4515 if (!Visited.insert(V).second)
4516 continue;
Nadav Rotem465834c2012-07-24 10:51:42 +00004517
Owen Anderson8ba5f392010-11-27 08:15:55 +00004518 // For a PHI node, push all of its incoming values.
4519 if (PHINode *P = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00004520 for (Value *IncValue : P->incoming_values())
4521 worklist.push_back(IncValue);
John Brawneb83c752017-10-03 13:04:15 +00004522 PhiOrSelectSeen = true;
4523 continue;
4524 }
4525 // Similar for select.
4526 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
4527 worklist.push_back(SI->getFalseValue());
4528 worklist.push_back(SI->getTrueValue());
4529 PhiOrSelectSeen = true;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004530 continue;
4531 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004532
Philip Reamesac115ed2016-03-09 23:13:12 +00004533 // For non-PHIs, determine the addressing mode being computed. Note that
4534 // the result may differ depending on what other uses our candidate
4535 // addressing instructions might have.
Serguei Katkova6fba3d2017-07-18 05:16:38 +00004536 AddrModeInsts.clear();
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00004537 std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr,
4538 0);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004539 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
Serguei Katkova6fba3d2017-07-18 05:16:38 +00004540 V, AccessTy, AddrSpace, MemoryInst, AddrModeInsts, *TLI, *TRI,
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00004541 InsertedInsts, PromotedInsts, TPT, LargeOffsetGEP);
Cameron Zwarich13c885d2011-03-05 08:12:26 +00004542
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00004543 GetElementPtrInst *GEP = LargeOffsetGEP.first;
4544 if (GEP && GEP->getParent() != MemoryInst->getParent() &&
4545 !NewGEPBases.count(GEP)) {
4546 // If splitting the underlying data structure can reduce the offset of a
4547 // GEP, collect the GEP. Skip the GEPs that are the new bases of
4548 // previously split data structures.
4549 LargeOffsetGEPMap[GEP->getPointerOperand()].push_back(LargeOffsetGEP);
4550 if (LargeOffsetGEPID.find(GEP) == LargeOffsetGEPID.end())
4551 LargeOffsetGEPID[GEP] = LargeOffsetGEPID.size();
4552 }
4553
4554 NewAddrMode.OriginalValue = V;
John Brawn736bf002017-10-03 13:08:22 +00004555 if (!AddrModes.addNewAddrMode(NewAddrMode))
4556 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004557 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004558
John Brawn736bf002017-10-03 13:08:22 +00004559 // Try to combine the AddrModes we've collected. If we couldn't collect any,
4560 // or we have multiple but either couldn't combine them or combining them
4561 // wouldn't do anything useful, bail out now.
4562 if (!AddrModes.combineAddrModes()) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004563 TPT.rollback(LastKnownGood);
4564 return false;
4565 }
4566 TPT.commit();
Nadav Rotem465834c2012-07-24 10:51:42 +00004567
John Brawn736bf002017-10-03 13:08:22 +00004568 // Get the combined AddrMode (or the only AddrMode, if we only had one).
4569 ExtAddrMode AddrMode = AddrModes.getAddrMode();
4570
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004571 // If all the instructions matched are already in this BB, don't do anything.
John Brawneb83c752017-10-03 13:04:15 +00004572 // If we saw a Phi node then it is not local definitely, and if we saw a select
4573 // then we want to push the address calculation past it even if it's already
4574 // in this BB.
4575 if (!PhiOrSelectSeen && none_of(AddrModeInsts, [&](Value *V) {
Justin Lebar838c7f52016-11-21 22:49:11 +00004576 return IsNonLocalValue(V, MemoryInst->getParent());
Serguei Katkov0b7b59a2017-07-11 06:24:44 +00004577 })) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004578 LLVM_DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode
4579 << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004580 return false;
4581 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004582
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004583 // Insert this computation right after this user. Since our caller is
4584 // scanning from the top of the BB to the bottom, reuse of the expr are
4585 // guaranteed to happen later.
Devang Patelc10e52a2011-09-06 18:49:53 +00004586 IRBuilder<> Builder(MemoryInst);
Eric Christopherc1ea1492008-09-24 05:32:41 +00004587
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004588 // Now that we determined the addressing expression we want to use and know
4589 // that we have to sink it into this block. Check to see if we have already
Simon Dardis230f4532017-11-24 16:45:28 +00004590 // done this for some other load/store instr in this block. If so, reuse
4591 // the computation. Before attempting reuse, check if the address is valid
4592 // as it may have been erased.
4593
4594 WeakTrackingVH SunkAddrVH = SunkAddrs[Addr];
4595
4596 Value * SunkAddr = SunkAddrVH.pointsToAliveValue() ? SunkAddrVH : nullptr;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004597 if (SunkAddr) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004598 LLVM_DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode
4599 << " for " << *MemoryInst << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004600 if (SunkAddr->getType() != Addr->getType())
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004601 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
Eric Christopherfccff372015-01-27 01:01:38 +00004602 } else if (AddrSinkUsingGEPs ||
David Blaikie8ad9a972018-03-28 22:28:50 +00004603 (!AddrSinkUsingGEPs.getNumOccurrences() && TM && TTI->useAA())) {
Hal Finkelc3998302014-04-12 00:59:48 +00004604 // By default, we use the GEP-based method when AA is used later. This
4605 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004606 LLVM_DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode
4607 << " for " << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00004608 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00004609 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00004610
4611 // First, find the pointer.
4612 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
4613 ResultPtr = AddrMode.BaseReg;
Craig Topperc0196b12014-04-14 00:51:57 +00004614 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00004615 }
4616
4617 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
4618 // We can't add more than one pointer together, nor can we scale a
4619 // pointer (both of which seem meaningless).
4620 if (ResultPtr || AddrMode.Scale != 1)
4621 return false;
4622
4623 ResultPtr = AddrMode.ScaledReg;
4624 AddrMode.Scale = 0;
4625 }
4626
Eli Friedman6f7c9ad2017-07-12 23:30:02 +00004627 // It is only safe to sign extend the BaseReg if we know that the math
4628 // required to create it did not overflow before we extend it. Since
4629 // the original IR value was tossed in favor of a constant back when
4630 // the AddrMode was created we need to bail out gracefully if widths
4631 // do not match instead of extending it.
4632 //
4633 // (See below for code to add the scale.)
4634 if (AddrMode.Scale) {
4635 Type *ScaledRegTy = AddrMode.ScaledReg->getType();
4636 if (cast<IntegerType>(IntPtrTy)->getBitWidth() >
4637 cast<IntegerType>(ScaledRegTy)->getBitWidth())
4638 return false;
4639 }
4640
Hal Finkelc3998302014-04-12 00:59:48 +00004641 if (AddrMode.BaseGV) {
4642 if (ResultPtr)
4643 return false;
4644
4645 ResultPtr = AddrMode.BaseGV;
4646 }
4647
4648 // If the real base value actually came from an inttoptr, then the matcher
4649 // will look through it and provide only the integer value. In that case,
4650 // use it here.
Keno Fischer05e4ac22017-06-29 20:28:59 +00004651 if (!DL->isNonIntegralPointerType(Addr->getType())) {
4652 if (!ResultPtr && AddrMode.BaseReg) {
4653 ResultPtr = Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(),
4654 "sunkaddr");
4655 AddrMode.BaseReg = nullptr;
4656 } else if (!ResultPtr && AddrMode.Scale == 1) {
4657 ResultPtr = Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(),
4658 "sunkaddr");
4659 AddrMode.Scale = 0;
4660 }
Hal Finkelc3998302014-04-12 00:59:48 +00004661 }
4662
4663 if (!ResultPtr &&
4664 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
4665 SunkAddr = Constant::getNullValue(Addr->getType());
4666 } else if (!ResultPtr) {
4667 return false;
4668 } else {
4669 Type *I8PtrTy =
David Blaikie3909da72015-03-30 20:42:56 +00004670 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
4671 Type *I8Ty = Builder.getInt8Ty();
Hal Finkelc3998302014-04-12 00:59:48 +00004672
4673 // Start with the base register. Do this first so that subsequent address
4674 // matching finds it last, which will prevent it from trying to match it
4675 // as the scaled value in case it happens to be a mul. That would be
4676 // problematic if we've sunk a different mul for the scale, because then
4677 // we'd end up sinking both muls.
4678 if (AddrMode.BaseReg) {
4679 Value *V = AddrMode.BaseReg;
4680 if (V->getType() != IntPtrTy)
4681 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
4682
4683 ResultIndex = V;
4684 }
4685
4686 // Add the scale value.
4687 if (AddrMode.Scale) {
4688 Value *V = AddrMode.ScaledReg;
4689 if (V->getType() == IntPtrTy) {
4690 // done.
Hal Finkelc3998302014-04-12 00:59:48 +00004691 } else {
Eli Friedman6f7c9ad2017-07-12 23:30:02 +00004692 assert(cast<IntegerType>(IntPtrTy)->getBitWidth() <
4693 cast<IntegerType>(V->getType())->getBitWidth() &&
4694 "We can't transform if ScaledReg is too narrow");
4695 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004696 }
4697
4698 if (AddrMode.Scale != 1)
4699 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4700 "sunkaddr");
4701 if (ResultIndex)
4702 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
4703 else
4704 ResultIndex = V;
4705 }
4706
4707 // Add in the Base Offset if present.
4708 if (AddrMode.BaseOffs) {
4709 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
4710 if (ResultIndex) {
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00004711 // We need to add this separately from the scale above to help with
4712 // SDAG consecutive load/store merging.
Hal Finkelc3998302014-04-12 00:59:48 +00004713 if (ResultPtr->getType() != I8PtrTy)
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004714 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00004715 ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004716 }
4717
4718 ResultIndex = V;
4719 }
4720
4721 if (!ResultIndex) {
4722 SunkAddr = ResultPtr;
4723 } else {
4724 if (ResultPtr->getType() != I8PtrTy)
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004725 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00004726 SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004727 }
4728
4729 if (SunkAddr->getType() != Addr->getType())
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004730 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
Hal Finkelc3998302014-04-12 00:59:48 +00004731 }
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004732 } else {
Keno Fischer05e4ac22017-06-29 20:28:59 +00004733 // We'd require a ptrtoint/inttoptr down the line, which we can't do for
4734 // non-integral pointers, so in that case bail out now.
4735 Type *BaseTy = AddrMode.BaseReg ? AddrMode.BaseReg->getType() : nullptr;
4736 Type *ScaleTy = AddrMode.Scale ? AddrMode.ScaledReg->getType() : nullptr;
4737 PointerType *BasePtrTy = dyn_cast_or_null<PointerType>(BaseTy);
4738 PointerType *ScalePtrTy = dyn_cast_or_null<PointerType>(ScaleTy);
4739 if (DL->isNonIntegralPointerType(Addr->getType()) ||
4740 (BasePtrTy && DL->isNonIntegralPointerType(BasePtrTy)) ||
4741 (ScalePtrTy && DL->isNonIntegralPointerType(ScalePtrTy)) ||
4742 (AddrMode.BaseGV &&
4743 DL->isNonIntegralPointerType(AddrMode.BaseGV->getType())))
4744 return false;
4745
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004746 LLVM_DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode
4747 << " for " << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00004748 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00004749 Value *Result = nullptr;
Dan Gohmanca194452010-01-19 22:45:06 +00004750
4751 // Start with the base register. Do this first so that subsequent address
4752 // matching finds it last, which will prevent it from trying to match it
4753 // as the scaled value in case it happens to be a mul. That would be
4754 // problematic if we've sunk a different mul for the scale, because then
4755 // we'd end up sinking both muls.
4756 if (AddrMode.BaseReg) {
4757 Value *V = AddrMode.BaseReg;
Duncan Sands19d0b472010-02-16 11:11:14 +00004758 if (V->getType()->isPointerTy())
Devang Patelc10e52a2011-09-06 18:49:53 +00004759 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00004760 if (V->getType() != IntPtrTy)
Devang Patelc10e52a2011-09-06 18:49:53 +00004761 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00004762 Result = V;
4763 }
4764
4765 // Add the scale value.
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004766 if (AddrMode.Scale) {
4767 Value *V = AddrMode.ScaledReg;
4768 if (V->getType() == IntPtrTy) {
4769 // done.
Duncan Sands19d0b472010-02-16 11:11:14 +00004770 } else if (V->getType()->isPointerTy()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004771 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004772 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
4773 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004774 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004775 } else {
Jim Grosbached2cd392014-03-26 17:27:01 +00004776 // It is only safe to sign extend the BaseReg if we know that the math
4777 // required to create it did not overflow before we extend it. Since
4778 // the original IR value was tossed in favor of a constant back when
4779 // the AddrMode was created we need to bail out gracefully if widths
4780 // do not match instead of extending it.
Joey Gouly12a8bf02014-05-13 15:42:45 +00004781 Instruction *I = dyn_cast_or_null<Instruction>(Result);
Jim Grosbach83b44e12014-04-10 00:27:45 +00004782 if (I && (Result != AddrMode.BaseReg))
4783 I->eraseFromParent();
Jim Grosbached2cd392014-03-26 17:27:01 +00004784 return false;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004785 }
4786 if (AddrMode.Scale != 1)
Devang Patelc10e52a2011-09-06 18:49:53 +00004787 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4788 "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004789 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004790 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004791 else
4792 Result = V;
4793 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004794
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004795 // Add in the BaseGV if present.
4796 if (AddrMode.BaseGV) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004797 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004798 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004799 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004800 else
4801 Result = V;
4802 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004803
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004804 // Add in the Base Offset if present.
4805 if (AddrMode.BaseOffs) {
Owen Andersonedb4a702009-07-24 23:12:02 +00004806 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004807 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004808 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004809 else
4810 Result = V;
4811 }
4812
Craig Topperc0196b12014-04-14 00:51:57 +00004813 if (!Result)
Owen Anderson5a1acd92009-07-31 20:28:14 +00004814 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004815 else
Devang Patelc10e52a2011-09-06 18:49:53 +00004816 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004817 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004818
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004819 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Simon Dardis230f4532017-11-24 16:45:28 +00004820 // Store the newly computed address into the cache. In the case we reused a
4821 // value, this should be idempotent.
4822 SunkAddrs[Addr] = WeakTrackingVH(SunkAddr);
Eric Christopherc1ea1492008-09-24 05:32:41 +00004823
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004824 // If we have no uses, recursively delete the value and all dead instructions
4825 // using it.
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004826 if (Repl->use_empty()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004827 // This can cause recursive deletion, which can invalidate our iterator.
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00004828 // Use a WeakTrackingVH to hold onto it in case this happens.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00004829 Value *CurValue = &*CurInstIterator;
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00004830 WeakTrackingVH IterHandle(CurValue);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004831 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00004832
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00004833 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004834
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00004835 if (IterHandle != CurValue) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004836 // If the iterator instruction was recursively deleted, start over at the
4837 // start of the block.
4838 CurInstIterator = BB->begin();
4839 SunkAddrs.clear();
Nadav Rotem465834c2012-07-24 10:51:42 +00004840 }
Dale Johannesenb67a6e662010-03-31 20:37:15 +00004841 }
Cameron Zwarichced753f2011-01-05 17:27:27 +00004842 ++NumMemoryInsts;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004843 return true;
4844}
4845
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004846/// If there are any memory operands, use OptimizeMemoryInst to sink their
4847/// address computing into the block when possible / profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004848bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
Evan Cheng1da25002008-02-26 02:42:37 +00004849 bool MadeChange = false;
Evan Cheng1da25002008-02-26 02:42:37 +00004850
Eric Christopher11e4df72015-02-26 22:38:43 +00004851 const TargetRegisterInfo *TRI =
Sanjay Patel4137d512017-06-07 14:29:52 +00004852 TM->getSubtargetImpl(*CS->getFunction())->getRegisterInfo();
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00004853 TargetLowering::AsmOperandInfoVector TargetConstraints =
4854 TLI->ParseConstraints(*DL, TRI, CS);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00004855 unsigned ArgNo = 0;
John Thompson1094c802010-09-13 18:15:37 +00004856 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
4857 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00004858
Evan Cheng1da25002008-02-26 02:42:37 +00004859 // Compute the constraint code and ConstraintType to use.
Dale Johannesence97d552010-06-25 21:55:36 +00004860 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng1da25002008-02-26 02:42:37 +00004861
Eli Friedman666bbe32008-02-26 18:37:49 +00004862 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4863 OpInfo.isIndirect) {
Chris Lattner7a277142011-01-15 07:14:54 +00004864 Value *OpVal = CS->getArgOperand(ArgNo++);
Sanjay Patelfc580a62015-09-21 23:03:16 +00004865 MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00004866 } else if (OpInfo.Type == InlineAsm::isInput)
4867 ArgNo++;
Evan Cheng1da25002008-02-26 02:42:37 +00004868 }
4869
4870 return MadeChange;
4871}
4872
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004873/// Check if all the uses of \p Val are equivalent (or free) zero or
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004874/// sign extensions.
Jun Bum Lim42301012017-03-17 19:05:21 +00004875static bool hasSameExtUse(Value *Val, const TargetLowering &TLI) {
4876 assert(!Val->use_empty() && "Input must have at least one use");
4877 const Instruction *FirstUser = cast<Instruction>(*Val->user_begin());
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004878 bool IsSExt = isa<SExtInst>(FirstUser);
4879 Type *ExtTy = FirstUser->getType();
Jun Bum Lim42301012017-03-17 19:05:21 +00004880 for (const User *U : Val->users()) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004881 const Instruction *UI = cast<Instruction>(U);
4882 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
4883 return false;
4884 Type *CurTy = UI->getType();
4885 // Same input and output types: Same instruction after CSE.
4886 if (CurTy == ExtTy)
4887 continue;
4888
4889 // If IsSExt is true, we are in this situation:
Jun Bum Lim42301012017-03-17 19:05:21 +00004890 // a = Val
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004891 // b = sext ty1 a to ty2
4892 // c = sext ty1 a to ty3
4893 // Assuming ty2 is shorter than ty3, this could be turned into:
Jun Bum Lim42301012017-03-17 19:05:21 +00004894 // a = Val
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004895 // b = sext ty1 a to ty2
4896 // c = sext ty2 b to ty3
4897 // However, the last sext is not free.
4898 if (IsSExt)
4899 return false;
4900
4901 // This is a ZExt, maybe this is free to extend from one type to another.
4902 // In that case, we would not account for a different use.
4903 Type *NarrowTy;
4904 Type *LargeTy;
4905 if (ExtTy->getScalarType()->getIntegerBitWidth() >
4906 CurTy->getScalarType()->getIntegerBitWidth()) {
4907 NarrowTy = CurTy;
4908 LargeTy = ExtTy;
4909 } else {
4910 NarrowTy = ExtTy;
4911 LargeTy = CurTy;
4912 }
4913
4914 if (!TLI.isZExtFree(NarrowTy, LargeTy))
4915 return false;
4916 }
4917 // All uses are the same or can be derived from one another for free.
4918 return true;
4919}
4920
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004921/// Try to speculatively promote extensions in \p Exts and continue
Jun Bum Lim42301012017-03-17 19:05:21 +00004922/// promoting through newly promoted operands recursively as far as doing so is
4923/// profitable. Save extensions profitably moved up, in \p ProfitablyMovedExts.
4924/// When some promotion happened, \p TPT contains the proper state to revert
4925/// them.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004926///
Jun Bum Lim42301012017-03-17 19:05:21 +00004927/// \return true if some promotion happened, false otherwise.
Jun Bum Lim42301012017-03-17 19:05:21 +00004928bool CodeGenPrepare::tryToPromoteExts(
4929 TypePromotionTransaction &TPT, const SmallVectorImpl<Instruction *> &Exts,
4930 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
4931 unsigned CreatedInstsCost) {
4932 bool Promoted = false;
4933
4934 // Iterate over all the extensions to try to promote them.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004935 for (auto I : Exts) {
Jun Bum Lim42301012017-03-17 19:05:21 +00004936 // Early check if we directly have ext(load).
4937 if (isa<LoadInst>(I->getOperand(0))) {
4938 ProfitablyMovedExts.push_back(I);
4939 continue;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004940 }
Jun Bum Lim42301012017-03-17 19:05:21 +00004941
4942 // Check whether or not we want to do any promotion. The reason we have
4943 // this check inside the for loop is to catch the case where an extension
4944 // is directly fed by a load because in such case the extension can be moved
4945 // up without any promotion on its operands.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004946 if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
Jun Bum Lim42301012017-03-17 19:05:21 +00004947 return false;
4948
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004949 // Get the action to perform the promotion.
Jun Bum Lim42301012017-03-17 19:05:21 +00004950 TypePromotionHelper::Action TPH =
4951 TypePromotionHelper::getAction(I, InsertedInsts, *TLI, PromotedInsts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004952 // Check if we can promote.
Jun Bum Lim42301012017-03-17 19:05:21 +00004953 if (!TPH) {
4954 // Save the current extension as we cannot move up through its operand.
4955 ProfitablyMovedExts.push_back(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004956 continue;
Jun Bum Lim42301012017-03-17 19:05:21 +00004957 }
4958
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004959 // Save the current state.
4960 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4961 TPT.getRestorationPoint();
4962 SmallVector<Instruction *, 4> NewExts;
Quentin Colombet1b274f92015-03-10 21:48:15 +00004963 unsigned NewCreatedInstsCost = 0;
4964 unsigned ExtCost = !TLI->isExtFree(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004965 // Promote.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004966 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
4967 &NewExts, nullptr, *TLI);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004968 assert(PromotedVal &&
4969 "TypePromotionHelper should have filtered out those cases");
4970
4971 // We would be able to merge only one extension in a load.
4972 // Therefore, if we have more than 1 new extension we heuristically
4973 // cut this search path, because it means we degrade the code quality.
4974 // With exactly 2, the transformation is neutral, because we will merge
4975 // one extension but leave one. However, we optimistically keep going,
4976 // because the new extension may be removed too.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004977 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
Jun Bum Limb99a06b2017-01-27 17:16:37 +00004978 // FIXME: It would be possible to propagate a negative value instead of
Jun Bum Lim42301012017-03-17 19:05:21 +00004979 // conservatively ceiling it to 0.
Jun Bum Limb99a06b2017-01-27 17:16:37 +00004980 TotalCreatedInstsCost =
4981 std::max((long long)0, (TotalCreatedInstsCost - ExtCost));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004982 if (!StressExtLdPromotion &&
Quentin Colombet1b274f92015-03-10 21:48:15 +00004983 (TotalCreatedInstsCost > 1 ||
Mehdi Amini44ede332015-07-09 02:09:04 +00004984 !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
Jun Bum Lim42301012017-03-17 19:05:21 +00004985 // This promotion is not profitable, rollback to the previous state, and
4986 // save the current extension in ProfitablyMovedExts as the latest
4987 // speculative promotion turned out to be unprofitable.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004988 TPT.rollback(LastKnownGood);
Jun Bum Lim42301012017-03-17 19:05:21 +00004989 ProfitablyMovedExts.push_back(I);
4990 continue;
4991 }
4992 // Continue promoting NewExts as far as doing so is profitable.
4993 SmallVector<Instruction *, 2> NewlyMovedExts;
4994 (void)tryToPromoteExts(TPT, NewExts, NewlyMovedExts, TotalCreatedInstsCost);
4995 bool NewPromoted = false;
4996 for (auto ExtInst : NewlyMovedExts) {
4997 Instruction *MovedExt = cast<Instruction>(ExtInst);
4998 Value *ExtOperand = MovedExt->getOperand(0);
4999 // If we have reached to a load, we need this extra profitability check
5000 // as it could potentially be merged into an ext(load).
5001 if (isa<LoadInst>(ExtOperand) &&
5002 !(StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
5003 (ExtOperand->hasOneUse() || hasSameExtUse(ExtOperand, *TLI))))
5004 continue;
5005
5006 ProfitablyMovedExts.push_back(MovedExt);
5007 NewPromoted = true;
5008 }
5009
5010 // If none of speculative promotions for NewExts is profitable, rollback
5011 // and save the current extension (I) as the last profitable extension.
5012 if (!NewPromoted) {
5013 TPT.rollback(LastKnownGood);
5014 ProfitablyMovedExts.push_back(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005015 continue;
5016 }
5017 // The promotion is profitable.
Jun Bum Lim42301012017-03-17 19:05:21 +00005018 Promoted = true;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005019 }
Jun Bum Lim42301012017-03-17 19:05:21 +00005020 return Promoted;
5021}
5022
Jun Bum Limdee55652017-04-03 19:20:07 +00005023/// Merging redundant sexts when one is dominating the other.
5024bool CodeGenPrepare::mergeSExts(Function &F) {
5025 DominatorTree DT(F);
5026 bool Changed = false;
5027 for (auto &Entry : ValToSExtendedUses) {
5028 SExts &Insts = Entry.second;
5029 SExts CurPts;
5030 for (Instruction *Inst : Insts) {
5031 if (RemovedInsts.count(Inst) || !isa<SExtInst>(Inst) ||
5032 Inst->getOperand(0) != Entry.first)
5033 continue;
5034 bool inserted = false;
5035 for (auto &Pt : CurPts) {
5036 if (DT.dominates(Inst, Pt)) {
5037 Pt->replaceAllUsesWith(Inst);
5038 RemovedInsts.insert(Pt);
5039 Pt->removeFromParent();
5040 Pt = Inst;
5041 inserted = true;
5042 Changed = true;
5043 break;
5044 }
5045 if (!DT.dominates(Pt, Inst))
5046 // Give up if we need to merge in a common dominator as the
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00005047 // experiments show it is not profitable.
Jun Bum Limdee55652017-04-03 19:20:07 +00005048 continue;
5049 Inst->replaceAllUsesWith(Pt);
5050 RemovedInsts.insert(Inst);
5051 Inst->removeFromParent();
5052 inserted = true;
5053 Changed = true;
5054 break;
5055 }
5056 if (!inserted)
5057 CurPts.push_back(Inst);
5058 }
5059 }
5060 return Changed;
5061}
5062
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00005063// Spliting large data structures so that the GEPs accessing them can have
5064// smaller offsets so that they can be sunk to the same blocks as their users.
5065// For example, a large struct starting from %base is splitted into two parts
5066// where the second part starts from %new_base.
5067//
5068// Before:
5069// BB0:
5070// %base =
5071//
5072// BB1:
5073// %gep0 = gep %base, off0
5074// %gep1 = gep %base, off1
5075// %gep2 = gep %base, off2
5076//
5077// BB2:
5078// %load1 = load %gep0
5079// %load2 = load %gep1
5080// %load3 = load %gep2
5081//
5082// After:
5083// BB0:
5084// %base =
5085// %new_base = gep %base, off0
5086//
5087// BB1:
5088// %new_gep0 = %new_base
5089// %new_gep1 = gep %new_base, off1 - off0
5090// %new_gep2 = gep %new_base, off2 - off0
5091//
5092// BB2:
5093// %load1 = load i32, i32* %new_gep0
5094// %load2 = load i32, i32* %new_gep1
5095// %load3 = load i32, i32* %new_gep2
5096//
5097// %new_gep1 and %new_gep2 can be sunk to BB2 now after the splitting because
5098// their offsets are smaller enough to fit into the addressing mode.
5099bool CodeGenPrepare::splitLargeGEPOffsets() {
5100 bool Changed = false;
5101 for (auto &Entry : LargeOffsetGEPMap) {
5102 Value *OldBase = Entry.first;
5103 SmallVectorImpl<std::pair<AssertingVH<GetElementPtrInst>, int64_t>>
5104 &LargeOffsetGEPs = Entry.second;
5105 auto compareGEPOffset =
5106 [&](const std::pair<GetElementPtrInst *, int64_t> &LHS,
5107 const std::pair<GetElementPtrInst *, int64_t> &RHS) {
5108 if (LHS.first == RHS.first)
5109 return false;
5110 if (LHS.second != RHS.second)
5111 return LHS.second < RHS.second;
5112 return LargeOffsetGEPID[LHS.first] < LargeOffsetGEPID[RHS.first];
5113 };
5114 // Sorting all the GEPs of the same data structures based on the offsets.
Fangrui Song0cac7262018-09-27 02:13:45 +00005115 llvm::sort(LargeOffsetGEPs, compareGEPOffset);
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00005116 LargeOffsetGEPs.erase(
5117 std::unique(LargeOffsetGEPs.begin(), LargeOffsetGEPs.end()),
5118 LargeOffsetGEPs.end());
5119 // Skip if all the GEPs have the same offsets.
5120 if (LargeOffsetGEPs.front().second == LargeOffsetGEPs.back().second)
5121 continue;
5122 GetElementPtrInst *BaseGEP = LargeOffsetGEPs.begin()->first;
5123 int64_t BaseOffset = LargeOffsetGEPs.begin()->second;
5124 Value *NewBaseGEP = nullptr;
5125
5126 auto LargeOffsetGEP = LargeOffsetGEPs.begin();
5127 while (LargeOffsetGEP != LargeOffsetGEPs.end()) {
5128 GetElementPtrInst *GEP = LargeOffsetGEP->first;
5129 int64_t Offset = LargeOffsetGEP->second;
5130 if (Offset != BaseOffset) {
5131 TargetLowering::AddrMode AddrMode;
5132 AddrMode.BaseOffs = Offset - BaseOffset;
5133 // The result type of the GEP might not be the type of the memory
5134 // access.
5135 if (!TLI->isLegalAddressingMode(*DL, AddrMode,
5136 GEP->getResultElementType(),
5137 GEP->getAddressSpace())) {
5138 // We need to create a new base if the offset to the current base is
5139 // too large to fit into the addressing mode. So, a very large struct
5140 // may be splitted into several parts.
5141 BaseGEP = GEP;
5142 BaseOffset = Offset;
5143 NewBaseGEP = nullptr;
5144 }
5145 }
5146
5147 // Generate a new GEP to replace the current one.
5148 IRBuilder<> Builder(GEP);
5149 Type *IntPtrTy = DL->getIntPtrType(GEP->getType());
5150 Type *I8PtrTy =
5151 Builder.getInt8PtrTy(GEP->getType()->getPointerAddressSpace());
5152 Type *I8Ty = Builder.getInt8Ty();
5153
5154 if (!NewBaseGEP) {
5155 // Create a new base if we don't have one yet. Find the insertion
5156 // pointer for the new base first.
5157 BasicBlock::iterator NewBaseInsertPt;
5158 BasicBlock *NewBaseInsertBB;
5159 if (auto *BaseI = dyn_cast<Instruction>(OldBase)) {
5160 // If the base of the struct is an instruction, the new base will be
5161 // inserted close to it.
5162 NewBaseInsertBB = BaseI->getParent();
5163 if (isa<PHINode>(BaseI))
5164 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
5165 else if (InvokeInst *Invoke = dyn_cast<InvokeInst>(BaseI)) {
5166 NewBaseInsertBB =
5167 SplitEdge(NewBaseInsertBB, Invoke->getNormalDest());
5168 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
5169 } else
5170 NewBaseInsertPt = std::next(BaseI->getIterator());
5171 } else {
5172 // If the current base is an argument or global value, the new base
5173 // will be inserted to the entry block.
5174 NewBaseInsertBB = &BaseGEP->getFunction()->getEntryBlock();
5175 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
5176 }
5177 IRBuilder<> NewBaseBuilder(NewBaseInsertBB, NewBaseInsertPt);
5178 // Create a new base.
5179 Value *BaseIndex = ConstantInt::get(IntPtrTy, BaseOffset);
5180 NewBaseGEP = OldBase;
5181 if (NewBaseGEP->getType() != I8PtrTy)
5182 NewBaseGEP = NewBaseBuilder.CreatePointerCast(NewBaseGEP, I8PtrTy);
5183 NewBaseGEP =
5184 NewBaseBuilder.CreateGEP(I8Ty, NewBaseGEP, BaseIndex, "splitgep");
5185 NewGEPBases.insert(NewBaseGEP);
5186 }
5187
5188 Value *NewGEP = NewBaseGEP;
5189 if (Offset == BaseOffset) {
5190 if (GEP->getType() != I8PtrTy)
5191 NewGEP = Builder.CreatePointerCast(NewGEP, GEP->getType());
5192 } else {
5193 // Calculate the new offset for the new GEP.
5194 Value *Index = ConstantInt::get(IntPtrTy, Offset - BaseOffset);
5195 NewGEP = Builder.CreateGEP(I8Ty, NewBaseGEP, Index);
5196
5197 if (GEP->getType() != I8PtrTy)
5198 NewGEP = Builder.CreatePointerCast(NewGEP, GEP->getType());
5199 }
5200 GEP->replaceAllUsesWith(NewGEP);
5201 LargeOffsetGEPID.erase(GEP);
5202 LargeOffsetGEP = LargeOffsetGEPs.erase(LargeOffsetGEP);
5203 GEP->eraseFromParent();
5204 Changed = true;
5205 }
5206 }
5207 return Changed;
5208}
5209
Jun Bum Lim42301012017-03-17 19:05:21 +00005210/// Return true, if an ext(load) can be formed from an extension in
5211/// \p MovedExts.
5212bool CodeGenPrepare::canFormExtLd(
5213 const SmallVectorImpl<Instruction *> &MovedExts, LoadInst *&LI,
5214 Instruction *&Inst, bool HasPromoted) {
5215 for (auto *MovedExtInst : MovedExts) {
5216 if (isa<LoadInst>(MovedExtInst->getOperand(0))) {
5217 LI = cast<LoadInst>(MovedExtInst->getOperand(0));
5218 Inst = MovedExtInst;
5219 break;
5220 }
5221 }
5222 if (!LI)
5223 return false;
5224
5225 // If they're already in the same block, there's nothing to do.
5226 // Make the cheap checks first if we did not promote.
5227 // If we promoted, we need to check if it is indeed profitable.
5228 if (!HasPromoted && LI->getParent() == Inst->getParent())
5229 return false;
5230
Haicheng Wuabdef9e2017-07-15 02:12:16 +00005231 return TLI->isExtLoad(LI, Inst, *DL);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005232}
5233
Sanjay Patel4ac6b112015-09-21 22:47:23 +00005234/// Move a zext or sext fed by a load into the same basic block as the load,
5235/// unless conditions are unfavorable. This allows SelectionDAG to fold the
5236/// extend into the load.
Dan Gohman99429a02009-10-16 20:59:35 +00005237///
Jun Bum Limdee55652017-04-03 19:20:07 +00005238/// E.g.,
5239/// \code
5240/// %ld = load i32* %addr
5241/// %add = add nuw i32 %ld, 4
5242/// %zext = zext i32 %add to i64
5243// \endcode
5244/// =>
5245/// \code
5246/// %ld = load i32* %addr
5247/// %zext = zext i32 %ld to i64
5248/// %add = add nuw i64 %zext, 4
5249/// \encode
5250/// Note that the promotion in %add to i64 is done in tryToPromoteExts(), which
5251/// allow us to match zext(load i32*) to i64.
5252///
5253/// Also, try to promote the computations used to obtain a sign extended
5254/// value used into memory accesses.
5255/// E.g.,
5256/// \code
5257/// a = add nsw i32 b, 3
5258/// d = sext i32 a to i64
5259/// e = getelementptr ..., i64 d
5260/// \endcode
5261/// =>
5262/// \code
5263/// f = sext i32 b to i64
5264/// a = add nsw i64 f, 3
5265/// e = getelementptr ..., i64 a
5266/// \endcode
5267///
5268/// \p Inst[in/out] the extension may be modified during the process if some
5269/// promotions apply.
5270bool CodeGenPrepare::optimizeExt(Instruction *&Inst) {
5271 // ExtLoad formation and address type promotion infrastructure requires TLI to
5272 // be effective.
Chandler Carruth0f139b42016-11-04 06:54:00 +00005273 if (!TLI)
5274 return false;
5275
Jun Bum Limdee55652017-04-03 19:20:07 +00005276 bool AllowPromotionWithoutCommonHeader = false;
5277 /// See if it is an interesting sext operations for the address type
5278 /// promotion before trying to promote it, e.g., the ones with the right
5279 /// type and used in memory accesses.
5280 bool ATPConsiderable = TTI->shouldConsiderAddressTypePromotion(
5281 *Inst, AllowPromotionWithoutCommonHeader);
5282 TypePromotionTransaction TPT(RemovedInsts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005283 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
Jun Bum Lim42301012017-03-17 19:05:21 +00005284 TPT.getRestorationPoint();
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005285 SmallVector<Instruction *, 1> Exts;
Jun Bum Limdee55652017-04-03 19:20:07 +00005286 SmallVector<Instruction *, 2> SpeculativelyMovedExts;
5287 Exts.push_back(Inst);
Jun Bum Lim42301012017-03-17 19:05:21 +00005288
Jun Bum Limdee55652017-04-03 19:20:07 +00005289 bool HasPromoted = tryToPromoteExts(TPT, Exts, SpeculativelyMovedExts);
Jun Bum Lim42301012017-03-17 19:05:21 +00005290
Dan Gohman99429a02009-10-16 20:59:35 +00005291 // Look for a load being extended.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005292 LoadInst *LI = nullptr;
Jun Bum Limdee55652017-04-03 19:20:07 +00005293 Instruction *ExtFedByLoad;
5294
5295 // Try to promote a chain of computation if it allows to form an extended
5296 // load.
5297 if (canFormExtLd(SpeculativelyMovedExts, LI, ExtFedByLoad, HasPromoted)) {
5298 assert(LI && ExtFedByLoad && "Expect a valid load and extension");
5299 TPT.commit();
5300 // Move the extend into the same block as the load
Sanjay Patel674d2c22017-08-29 14:07:48 +00005301 ExtFedByLoad->moveAfter(LI);
Jun Bum Limdee55652017-04-03 19:20:07 +00005302 // CGP does not check if the zext would be speculatively executed when moved
5303 // to the same basic block as the load. Preserving its original location
5304 // would pessimize the debugging experience, as well as negatively impact
5305 // the quality of sample pgo. We don't want to use "line 0" as that has a
5306 // size cost in the line-table section and logically the zext can be seen as
5307 // part of the load. Therefore we conservatively reuse the same debug
5308 // location for the load and the zext.
5309 ExtFedByLoad->setDebugLoc(LI->getDebugLoc());
5310 ++NumExtsMoved;
5311 Inst = ExtFedByLoad;
5312 return true;
5313 }
5314
5315 // Continue promoting SExts if known as considerable depending on targets.
5316 if (ATPConsiderable &&
5317 performAddressTypePromotion(Inst, AllowPromotionWithoutCommonHeader,
5318 HasPromoted, TPT, SpeculativelyMovedExts))
5319 return true;
5320
5321 TPT.rollback(LastKnownGood);
5322 return false;
5323}
5324
5325// Perform address type promotion if doing so is profitable.
5326// If AllowPromotionWithoutCommonHeader == false, we should find other sext
5327// instructions that sign extended the same initial value. However, if
5328// AllowPromotionWithoutCommonHeader == true, we expect promoting the
5329// extension is just profitable.
5330bool CodeGenPrepare::performAddressTypePromotion(
5331 Instruction *&Inst, bool AllowPromotionWithoutCommonHeader,
5332 bool HasPromoted, TypePromotionTransaction &TPT,
5333 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts) {
5334 bool Promoted = false;
5335 SmallPtrSet<Instruction *, 1> UnhandledExts;
5336 bool AllSeenFirst = true;
5337 for (auto I : SpeculativelyMovedExts) {
5338 Value *HeadOfChain = I->getOperand(0);
5339 DenseMap<Value *, Instruction *>::iterator AlreadySeen =
5340 SeenChainsForSExt.find(HeadOfChain);
5341 // If there is an unhandled SExt which has the same header, try to promote
5342 // it as well.
5343 if (AlreadySeen != SeenChainsForSExt.end()) {
5344 if (AlreadySeen->second != nullptr)
5345 UnhandledExts.insert(AlreadySeen->second);
5346 AllSeenFirst = false;
5347 }
5348 }
5349
5350 if (!AllSeenFirst || (AllowPromotionWithoutCommonHeader &&
5351 SpeculativelyMovedExts.size() == 1)) {
5352 TPT.commit();
5353 if (HasPromoted)
5354 Promoted = true;
5355 for (auto I : SpeculativelyMovedExts) {
5356 Value *HeadOfChain = I->getOperand(0);
5357 SeenChainsForSExt[HeadOfChain] = nullptr;
5358 ValToSExtendedUses[HeadOfChain].push_back(I);
5359 }
5360 // Update Inst as promotion happen.
5361 Inst = SpeculativelyMovedExts.pop_back_val();
5362 } else {
5363 // This is the first chain visited from the header, keep the current chain
5364 // as unhandled. Defer to promote this until we encounter another SExt
5365 // chain derived from the same header.
5366 for (auto I : SpeculativelyMovedExts) {
5367 Value *HeadOfChain = I->getOperand(0);
5368 SeenChainsForSExt[HeadOfChain] = Inst;
5369 }
Dan Gohman99429a02009-10-16 20:59:35 +00005370 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005371 }
Dan Gohman99429a02009-10-16 20:59:35 +00005372
Jun Bum Limdee55652017-04-03 19:20:07 +00005373 if (!AllSeenFirst && !UnhandledExts.empty())
5374 for (auto VisitedSExt : UnhandledExts) {
5375 if (RemovedInsts.count(VisitedSExt))
5376 continue;
5377 TypePromotionTransaction TPT(RemovedInsts);
5378 SmallVector<Instruction *, 1> Exts;
5379 SmallVector<Instruction *, 2> Chains;
5380 Exts.push_back(VisitedSExt);
5381 bool HasPromoted = tryToPromoteExts(TPT, Exts, Chains);
5382 TPT.commit();
5383 if (HasPromoted)
5384 Promoted = true;
5385 for (auto I : Chains) {
5386 Value *HeadOfChain = I->getOperand(0);
5387 // Mark this as handled.
5388 SeenChainsForSExt[HeadOfChain] = nullptr;
5389 ValToSExtendedUses[HeadOfChain].push_back(I);
5390 }
5391 }
5392 return Promoted;
Dan Gohman99429a02009-10-16 20:59:35 +00005393}
5394
Sanjay Patelfc580a62015-09-21 23:03:16 +00005395bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
Evan Chengd3d80172007-12-05 23:58:20 +00005396 BasicBlock *DefBB = I->getParent();
5397
Bob Wilsonff714f92010-09-21 21:44:14 +00005398 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengd3d80172007-12-05 23:58:20 +00005399 // other uses of the source with result of extension.
5400 Value *Src = I->getOperand(0);
5401 if (Src->hasOneUse())
5402 return false;
5403
Evan Cheng2011df42007-12-13 07:50:36 +00005404 // Only do this xform if truncating is free.
Gabor Greifaa261722008-02-26 19:13:21 +00005405 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Cheng37c36ed2007-12-13 03:32:53 +00005406 return false;
5407
Evan Cheng7bc89422007-12-12 00:51:06 +00005408 // Only safe to perform the optimization if the source is also defined in
Evan Cheng63d33cf2007-12-12 02:53:41 +00005409 // this block.
5410 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng7bc89422007-12-12 00:51:06 +00005411 return false;
5412
Evan Chengd3d80172007-12-05 23:58:20 +00005413 bool DefIsLiveOut = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00005414 for (User *U : I->users()) {
5415 Instruction *UI = cast<Instruction>(U);
Evan Chengd3d80172007-12-05 23:58:20 +00005416
5417 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005418 BasicBlock *UserBB = UI->getParent();
Evan Chengd3d80172007-12-05 23:58:20 +00005419 if (UserBB == DefBB) continue;
5420 DefIsLiveOut = true;
5421 break;
5422 }
5423 if (!DefIsLiveOut)
5424 return false;
5425
Jim Grosbach0f38c1e2013-04-15 17:40:48 +00005426 // Make sure none of the uses are PHI nodes.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005427 for (User *U : Src->users()) {
5428 Instruction *UI = cast<Instruction>(U);
5429 BasicBlock *UserBB = UI->getParent();
Evan Cheng37c36ed2007-12-13 03:32:53 +00005430 if (UserBB == DefBB) continue;
5431 // Be conservative. We don't want this xform to end up introducing
5432 // reloads just before load / store instructions.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005433 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
Evan Cheng63d33cf2007-12-12 02:53:41 +00005434 return false;
5435 }
5436
Evan Chengd3d80172007-12-05 23:58:20 +00005437 // InsertedTruncs - Only insert one trunc in each block once.
5438 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
5439
5440 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00005441 for (Use &U : Src->uses()) {
5442 Instruction *User = cast<Instruction>(U.getUser());
Evan Chengd3d80172007-12-05 23:58:20 +00005443
5444 // Figure out which BB this ext is used in.
5445 BasicBlock *UserBB = User->getParent();
5446 if (UserBB == DefBB) continue;
5447
5448 // Both src and def are live in this block. Rewrite the use.
5449 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
5450
5451 if (!InsertedTrunc) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00005452 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005453 assert(InsertPt != UserBB->end());
5454 InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00005455 InsertedInsts.insert(InsertedTrunc);
Evan Chengd3d80172007-12-05 23:58:20 +00005456 }
5457
5458 // Replace a use of the {s|z}ext source with a use of the result.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005459 U = InsertedTrunc;
Cameron Zwarichced753f2011-01-05 17:27:27 +00005460 ++NumExtUses;
Evan Chengd3d80172007-12-05 23:58:20 +00005461 MadeChange = true;
5462 }
5463
5464 return MadeChange;
5465}
5466
Geoff Berry5256fca2015-11-20 22:34:39 +00005467// Find loads whose uses only use some of the loaded value's bits. Add an "and"
5468// just after the load if the target can fold this into one extload instruction,
5469// with the hope of eliminating some of the other later "and" instructions using
5470// the loaded value. "and"s that are made trivially redundant by the insertion
5471// of the new "and" are removed by this function, while others (e.g. those whose
5472// path from the load goes through a phi) are left for isel to potentially
5473// remove.
5474//
5475// For example:
5476//
5477// b0:
5478// x = load i32
5479// ...
5480// b1:
5481// y = and x, 0xff
5482// z = use y
5483//
5484// becomes:
5485//
5486// b0:
5487// x = load i32
5488// x' = and x, 0xff
5489// ...
5490// b1:
5491// z = use x'
5492//
5493// whereas:
5494//
5495// b0:
5496// x1 = load i32
5497// ...
5498// b1:
5499// x2 = load i32
5500// ...
5501// b2:
5502// x = phi x1, x2
5503// y = and x, 0xff
5504//
5505// becomes (after a call to optimizeLoadExt for each load):
5506//
5507// b0:
5508// x1 = load i32
5509// x1' = and x1, 0xff
5510// ...
5511// b1:
5512// x2 = load i32
5513// x2' = and x2, 0xff
5514// ...
5515// b2:
5516// x = phi x1', x2'
5517// y = and x, 0xff
Geoff Berry5256fca2015-11-20 22:34:39 +00005518bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
Vedant Kumarb3091da2018-07-06 20:17:42 +00005519 if (!Load->isSimple() || !Load->getType()->isIntOrPtrTy())
Geoff Berry5256fca2015-11-20 22:34:39 +00005520 return false;
5521
Geoff Berry5d534b62017-02-21 18:53:14 +00005522 // Skip loads we've already transformed.
5523 if (Load->hasOneUse() &&
5524 InsertedInsts.count(cast<Instruction>(*Load->user_begin())))
5525 return false;
Geoff Berry5256fca2015-11-20 22:34:39 +00005526
5527 // Look at all uses of Load, looking through phis, to determine how many bits
5528 // of the loaded value are needed.
5529 SmallVector<Instruction *, 8> WorkList;
5530 SmallPtrSet<Instruction *, 16> Visited;
5531 SmallVector<Instruction *, 8> AndsToMaybeRemove;
5532 for (auto *U : Load->users())
5533 WorkList.push_back(cast<Instruction>(U));
5534
5535 EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
5536 unsigned BitWidth = LoadResultVT.getSizeInBits();
5537 APInt DemandBits(BitWidth, 0);
5538 APInt WidestAndBits(BitWidth, 0);
5539
5540 while (!WorkList.empty()) {
5541 Instruction *I = WorkList.back();
5542 WorkList.pop_back();
5543
5544 // Break use-def graph loops.
5545 if (!Visited.insert(I).second)
5546 continue;
5547
5548 // For a PHI node, push all of its users.
5549 if (auto *Phi = dyn_cast<PHINode>(I)) {
5550 for (auto *U : Phi->users())
5551 WorkList.push_back(cast<Instruction>(U));
5552 continue;
5553 }
5554
5555 switch (I->getOpcode()) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00005556 case Instruction::And: {
Geoff Berry5256fca2015-11-20 22:34:39 +00005557 auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
5558 if (!AndC)
5559 return false;
5560 APInt AndBits = AndC->getValue();
5561 DemandBits |= AndBits;
5562 // Keep track of the widest and mask we see.
5563 if (AndBits.ugt(WidestAndBits))
5564 WidestAndBits = AndBits;
5565 if (AndBits == WidestAndBits && I->getOperand(0) == Load)
5566 AndsToMaybeRemove.push_back(I);
5567 break;
5568 }
5569
Eugene Zelenko900b6332017-08-29 22:32:07 +00005570 case Instruction::Shl: {
Geoff Berry5256fca2015-11-20 22:34:39 +00005571 auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
5572 if (!ShlC)
5573 return false;
5574 uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
Craig Topperfc947bc2017-04-18 17:14:21 +00005575 DemandBits.setLowBits(BitWidth - ShiftAmt);
Geoff Berry5256fca2015-11-20 22:34:39 +00005576 break;
5577 }
5578
Eugene Zelenko900b6332017-08-29 22:32:07 +00005579 case Instruction::Trunc: {
Geoff Berry5256fca2015-11-20 22:34:39 +00005580 EVT TruncVT = TLI->getValueType(*DL, I->getType());
5581 unsigned TruncBitWidth = TruncVT.getSizeInBits();
Craig Topperfc947bc2017-04-18 17:14:21 +00005582 DemandBits.setLowBits(TruncBitWidth);
Geoff Berry5256fca2015-11-20 22:34:39 +00005583 break;
5584 }
5585
5586 default:
5587 return false;
5588 }
5589 }
5590
5591 uint32_t ActiveBits = DemandBits.getActiveBits();
5592 // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
5593 // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example,
5594 // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but
5595 // (and (load x) 1) is not matched as a single instruction, rather as a LDR
5596 // followed by an AND.
5597 // TODO: Look into removing this restriction by fixing backends to either
5598 // return false for isLoadExtLegal for i1 or have them select this pattern to
5599 // a single instruction.
5600 //
5601 // Also avoid hoisting if we didn't see any ands with the exact DemandBits
5602 // mask, since these are the only ands that will be removed by isel.
Craig Topperd33ee1b2017-04-03 16:34:59 +00005603 if (ActiveBits <= 1 || !DemandBits.isMask(ActiveBits) ||
Geoff Berry5256fca2015-11-20 22:34:39 +00005604 WidestAndBits != DemandBits)
5605 return false;
5606
5607 LLVMContext &Ctx = Load->getType()->getContext();
5608 Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
5609 EVT TruncVT = TLI->getValueType(*DL, TruncTy);
5610
5611 // Reject cases that won't be matched as extloads.
5612 if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
5613 !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT))
5614 return false;
5615
5616 IRBuilder<> Builder(Load->getNextNode());
5617 auto *NewAnd = dyn_cast<Instruction>(
5618 Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
Geoff Berry5d534b62017-02-21 18:53:14 +00005619 // Mark this instruction as "inserted by CGP", so that other
5620 // optimizations don't touch it.
5621 InsertedInsts.insert(NewAnd);
Geoff Berry5256fca2015-11-20 22:34:39 +00005622
5623 // Replace all uses of load with new and (except for the use of load in the
5624 // new and itself).
5625 Load->replaceAllUsesWith(NewAnd);
5626 NewAnd->setOperand(0, Load);
5627
5628 // Remove any and instructions that are now redundant.
5629 for (auto *And : AndsToMaybeRemove)
5630 // Check that the and mask is the same as the one we decided to put on the
5631 // new and.
5632 if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
5633 And->replaceAllUsesWith(NewAnd);
5634 if (&*CurInstIterator == And)
5635 CurInstIterator = std::next(And->getIterator());
5636 And->eraseFromParent();
5637 ++NumAndUses;
5638 }
5639
5640 ++NumAndsAdded;
5641 return true;
5642}
5643
Sanjay Patel69a50a12015-10-19 21:59:12 +00005644/// Check if V (an operand of a select instruction) is an expensive instruction
5645/// that is only used once.
5646static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
5647 auto *I = dyn_cast<Instruction>(V);
5648 // If it's safe to speculatively execute, then it should not have side
5649 // effects; therefore, it's safe to sink and possibly *not* execute.
Rafael Espindola84921b92015-10-24 23:11:13 +00005650 return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
5651 TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005652}
5653
Sanjay Patel4ac6b112015-09-21 22:47:23 +00005654/// Returns true if a SelectInst should be turned into an explicit branch.
Sanjay Patel69a50a12015-10-19 21:59:12 +00005655static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
Sanjay Pateld66607b2016-04-26 17:11:17 +00005656 const TargetLowering *TLI,
Sanjay Patel69a50a12015-10-19 21:59:12 +00005657 SelectInst *SI) {
Sanjay Pateld66607b2016-04-26 17:11:17 +00005658 // If even a predictable select is cheap, then a branch can't be cheaper.
5659 if (!TLI->isPredictableSelectExpensive())
5660 return false;
5661
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005662 // FIXME: This should use the same heuristics as IfConversion to determine
Sanjay Pateld66607b2016-04-26 17:11:17 +00005663 // whether a select is better represented as a branch.
5664
5665 // If metadata tells us that the select condition is obviously predictable,
5666 // then we want to replace the select with a branch.
5667 uint64_t TrueWeight, FalseWeight;
5668 if (SI->extractProfMetadata(TrueWeight, FalseWeight)) {
5669 uint64_t Max = std::max(TrueWeight, FalseWeight);
5670 uint64_t Sum = TrueWeight + FalseWeight;
Sanjay Patelc7b91e62016-05-09 17:31:55 +00005671 if (Sum != 0) {
5672 auto Probability = BranchProbability::getBranchProbability(Max, Sum);
5673 if (Probability > TLI->getPredictableBranchThreshold())
5674 return true;
5675 }
Sanjay Pateld66607b2016-04-26 17:11:17 +00005676 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005677
5678 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
5679
Sanjay Patel4e652762015-09-28 22:14:51 +00005680 // If a branch is predictable, an out-of-order CPU can avoid blocking on its
5681 // comparison condition. If the compare has more than one use, there's
5682 // probably another cmov or setcc around, so it's not worth emitting a branch.
Sanjay Patel5e5f0e92015-09-28 21:44:46 +00005683 if (!Cmp || !Cmp->hasOneUse())
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005684 return false;
5685
Sanjay Patel69a50a12015-10-19 21:59:12 +00005686 // If either operand of the select is expensive and only needed on one side
5687 // of the select, we should form a branch.
5688 if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
5689 sinkSelectOperand(TTI, SI->getFalseValue()))
5690 return true;
5691
5692 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005693}
5694
Dehao Chen9bbb9412016-09-12 20:23:28 +00005695/// If \p isTrue is true, return the true value of \p SI, otherwise return
5696/// false value of \p SI. If the true/false value of \p SI is defined by any
5697/// select instructions in \p Selects, look through the defining select
5698/// instruction until the true/false value is not defined in \p Selects.
5699static Value *getTrueOrFalseValue(
5700 SelectInst *SI, bool isTrue,
5701 const SmallPtrSet<const Instruction *, 2> &Selects) {
5702 Value *V;
5703
5704 for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI);
5705 DefSI = dyn_cast<SelectInst>(V)) {
Dehao Chenc32d7122016-09-12 20:29:54 +00005706 assert(DefSI->getCondition() == SI->getCondition() &&
Dehao Chen9bbb9412016-09-12 20:23:28 +00005707 "The condition of DefSI does not match with SI");
5708 V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
5709 }
5710 return V;
5711}
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005712
Nadav Rotem9d832022012-09-02 12:10:19 +00005713/// If we have a SelectInst that will likely profit from branch prediction,
5714/// turn it into a branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005715bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
Vedant Kumarfbc38732018-08-21 23:42:23 +00005716 // If branch conversion isn't desirable, exit early.
5717 if (DisableSelectToBranch || OptSize || !TLI)
5718 return false;
5719
Dehao Chen9bbb9412016-09-12 20:23:28 +00005720 // Find all consecutive select instructions that share the same condition.
5721 SmallVector<SelectInst *, 2> ASI;
5722 ASI.push_back(SI);
David Blaikie7d306532018-08-28 00:55:19 +00005723 for (BasicBlock::iterator It = ++BasicBlock::iterator(SI);
5724 It != SI->getParent()->end(); ++It) {
5725 SelectInst *I = dyn_cast<SelectInst>(&*It);
Dehao Chen9bbb9412016-09-12 20:23:28 +00005726 if (I && SI->getCondition() == I->getCondition()) {
5727 ASI.push_back(I);
5728 } else {
5729 break;
5730 }
5731 }
5732
5733 SelectInst *LastSI = ASI.back();
5734 // Increment the current iterator to skip all the rest of select instructions
5735 // because they will be either "not lowered" or "all lowered" to branch.
5736 CurInstIterator = std::next(LastSI->getIterator());
5737
Nadav Rotem9d832022012-09-02 12:10:19 +00005738 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
5739
5740 // Can we convert the 'select' to CF ?
Vedant Kumarfbc38732018-08-21 23:42:23 +00005741 if (VectorCond || SI->getMetadata(LLVMContext::MD_unpredictable))
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005742 return false;
5743
Nadav Rotem9d832022012-09-02 12:10:19 +00005744 TargetLowering::SelectSupportKind SelectKind;
5745 if (VectorCond)
5746 SelectKind = TargetLowering::VectorMaskSelect;
5747 else if (SI->getType()->isVectorTy())
5748 SelectKind = TargetLowering::ScalarCondVectorVal;
5749 else
5750 SelectKind = TargetLowering::ScalarValSelect;
5751
Sanjay Pateld66607b2016-04-26 17:11:17 +00005752 if (TLI->isSelectSupported(SelectKind) &&
5753 !isFormingBranchFromSelectProfitable(TTI, TLI, SI))
5754 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005755
5756 ModifiedDT = true;
5757
Sanjay Patel69a50a12015-10-19 21:59:12 +00005758 // Transform a sequence like this:
5759 // start:
5760 // %cmp = cmp uge i32 %a, %b
5761 // %sel = select i1 %cmp, i32 %c, i32 %d
5762 //
5763 // Into:
5764 // start:
5765 // %cmp = cmp uge i32 %a, %b
5766 // br i1 %cmp, label %select.true, label %select.false
5767 // select.true:
5768 // br label %select.end
5769 // select.false:
5770 // br label %select.end
5771 // select.end:
5772 // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
5773 //
5774 // In addition, we may sink instructions that produce %c or %d from
5775 // the entry block into the destination(s) of the new branch.
5776 // If the true or false blocks do not contain a sunken instruction, that
5777 // block and its branch may be optimized away. In that case, one side of the
5778 // first branch will point directly to select.end, and the corresponding PHI
5779 // predecessor block will be the start block.
5780
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005781 // First, we split the block containing the select into 2 blocks.
5782 BasicBlock *StartBlock = SI->getParent();
Dehao Chen9bbb9412016-09-12 20:23:28 +00005783 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI));
Sanjay Patel69a50a12015-10-19 21:59:12 +00005784 BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005785
Sanjay Patel69a50a12015-10-19 21:59:12 +00005786 // Delete the unconditional branch that was just created by the split.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005787 StartBlock->getTerminator()->eraseFromParent();
Sanjay Patel69a50a12015-10-19 21:59:12 +00005788
5789 // These are the new basic blocks for the conditional branch.
5790 // At least one will become an actual new basic block.
5791 BasicBlock *TrueBlock = nullptr;
5792 BasicBlock *FalseBlock = nullptr;
Dehao Chen9bbb9412016-09-12 20:23:28 +00005793 BranchInst *TrueBranch = nullptr;
5794 BranchInst *FalseBranch = nullptr;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005795
5796 // Sink expensive instructions into the conditional blocks to avoid executing
5797 // them speculatively.
Dehao Chen9bbb9412016-09-12 20:23:28 +00005798 for (SelectInst *SI : ASI) {
5799 if (sinkSelectOperand(TTI, SI->getTrueValue())) {
5800 if (TrueBlock == nullptr) {
5801 TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink",
5802 EndBlock->getParent(), EndBlock);
5803 TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
Vedant Kumar1e8a2c92018-08-22 00:10:37 +00005804 TrueBranch->setDebugLoc(SI->getDebugLoc());
Dehao Chen9bbb9412016-09-12 20:23:28 +00005805 }
5806 auto *TrueInst = cast<Instruction>(SI->getTrueValue());
5807 TrueInst->moveBefore(TrueBranch);
5808 }
5809 if (sinkSelectOperand(TTI, SI->getFalseValue())) {
5810 if (FalseBlock == nullptr) {
5811 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink",
5812 EndBlock->getParent(), EndBlock);
5813 FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
Vedant Kumar1e8a2c92018-08-22 00:10:37 +00005814 FalseBranch->setDebugLoc(SI->getDebugLoc());
Dehao Chen9bbb9412016-09-12 20:23:28 +00005815 }
5816 auto *FalseInst = cast<Instruction>(SI->getFalseValue());
5817 FalseInst->moveBefore(FalseBranch);
5818 }
Sanjay Patel69a50a12015-10-19 21:59:12 +00005819 }
5820
5821 // If there was nothing to sink, then arbitrarily choose the 'false' side
5822 // for a new input value to the PHI.
5823 if (TrueBlock == FalseBlock) {
5824 assert(TrueBlock == nullptr &&
5825 "Unexpected basic block transform while optimizing select");
5826
5827 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
5828 EndBlock->getParent(), EndBlock);
Vedant Kumar1e8a2c92018-08-22 00:10:37 +00005829 auto *FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
5830 FalseBranch->setDebugLoc(SI->getDebugLoc());
Sanjay Patel69a50a12015-10-19 21:59:12 +00005831 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005832
5833 // Insert the real conditional branch based on the original condition.
Sanjay Patel69a50a12015-10-19 21:59:12 +00005834 // If we did not create a new block for one of the 'true' or 'false' paths
5835 // of the condition, it means that side of the branch goes to the end block
5836 // directly and the path originates from the start block from the point of
5837 // view of the new PHI.
Xinliang David Li241e6c72016-09-03 21:26:36 +00005838 BasicBlock *TT, *FT;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005839 if (TrueBlock == nullptr) {
Xinliang David Li241e6c72016-09-03 21:26:36 +00005840 TT = EndBlock;
5841 FT = FalseBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005842 TrueBlock = StartBlock;
5843 } else if (FalseBlock == nullptr) {
Xinliang David Li241e6c72016-09-03 21:26:36 +00005844 TT = TrueBlock;
5845 FT = EndBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005846 FalseBlock = StartBlock;
5847 } else {
Xinliang David Li241e6c72016-09-03 21:26:36 +00005848 TT = TrueBlock;
5849 FT = FalseBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005850 }
Xinliang David Li241e6c72016-09-03 21:26:36 +00005851 IRBuilder<>(SI).CreateCondBr(SI->getCondition(), TT, FT, SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005852
Dehao Chen9bbb9412016-09-12 20:23:28 +00005853 SmallPtrSet<const Instruction *, 2> INS;
5854 INS.insert(ASI.begin(), ASI.end());
5855 // Use reverse iterator because later select may use the value of the
5856 // earlier select, and we need to propagate value through earlier select
5857 // to get the PHI operand.
5858 for (auto It = ASI.rbegin(); It != ASI.rend(); ++It) {
5859 SelectInst *SI = *It;
5860 // The select itself is replaced with a PHI Node.
5861 PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
5862 PN->takeName(SI);
5863 PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock);
5864 PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock);
Vedant Kumar1e8a2c92018-08-22 00:10:37 +00005865 PN->setDebugLoc(SI->getDebugLoc());
Sanjay Patel69a50a12015-10-19 21:59:12 +00005866
Dehao Chen9bbb9412016-09-12 20:23:28 +00005867 SI->replaceAllUsesWith(PN);
5868 SI->eraseFromParent();
5869 INS.erase(SI);
5870 ++NumSelectsExpanded;
5871 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005872
5873 // Instruct OptimizeBlock to skip to the next block.
5874 CurInstIterator = StartBlock->end();
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005875 return true;
5876}
5877
Benjamin Kramer573ff362014-03-01 17:24:40 +00005878static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00005879 SmallVector<int, 16> Mask(SVI->getShuffleMask());
5880 int SplatElem = -1;
5881 for (unsigned i = 0; i < Mask.size(); ++i) {
5882 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
5883 return false;
5884 SplatElem = Mask[i];
5885 }
5886
5887 return true;
5888}
5889
5890/// Some targets have expensive vector shifts if the lanes aren't all the same
5891/// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
5892/// it's often worth sinking a shufflevector splat down to its use so that
5893/// codegen can spot all lanes are identical.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005894bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00005895 BasicBlock *DefBB = SVI->getParent();
5896
5897 // Only do this xform if variable vector shifts are particularly expensive.
5898 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
5899 return false;
5900
5901 // We only expect better codegen by sinking a shuffle if we can recognise a
5902 // constant splat.
5903 if (!isBroadcastShuffle(SVI))
5904 return false;
5905
5906 // InsertedShuffles - Only insert a shuffle in each block once.
5907 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
5908
5909 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00005910 for (User *U : SVI->users()) {
5911 Instruction *UI = cast<Instruction>(U);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005912
5913 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005914 BasicBlock *UserBB = UI->getParent();
Tim Northoveraeb8e062014-02-19 10:02:43 +00005915 if (UserBB == DefBB) continue;
5916
5917 // For now only apply this when the splat is used by a shift instruction.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005918 if (!UI->isShift()) continue;
Tim Northoveraeb8e062014-02-19 10:02:43 +00005919
5920 // Everything checks out, sink the shuffle if the user's block doesn't
5921 // already have a copy.
5922 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
5923
5924 if (!InsertedShuffle) {
5925 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005926 assert(InsertPt != UserBB->end());
5927 InsertedShuffle =
5928 new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
5929 SVI->getOperand(2), "", &*InsertPt);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005930 }
5931
Chandler Carruthcdf47882014-03-09 03:16:01 +00005932 UI->replaceUsesOfWith(SVI, InsertedShuffle);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005933 MadeChange = true;
5934 }
5935
5936 // If we removed all uses, nuke the shuffle.
5937 if (SVI->use_empty()) {
5938 SVI->eraseFromParent();
5939 MadeChange = true;
5940 }
5941
5942 return MadeChange;
5943}
5944
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00005945bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
5946 if (!TLI || !DL)
5947 return false;
5948
5949 Value *Cond = SI->getCondition();
5950 Type *OldType = Cond->getType();
5951 LLVMContext &Context = Cond->getContext();
5952 MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType));
5953 unsigned RegWidth = RegType.getSizeInBits();
5954
5955 if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
5956 return false;
5957
5958 // If the register width is greater than the type width, expand the condition
5959 // of the switch instruction and each case constant to the width of the
5960 // register. By widening the type of the switch condition, subsequent
5961 // comparisons (for case comparisons) will not need to be extended to the
5962 // preferred register width, so we will potentially eliminate N-1 extends,
5963 // where N is the number of cases in the switch.
5964 auto *NewType = Type::getIntNTy(Context, RegWidth);
5965
5966 // Zero-extend the switch condition and case constants unless the switch
5967 // condition is a function argument that is already being sign-extended.
5968 // In that case, we can avoid an unnecessary mask/extension by sign-extending
5969 // everything instead.
5970 Instruction::CastOps ExtType = Instruction::ZExt;
5971 if (auto *Arg = dyn_cast<Argument>(Cond))
5972 if (Arg->hasSExtAttr())
5973 ExtType = Instruction::SExt;
5974
5975 auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
5976 ExtInst->insertBefore(SI);
Vedant Kumar47606862018-08-22 01:23:31 +00005977 ExtInst->setDebugLoc(SI->getDebugLoc());
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00005978 SI->setCondition(ExtInst);
Chandler Carruth927d8e62017-04-12 07:27:28 +00005979 for (auto Case : SI->cases()) {
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00005980 APInt NarrowConst = Case.getCaseValue()->getValue();
5981 APInt WideConst = (ExtType == Instruction::ZExt) ?
5982 NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth);
5983 Case.setValue(ConstantInt::get(Context, WideConst));
5984 }
5985
5986 return true;
5987}
5988
Zaara Syeda3a7578c2017-05-31 17:12:38 +00005989
Quentin Colombetc32615d2014-10-31 17:52:53 +00005990namespace {
Eugene Zelenko900b6332017-08-29 22:32:07 +00005991
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00005992/// Helper class to promote a scalar operation to a vector one.
Quentin Colombetc32615d2014-10-31 17:52:53 +00005993/// This class is used to move downward extractelement transition.
5994/// E.g.,
5995/// a = vector_op <2 x i32>
5996/// b = extractelement <2 x i32> a, i32 0
5997/// c = scalar_op b
5998/// store c
5999///
6000/// =>
6001/// a = vector_op <2 x i32>
6002/// c = vector_op a (equivalent to scalar_op on the related lane)
6003/// * d = extractelement <2 x i32> c, i32 0
6004/// * store d
6005/// Assuming both extractelement and store can be combine, we get rid of the
6006/// transition.
6007class VectorPromoteHelper {
Mehdi Amini44ede332015-07-09 02:09:04 +00006008 /// DataLayout associated with the current module.
6009 const DataLayout &DL;
6010
Quentin Colombetc32615d2014-10-31 17:52:53 +00006011 /// Used to perform some checks on the legality of vector operations.
6012 const TargetLowering &TLI;
6013
6014 /// Used to estimated the cost of the promoted chain.
6015 const TargetTransformInfo &TTI;
6016
6017 /// The transition being moved downwards.
6018 Instruction *Transition;
Eugene Zelenko900b6332017-08-29 22:32:07 +00006019
Quentin Colombetc32615d2014-10-31 17:52:53 +00006020 /// The sequence of instructions to be promoted.
6021 SmallVector<Instruction *, 4> InstsToBePromoted;
Eugene Zelenko900b6332017-08-29 22:32:07 +00006022
Quentin Colombetc32615d2014-10-31 17:52:53 +00006023 /// Cost of combining a store and an extract.
6024 unsigned StoreExtractCombineCost;
Eugene Zelenko900b6332017-08-29 22:32:07 +00006025
Quentin Colombetc32615d2014-10-31 17:52:53 +00006026 /// Instruction that will be combined with the transition.
Eugene Zelenko900b6332017-08-29 22:32:07 +00006027 Instruction *CombineInst = nullptr;
Quentin Colombetc32615d2014-10-31 17:52:53 +00006028
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006029 /// The instruction that represents the current end of the transition.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006030 /// Since we are faking the promotion until we reach the end of the chain
6031 /// of computation, we need a way to get the current end of the transition.
6032 Instruction *getEndOfTransition() const {
6033 if (InstsToBePromoted.empty())
6034 return Transition;
6035 return InstsToBePromoted.back();
6036 }
6037
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006038 /// Return the index of the original value in the transition.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006039 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
6040 /// c, is at index 0.
6041 unsigned getTransitionOriginalValueIdx() const {
6042 assert(isa<ExtractElementInst>(Transition) &&
6043 "Other kind of transitions are not supported yet");
6044 return 0;
6045 }
6046
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006047 /// Return the index of the index in the transition.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006048 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
6049 /// is at index 1.
6050 unsigned getTransitionIdx() const {
6051 assert(isa<ExtractElementInst>(Transition) &&
6052 "Other kind of transitions are not supported yet");
6053 return 1;
6054 }
6055
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006056 /// Get the type of the transition.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006057 /// This is the type of the original value.
6058 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
6059 /// transition is <2 x i32>.
6060 Type *getTransitionType() const {
6061 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
6062 }
6063
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006064 /// Promote \p ToBePromoted by moving \p Def downward through.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006065 /// I.e., we have the following sequence:
6066 /// Def = Transition <ty1> a to <ty2>
6067 /// b = ToBePromoted <ty2> Def, ...
6068 /// =>
6069 /// b = ToBePromoted <ty1> a, ...
6070 /// Def = Transition <ty1> ToBePromoted to <ty2>
6071 void promoteImpl(Instruction *ToBePromoted);
6072
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006073 /// Check whether or not it is profitable to promote all the
Quentin Colombetc32615d2014-10-31 17:52:53 +00006074 /// instructions enqueued to be promoted.
6075 bool isProfitableToPromote() {
6076 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
6077 unsigned Index = isa<ConstantInt>(ValIdx)
6078 ? cast<ConstantInt>(ValIdx)->getZExtValue()
6079 : -1;
6080 Type *PromotedType = getTransitionType();
6081
6082 StoreInst *ST = cast<StoreInst>(CombineInst);
6083 unsigned AS = ST->getPointerAddressSpace();
6084 unsigned Align = ST->getAlignment();
6085 // Check if this store is supported.
6086 if (!TLI.allowsMisalignedMemoryAccesses(
Mehdi Amini44ede332015-07-09 02:09:04 +00006087 TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
6088 Align)) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00006089 // If this is not supported, there is no way we can combine
6090 // the extract with the store.
6091 return false;
6092 }
6093
6094 // The scalar chain of computation has to pay for the transition
6095 // scalar to vector.
6096 // The vector chain has to account for the combining cost.
6097 uint64_t ScalarCost =
6098 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
6099 uint64_t VectorCost = StoreExtractCombineCost;
6100 for (const auto &Inst : InstsToBePromoted) {
6101 // Compute the cost.
6102 // By construction, all instructions being promoted are arithmetic ones.
6103 // Moreover, one argument is a constant that can be viewed as a splat
6104 // constant.
6105 Value *Arg0 = Inst->getOperand(0);
6106 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
6107 isa<ConstantFP>(Arg0);
6108 TargetTransformInfo::OperandValueKind Arg0OVK =
6109 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
6110 : TargetTransformInfo::OK_AnyValue;
6111 TargetTransformInfo::OperandValueKind Arg1OVK =
6112 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
6113 : TargetTransformInfo::OK_AnyValue;
6114 ScalarCost += TTI.getArithmeticInstrCost(
6115 Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
6116 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
6117 Arg0OVK, Arg1OVK);
6118 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006119 LLVM_DEBUG(
6120 dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
6121 << ScalarCost << "\nVector: " << VectorCost << '\n');
Quentin Colombetc32615d2014-10-31 17:52:53 +00006122 return ScalarCost > VectorCost;
6123 }
6124
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006125 /// Generate a constant vector with \p Val with the same
Quentin Colombetc32615d2014-10-31 17:52:53 +00006126 /// number of elements as the transition.
6127 /// \p UseSplat defines whether or not \p Val should be replicated
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00006128 /// across the whole vector.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006129 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
6130 /// otherwise we generate a vector with as many undef as possible:
6131 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
6132 /// used at the index of the extract.
6133 Value *getConstantVector(Constant *Val, bool UseSplat) const {
Eugene Zelenko900b6332017-08-29 22:32:07 +00006134 unsigned ExtractIdx = std::numeric_limits<unsigned>::max();
Quentin Colombetc32615d2014-10-31 17:52:53 +00006135 if (!UseSplat) {
6136 // If we cannot determine where the constant must be, we have to
6137 // use a splat constant.
6138 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
6139 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
6140 ExtractIdx = CstVal->getSExtValue();
6141 else
6142 UseSplat = true;
6143 }
6144
6145 unsigned End = getTransitionType()->getVectorNumElements();
6146 if (UseSplat)
6147 return ConstantVector::getSplat(End, Val);
6148
6149 SmallVector<Constant *, 4> ConstVec;
6150 UndefValue *UndefVal = UndefValue::get(Val->getType());
6151 for (unsigned Idx = 0; Idx != End; ++Idx) {
6152 if (Idx == ExtractIdx)
6153 ConstVec.push_back(Val);
6154 else
6155 ConstVec.push_back(UndefVal);
6156 }
6157 return ConstantVector::get(ConstVec);
6158 }
6159
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006160 /// Check if promoting to a vector type an operand at \p OperandIdx
Quentin Colombetc32615d2014-10-31 17:52:53 +00006161 /// in \p Use can trigger undefined behavior.
6162 static bool canCauseUndefinedBehavior(const Instruction *Use,
6163 unsigned OperandIdx) {
6164 // This is not safe to introduce undef when the operand is on
6165 // the right hand side of a division-like instruction.
6166 if (OperandIdx != 1)
6167 return false;
6168 switch (Use->getOpcode()) {
6169 default:
6170 return false;
6171 case Instruction::SDiv:
6172 case Instruction::UDiv:
6173 case Instruction::SRem:
6174 case Instruction::URem:
6175 return true;
6176 case Instruction::FDiv:
6177 case Instruction::FRem:
6178 return !Use->hasNoNaNs();
6179 }
6180 llvm_unreachable(nullptr);
6181 }
6182
6183public:
Mehdi Amini44ede332015-07-09 02:09:04 +00006184 VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
6185 const TargetTransformInfo &TTI, Instruction *Transition,
6186 unsigned CombineCost)
6187 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
Eugene Zelenko900b6332017-08-29 22:32:07 +00006188 StoreExtractCombineCost(CombineCost) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00006189 assert(Transition && "Do not know how to promote null");
6190 }
6191
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006192 /// Check if we can promote \p ToBePromoted to \p Type.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006193 bool canPromote(const Instruction *ToBePromoted) const {
6194 // We could support CastInst too.
6195 return isa<BinaryOperator>(ToBePromoted);
6196 }
6197
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006198 /// Check if it is profitable to promote \p ToBePromoted
Quentin Colombetc32615d2014-10-31 17:52:53 +00006199 /// by moving downward the transition through.
6200 bool shouldPromote(const Instruction *ToBePromoted) const {
6201 // Promote only if all the operands can be statically expanded.
6202 // Indeed, we do not want to introduce any new kind of transitions.
6203 for (const Use &U : ToBePromoted->operands()) {
6204 const Value *Val = U.get();
6205 if (Val == getEndOfTransition()) {
6206 // If the use is a division and the transition is on the rhs,
6207 // we cannot promote the operation, otherwise we may create a
6208 // division by zero.
6209 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
6210 return false;
6211 continue;
6212 }
6213 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
6214 !isa<ConstantFP>(Val))
6215 return false;
6216 }
6217 // Check that the resulting operation is legal.
6218 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
6219 if (!ISDOpcode)
6220 return false;
6221 return StressStoreExtract ||
Ahmed Bougacha026600d2014-11-12 23:05:03 +00006222 TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00006223 ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
Quentin Colombetc32615d2014-10-31 17:52:53 +00006224 }
6225
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006226 /// Check whether or not \p Use can be combined
Quentin Colombetc32615d2014-10-31 17:52:53 +00006227 /// with the transition.
6228 /// I.e., is it possible to do Use(Transition) => AnotherUse?
6229 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
6230
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006231 /// Record \p ToBePromoted as part of the chain to be promoted.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006232 void enqueueForPromotion(Instruction *ToBePromoted) {
6233 InstsToBePromoted.push_back(ToBePromoted);
6234 }
6235
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006236 /// Set the instruction that will be combined with the transition.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006237 void recordCombineInstruction(Instruction *ToBeCombined) {
6238 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
6239 CombineInst = ToBeCombined;
6240 }
6241
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006242 /// Promote all the instructions enqueued for promotion if it is
Quentin Colombetc32615d2014-10-31 17:52:53 +00006243 /// is profitable.
6244 /// \return True if the promotion happened, false otherwise.
6245 bool promote() {
6246 // Check if there is something to promote.
6247 // Right now, if we do not have anything to combine with,
6248 // we assume the promotion is not profitable.
6249 if (InstsToBePromoted.empty() || !CombineInst)
6250 return false;
6251
6252 // Check cost.
6253 if (!StressStoreExtract && !isProfitableToPromote())
6254 return false;
6255
6256 // Promote.
6257 for (auto &ToBePromoted : InstsToBePromoted)
6258 promoteImpl(ToBePromoted);
6259 InstsToBePromoted.clear();
6260 return true;
6261 }
6262};
Eugene Zelenko900b6332017-08-29 22:32:07 +00006263
6264} // end anonymous namespace
Quentin Colombetc32615d2014-10-31 17:52:53 +00006265
6266void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
6267 // At this point, we know that all the operands of ToBePromoted but Def
6268 // can be statically promoted.
6269 // For Def, we need to use its parameter in ToBePromoted:
6270 // b = ToBePromoted ty1 a
6271 // Def = Transition ty1 b to ty2
6272 // Move the transition down.
6273 // 1. Replace all uses of the promoted operation by the transition.
6274 // = ... b => = ... Def.
6275 assert(ToBePromoted->getType() == Transition->getType() &&
6276 "The type of the result of the transition does not match "
6277 "the final type");
6278 ToBePromoted->replaceAllUsesWith(Transition);
6279 // 2. Update the type of the uses.
6280 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
6281 Type *TransitionTy = getTransitionType();
6282 ToBePromoted->mutateType(TransitionTy);
6283 // 3. Update all the operands of the promoted operation with promoted
6284 // operands.
6285 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
6286 for (Use &U : ToBePromoted->operands()) {
6287 Value *Val = U.get();
6288 Value *NewVal = nullptr;
6289 if (Val == Transition)
6290 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
6291 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
6292 isa<ConstantFP>(Val)) {
6293 // Use a splat constant if it is not safe to use undef.
6294 NewVal = getConstantVector(
6295 cast<Constant>(Val),
6296 isa<UndefValue>(Val) ||
6297 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
6298 } else
Craig Topperd3c02f12015-01-05 10:15:49 +00006299 llvm_unreachable("Did you modified shouldPromote and forgot to update "
6300 "this?");
Quentin Colombetc32615d2014-10-31 17:52:53 +00006301 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
6302 }
Sanjay Patel674d2c22017-08-29 14:07:48 +00006303 Transition->moveAfter(ToBePromoted);
Quentin Colombetc32615d2014-10-31 17:52:53 +00006304 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
6305}
6306
6307/// Some targets can do store(extractelement) with one instruction.
6308/// Try to push the extractelement towards the stores when the target
6309/// has this feature and this is profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00006310bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00006311 unsigned CombineCost = std::numeric_limits<unsigned>::max();
Quentin Colombetc32615d2014-10-31 17:52:53 +00006312 if (DisableStoreExtract || !TLI ||
6313 (!StressStoreExtract &&
6314 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
6315 Inst->getOperand(1), CombineCost)))
6316 return false;
6317
6318 // At this point we know that Inst is a vector to scalar transition.
6319 // Try to move it down the def-use chain, until:
6320 // - We can combine the transition with its single use
6321 // => we got rid of the transition.
6322 // - We escape the current basic block
6323 // => we would need to check that we are moving it at a cheaper place and
6324 // we do not do that for now.
6325 BasicBlock *Parent = Inst->getParent();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006326 LLVM_DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
Mehdi Amini44ede332015-07-09 02:09:04 +00006327 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
Quentin Colombetc32615d2014-10-31 17:52:53 +00006328 // If the transition has more than one use, assume this is not going to be
6329 // beneficial.
6330 while (Inst->hasOneUse()) {
6331 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006332 LLVM_DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
Quentin Colombetc32615d2014-10-31 17:52:53 +00006333
6334 if (ToBePromoted->getParent() != Parent) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006335 LLVM_DEBUG(dbgs() << "Instruction to promote is in a different block ("
6336 << ToBePromoted->getParent()->getName()
6337 << ") than the transition (" << Parent->getName()
6338 << ").\n");
Quentin Colombetc32615d2014-10-31 17:52:53 +00006339 return false;
6340 }
6341
6342 if (VPH.canCombine(ToBePromoted)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006343 LLVM_DEBUG(dbgs() << "Assume " << *Inst << '\n'
6344 << "will be combined with: " << *ToBePromoted << '\n');
Quentin Colombetc32615d2014-10-31 17:52:53 +00006345 VPH.recordCombineInstruction(ToBePromoted);
6346 bool Changed = VPH.promote();
6347 NumStoreExtractExposed += Changed;
6348 return Changed;
6349 }
6350
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006351 LLVM_DEBUG(dbgs() << "Try promoting.\n");
Quentin Colombetc32615d2014-10-31 17:52:53 +00006352 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
6353 return false;
6354
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006355 LLVM_DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
Quentin Colombetc32615d2014-10-31 17:52:53 +00006356
6357 VPH.enqueueForPromotion(ToBePromoted);
6358 Inst = ToBePromoted;
6359 }
6360 return false;
6361}
6362
Wei Mia2f0b592016-12-22 19:44:45 +00006363/// For the instruction sequence of store below, F and I values
6364/// are bundled together as an i64 value before being stored into memory.
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00006365/// Sometimes it is more efficient to generate separate stores for F and I,
Wei Mia2f0b592016-12-22 19:44:45 +00006366/// which can remove the bitwise instructions or sink them to colder places.
6367///
6368/// (store (or (zext (bitcast F to i32) to i64),
6369/// (shl (zext I to i64), 32)), addr) -->
6370/// (store F, addr) and (store I, addr+4)
6371///
6372/// Similarly, splitting for other merged store can also be beneficial, like:
6373/// For pair of {i32, i32}, i64 store --> two i32 stores.
6374/// For pair of {i32, i16}, i64 store --> two i32 stores.
6375/// For pair of {i16, i16}, i32 store --> two i16 stores.
6376/// For pair of {i16, i8}, i32 store --> two i16 stores.
6377/// For pair of {i8, i8}, i16 store --> two i8 stores.
6378///
6379/// We allow each target to determine specifically which kind of splitting is
6380/// supported.
6381///
6382/// The store patterns are commonly seen from the simple code snippet below
6383/// if only std::make_pair(...) is sroa transformed before inlined into hoo.
6384/// void goo(const std::pair<int, float> &);
6385/// hoo() {
6386/// ...
6387/// goo(std::make_pair(tmp, ftmp));
6388/// ...
6389/// }
6390///
6391/// Although we already have similar splitting in DAG Combine, we duplicate
6392/// it in CodeGenPrepare to catch the case in which pattern is across
6393/// multiple BBs. The logic in DAG Combine is kept to catch case generated
6394/// during code expansion.
6395static bool splitMergedValStore(StoreInst &SI, const DataLayout &DL,
6396 const TargetLowering &TLI) {
6397 // Handle simple but common cases only.
6398 Type *StoreType = SI.getValueOperand()->getType();
6399 if (DL.getTypeStoreSizeInBits(StoreType) != DL.getTypeSizeInBits(StoreType) ||
6400 DL.getTypeSizeInBits(StoreType) == 0)
6401 return false;
6402
6403 unsigned HalfValBitSize = DL.getTypeSizeInBits(StoreType) / 2;
6404 Type *SplitStoreType = Type::getIntNTy(SI.getContext(), HalfValBitSize);
6405 if (DL.getTypeStoreSizeInBits(SplitStoreType) !=
6406 DL.getTypeSizeInBits(SplitStoreType))
6407 return false;
6408
6409 // Match the following patterns:
6410 // (store (or (zext LValue to i64),
6411 // (shl (zext HValue to i64), 32)), HalfValBitSize)
6412 // or
6413 // (store (or (shl (zext HValue to i64), 32)), HalfValBitSize)
6414 // (zext LValue to i64),
6415 // Expect both operands of OR and the first operand of SHL have only
6416 // one use.
6417 Value *LValue, *HValue;
6418 if (!match(SI.getValueOperand(),
6419 m_c_Or(m_OneUse(m_ZExt(m_Value(LValue))),
6420 m_OneUse(m_Shl(m_OneUse(m_ZExt(m_Value(HValue))),
6421 m_SpecificInt(HalfValBitSize))))))
6422 return false;
6423
6424 // Check LValue and HValue are int with size less or equal than 32.
6425 if (!LValue->getType()->isIntegerTy() ||
6426 DL.getTypeSizeInBits(LValue->getType()) > HalfValBitSize ||
6427 !HValue->getType()->isIntegerTy() ||
6428 DL.getTypeSizeInBits(HValue->getType()) > HalfValBitSize)
6429 return false;
6430
6431 // If LValue/HValue is a bitcast instruction, use the EVT before bitcast
6432 // as the input of target query.
6433 auto *LBC = dyn_cast<BitCastInst>(LValue);
6434 auto *HBC = dyn_cast<BitCastInst>(HValue);
6435 EVT LowTy = LBC ? EVT::getEVT(LBC->getOperand(0)->getType())
6436 : EVT::getEVT(LValue->getType());
6437 EVT HighTy = HBC ? EVT::getEVT(HBC->getOperand(0)->getType())
6438 : EVT::getEVT(HValue->getType());
6439 if (!ForceSplitStore && !TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
6440 return false;
6441
6442 // Start to split store.
6443 IRBuilder<> Builder(SI.getContext());
6444 Builder.SetInsertPoint(&SI);
6445
6446 // If LValue/HValue is a bitcast in another BB, create a new one in current
6447 // BB so it may be merged with the splitted stores by dag combiner.
6448 if (LBC && LBC->getParent() != SI.getParent())
6449 LValue = Builder.CreateBitCast(LBC->getOperand(0), LBC->getType());
6450 if (HBC && HBC->getParent() != SI.getParent())
6451 HValue = Builder.CreateBitCast(HBC->getOperand(0), HBC->getType());
6452
Jonas Paulsson5612bb22018-03-13 08:36:20 +00006453 bool IsLE = SI.getModule()->getDataLayout().isLittleEndian();
Wei Mia2f0b592016-12-22 19:44:45 +00006454 auto CreateSplitStore = [&](Value *V, bool Upper) {
6455 V = Builder.CreateZExtOrBitCast(V, SplitStoreType);
6456 Value *Addr = Builder.CreateBitCast(
6457 SI.getOperand(1),
6458 SplitStoreType->getPointerTo(SI.getPointerAddressSpace()));
Jonas Paulsson5612bb22018-03-13 08:36:20 +00006459 if ((IsLE && Upper) || (!IsLE && !Upper))
Wei Mia2f0b592016-12-22 19:44:45 +00006460 Addr = Builder.CreateGEP(
6461 SplitStoreType, Addr,
6462 ConstantInt::get(Type::getInt32Ty(SI.getContext()), 1));
6463 Builder.CreateAlignedStore(
6464 V, Addr, Upper ? SI.getAlignment() / 2 : SI.getAlignment());
6465 };
6466
6467 CreateSplitStore(LValue, false);
6468 CreateSplitStore(HValue, true);
6469
6470 // Delete the old store.
6471 SI.eraseFromParent();
6472 return true;
6473}
6474
Hiroshi Yamauchi93644322017-09-11 17:52:08 +00006475// Return true if the GEP has two operands, the first operand is of a sequential
6476// type, and the second operand is a constant.
6477static bool GEPSequentialConstIndexed(GetElementPtrInst *GEP) {
6478 gep_type_iterator I = gep_type_begin(*GEP);
6479 return GEP->getNumOperands() == 2 &&
6480 I.isSequential() &&
6481 isa<ConstantInt>(GEP->getOperand(1));
6482}
6483
6484// Try unmerging GEPs to reduce liveness interference (register pressure) across
6485// IndirectBr edges. Since IndirectBr edges tend to touch on many blocks,
6486// reducing liveness interference across those edges benefits global register
6487// allocation. Currently handles only certain cases.
6488//
6489// For example, unmerge %GEPI and %UGEPI as below.
6490//
6491// ---------- BEFORE ----------
6492// SrcBlock:
6493// ...
6494// %GEPIOp = ...
6495// ...
6496// %GEPI = gep %GEPIOp, Idx
6497// ...
6498// indirectbr ... [ label %DstB0, label %DstB1, ... label %DstBi ... ]
6499// (* %GEPI is alive on the indirectbr edges due to other uses ahead)
6500// (* %GEPIOp is alive on the indirectbr edges only because of it's used by
6501// %UGEPI)
6502//
6503// DstB0: ... (there may be a gep similar to %UGEPI to be unmerged)
6504// DstB1: ... (there may be a gep similar to %UGEPI to be unmerged)
6505// ...
6506//
6507// DstBi:
6508// ...
6509// %UGEPI = gep %GEPIOp, UIdx
6510// ...
6511// ---------------------------
6512//
6513// ---------- AFTER ----------
6514// SrcBlock:
6515// ... (same as above)
6516// (* %GEPI is still alive on the indirectbr edges)
6517// (* %GEPIOp is no longer alive on the indirectbr edges as a result of the
6518// unmerging)
6519// ...
6520//
6521// DstBi:
6522// ...
6523// %UGEPI = gep %GEPI, (UIdx-Idx)
6524// ...
6525// ---------------------------
6526//
6527// The register pressure on the IndirectBr edges is reduced because %GEPIOp is
6528// no longer alive on them.
6529//
6530// We try to unmerge GEPs here in CodGenPrepare, as opposed to limiting merging
6531// of GEPs in the first place in InstCombiner::visitGetElementPtrInst() so as
6532// not to disable further simplications and optimizations as a result of GEP
6533// merging.
6534//
6535// Note this unmerging may increase the length of the data flow critical path
6536// (the path from %GEPIOp to %UGEPI would go through %GEPI), which is a tradeoff
6537// between the register pressure and the length of data-flow critical
6538// path. Restricting this to the uncommon IndirectBr case would minimize the
6539// impact of potentially longer critical path, if any, and the impact on compile
6540// time.
6541static bool tryUnmergingGEPsAcrossIndirectBr(GetElementPtrInst *GEPI,
6542 const TargetTransformInfo *TTI) {
6543 BasicBlock *SrcBlock = GEPI->getParent();
6544 // Check that SrcBlock ends with an IndirectBr. If not, give up. The common
6545 // (non-IndirectBr) cases exit early here.
6546 if (!isa<IndirectBrInst>(SrcBlock->getTerminator()))
6547 return false;
6548 // Check that GEPI is a simple gep with a single constant index.
6549 if (!GEPSequentialConstIndexed(GEPI))
6550 return false;
6551 ConstantInt *GEPIIdx = cast<ConstantInt>(GEPI->getOperand(1));
6552 // Check that GEPI is a cheap one.
6553 if (TTI->getIntImmCost(GEPIIdx->getValue(), GEPIIdx->getType())
6554 > TargetTransformInfo::TCC_Basic)
6555 return false;
6556 Value *GEPIOp = GEPI->getOperand(0);
6557 // Check that GEPIOp is an instruction that's also defined in SrcBlock.
6558 if (!isa<Instruction>(GEPIOp))
6559 return false;
6560 auto *GEPIOpI = cast<Instruction>(GEPIOp);
6561 if (GEPIOpI->getParent() != SrcBlock)
6562 return false;
6563 // Check that GEP is used outside the block, meaning it's alive on the
6564 // IndirectBr edge(s).
6565 if (find_if(GEPI->users(), [&](User *Usr) {
6566 if (auto *I = dyn_cast<Instruction>(Usr)) {
6567 if (I->getParent() != SrcBlock) {
6568 return true;
6569 }
6570 }
6571 return false;
6572 }) == GEPI->users().end())
6573 return false;
6574 // The second elements of the GEP chains to be unmerged.
6575 std::vector<GetElementPtrInst *> UGEPIs;
6576 // Check each user of GEPIOp to check if unmerging would make GEPIOp not alive
6577 // on IndirectBr edges.
6578 for (User *Usr : GEPIOp->users()) {
6579 if (Usr == GEPI) continue;
6580 // Check if Usr is an Instruction. If not, give up.
6581 if (!isa<Instruction>(Usr))
6582 return false;
6583 auto *UI = cast<Instruction>(Usr);
6584 // Check if Usr in the same block as GEPIOp, which is fine, skip.
6585 if (UI->getParent() == SrcBlock)
6586 continue;
6587 // Check if Usr is a GEP. If not, give up.
6588 if (!isa<GetElementPtrInst>(Usr))
6589 return false;
6590 auto *UGEPI = cast<GetElementPtrInst>(Usr);
6591 // Check if UGEPI is a simple gep with a single constant index and GEPIOp is
6592 // the pointer operand to it. If so, record it in the vector. If not, give
6593 // up.
6594 if (!GEPSequentialConstIndexed(UGEPI))
6595 return false;
6596 if (UGEPI->getOperand(0) != GEPIOp)
6597 return false;
6598 if (GEPIIdx->getType() !=
6599 cast<ConstantInt>(UGEPI->getOperand(1))->getType())
6600 return false;
6601 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
6602 if (TTI->getIntImmCost(UGEPIIdx->getValue(), UGEPIIdx->getType())
6603 > TargetTransformInfo::TCC_Basic)
6604 return false;
6605 UGEPIs.push_back(UGEPI);
6606 }
6607 if (UGEPIs.size() == 0)
6608 return false;
6609 // Check the materializing cost of (Uidx-Idx).
6610 for (GetElementPtrInst *UGEPI : UGEPIs) {
6611 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
6612 APInt NewIdx = UGEPIIdx->getValue() - GEPIIdx->getValue();
6613 unsigned ImmCost = TTI->getIntImmCost(NewIdx, GEPIIdx->getType());
6614 if (ImmCost > TargetTransformInfo::TCC_Basic)
6615 return false;
6616 }
6617 // Now unmerge between GEPI and UGEPIs.
6618 for (GetElementPtrInst *UGEPI : UGEPIs) {
6619 UGEPI->setOperand(0, GEPI);
6620 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
6621 Constant *NewUGEPIIdx =
6622 ConstantInt::get(GEPIIdx->getType(),
6623 UGEPIIdx->getValue() - GEPIIdx->getValue());
6624 UGEPI->setOperand(1, NewUGEPIIdx);
6625 // If GEPI is not inbounds but UGEPI is inbounds, change UGEPI to not
6626 // inbounds to avoid UB.
6627 if (!GEPI->isInBounds()) {
6628 UGEPI->setIsInBounds(false);
6629 }
6630 }
6631 // After unmerging, verify that GEPIOp is actually only used in SrcBlock (not
6632 // alive on IndirectBr edges).
6633 assert(find_if(GEPIOp->users(), [&](User *Usr) {
6634 return cast<Instruction>(Usr)->getParent() != SrcBlock;
6635 }) == GEPIOp->users().end() && "GEPIOp is used outside SrcBlock");
6636 return true;
6637}
6638
Sanjay Patel3b8974b2017-06-08 20:00:09 +00006639bool CodeGenPrepare::optimizeInst(Instruction *I, bool &ModifiedDT) {
Ahmed Bougachaf3299142015-06-17 20:44:32 +00006640 // Bail out if we inserted the instruction to prevent optimizations from
6641 // stepping on each other's toes.
6642 if (InsertedInsts.count(I))
6643 return false;
6644
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006645 if (PHINode *P = dyn_cast<PHINode>(I)) {
6646 // It is possible for very late stage optimizations (such as SimplifyCFG)
6647 // to introduce PHI nodes too late to be cleaned up. If we detect such a
6648 // trivial PHI, go ahead and zap it here.
Daniel Berlin4d0fe642017-04-28 19:55:38 +00006649 if (Value *V = SimplifyInstruction(P, {*DL, TLInfo})) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006650 P->replaceAllUsesWith(V);
6651 P->eraseFromParent();
6652 ++NumPHIsElim;
Chris Lattneree588de2011-01-15 07:29:01 +00006653 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006654 }
Chris Lattneree588de2011-01-15 07:29:01 +00006655 return false;
6656 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006657
Chris Lattneree588de2011-01-15 07:29:01 +00006658 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006659 // If the source of the cast is a constant, then this should have
6660 // already been constant folded. The only reason NOT to constant fold
6661 // it is if something (e.g. LSR) was careful to place the constant
6662 // evaluation in a block other than then one that uses it (e.g. to hoist
6663 // the address of globals out of a loop). If this is the case, we don't
6664 // want to forward-subst the cast.
6665 if (isa<Constant>(CI->getOperand(0)))
6666 return false;
6667
Mehdi Amini44ede332015-07-09 02:09:04 +00006668 if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
Chris Lattneree588de2011-01-15 07:29:01 +00006669 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006670
Chris Lattneree588de2011-01-15 07:29:01 +00006671 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00006672 /// Sink a zext or sext into its user blocks if the target type doesn't
6673 /// fit in one register
Mehdi Amini44ede332015-07-09 02:09:04 +00006674 if (TLI &&
6675 TLI->getTypeAction(CI->getContext(),
6676 TLI->getValueType(*DL, CI->getType())) ==
6677 TargetLowering::TypeExpandInteger) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00006678 return SinkCast(CI);
6679 } else {
Jun Bum Limdee55652017-04-03 19:20:07 +00006680 bool MadeChange = optimizeExt(I);
Sanjay Patelfc580a62015-09-21 23:03:16 +00006681 return MadeChange | optimizeExtUses(I);
Manuel Jacoba7c48f92014-03-13 13:36:25 +00006682 }
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006683 }
Chris Lattneree588de2011-01-15 07:29:01 +00006684 return false;
6685 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006686
Chris Lattneree588de2011-01-15 07:29:01 +00006687 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Hal Finkeldecb0242014-01-02 21:13:43 +00006688 if (!TLI || !TLI->hasMultipleConditionRegisters())
Peter Zotovf87e5502016-04-03 17:11:53 +00006689 return OptimizeCmpExpression(CI, TLI);
Nadav Rotem465834c2012-07-24 10:51:42 +00006690
Chris Lattneree588de2011-01-15 07:29:01 +00006691 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Sanjoy Das00757272016-12-16 20:29:39 +00006692 LI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006693 if (TLI) {
Geoff Berry5256fca2015-11-20 22:34:39 +00006694 bool Modified = optimizeLoadExt(LI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006695 unsigned AS = LI->getPointerAddressSpace();
Geoff Berry5256fca2015-11-20 22:34:39 +00006696 Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
6697 return Modified;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006698 }
Hans Wennborgf3254832012-10-30 11:23:25 +00006699 return false;
Chris Lattneree588de2011-01-15 07:29:01 +00006700 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006701
Chris Lattneree588de2011-01-15 07:29:01 +00006702 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Wei Mia2f0b592016-12-22 19:44:45 +00006703 if (TLI && splitMergedValStore(*SI, *DL, *TLI))
6704 return true;
Sanjoy Das00757272016-12-16 20:29:39 +00006705 SI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006706 if (TLI) {
6707 unsigned AS = SI->getPointerAddressSpace();
Sanjay Patelfc580a62015-09-21 23:03:16 +00006708 return optimizeMemoryInst(I, SI->getOperand(1),
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006709 SI->getOperand(0)->getType(), AS);
6710 }
Chris Lattneree588de2011-01-15 07:29:01 +00006711 return false;
6712 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006713
Matt Arsenault02d915b2017-03-15 22:35:20 +00006714 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
6715 unsigned AS = RMW->getPointerAddressSpace();
6716 return optimizeMemoryInst(I, RMW->getPointerOperand(),
6717 RMW->getType(), AS);
6718 }
6719
6720 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(I)) {
6721 unsigned AS = CmpX->getPointerAddressSpace();
6722 return optimizeMemoryInst(I, CmpX->getPointerOperand(),
6723 CmpX->getCompareOperand()->getType(), AS);
6724 }
6725
Yi Jiangd069f632014-04-21 19:34:27 +00006726 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
6727
Geoff Berry5d534b62017-02-21 18:53:14 +00006728 if (BinOp && (BinOp->getOpcode() == Instruction::And) &&
6729 EnableAndCmpSinking && TLI)
6730 return sinkAndCmp0Expression(BinOp, *TLI, InsertedInsts);
6731
Yi Jiangd069f632014-04-21 19:34:27 +00006732 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
6733 BinOp->getOpcode() == Instruction::LShr)) {
6734 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
6735 if (TLI && CI && TLI->hasExtractBitsInsn())
Mehdi Amini44ede332015-07-09 02:09:04 +00006736 return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
Yi Jiangd069f632014-04-21 19:34:27 +00006737
6738 return false;
6739 }
6740
Chris Lattneree588de2011-01-15 07:29:01 +00006741 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00006742 if (GEPI->hasAllZeroIndices()) {
6743 /// The GEP operand must be a pointer, so must its result -> BitCast
6744 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
6745 GEPI->getName(), GEPI);
Vedant Kumar40399a22018-05-24 23:00:21 +00006746 NC->setDebugLoc(GEPI->getDebugLoc());
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00006747 GEPI->replaceAllUsesWith(NC);
6748 GEPI->eraseFromParent();
6749 ++NumGEPsElim;
Sanjay Patelfc580a62015-09-21 23:03:16 +00006750 optimizeInst(NC, ModifiedDT);
Chris Lattneree588de2011-01-15 07:29:01 +00006751 return true;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00006752 }
Hiroshi Yamauchi93644322017-09-11 17:52:08 +00006753 if (tryUnmergingGEPsAcrossIndirectBr(GEPI, TTI)) {
6754 return true;
6755 }
Chris Lattneree588de2011-01-15 07:29:01 +00006756 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006757 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006758
Chris Lattneree588de2011-01-15 07:29:01 +00006759 if (CallInst *CI = dyn_cast<CallInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006760 return optimizeCallInst(CI, ModifiedDT);
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006761
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00006762 if (SelectInst *SI = dyn_cast<SelectInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006763 return optimizeSelectInst(SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00006764
Tim Northoveraeb8e062014-02-19 10:02:43 +00006765 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006766 return optimizeShuffleVectorInst(SVI);
Tim Northoveraeb8e062014-02-19 10:02:43 +00006767
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00006768 if (auto *Switch = dyn_cast<SwitchInst>(I))
6769 return optimizeSwitchInst(Switch);
6770
Quentin Colombetc32615d2014-10-31 17:52:53 +00006771 if (isa<ExtractElementInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006772 return optimizeExtractElementInst(I);
Quentin Colombetc32615d2014-10-31 17:52:53 +00006773
Chris Lattneree588de2011-01-15 07:29:01 +00006774 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006775}
6776
James Molloyf01488e2016-01-15 09:20:19 +00006777/// Given an OR instruction, check to see if this is a bitreverse
6778/// idiom. If so, insert the new intrinsic and return true.
6779static bool makeBitReverse(Instruction &I, const DataLayout &DL,
6780 const TargetLowering &TLI) {
6781 if (!I.getType()->isIntegerTy() ||
6782 !TLI.isOperationLegalOrCustom(ISD::BITREVERSE,
6783 TLI.getValueType(DL, I.getType(), true)))
6784 return false;
6785
6786 SmallVector<Instruction*, 4> Insts;
Chad Rosiera00df492016-05-25 16:22:14 +00006787 if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts))
James Molloyf01488e2016-01-15 09:20:19 +00006788 return false;
6789 Instruction *LastInst = Insts.back();
6790 I.replaceAllUsesWith(LastInst);
6791 RecursivelyDeleteTriviallyDeadInstructions(&I);
6792 return true;
6793}
6794
Chris Lattnerf2836d12007-03-31 04:06:36 +00006795// In this pass we look for GEP and cast instructions that are used
6796// across basic blocks and rewrite them to improve basic-block-at-a-time
6797// selection.
Sanjay Patel3b8974b2017-06-08 20:00:09 +00006798bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool &ModifiedDT) {
Cameron Zwarichce3b9302011-01-06 00:42:50 +00006799 SunkAddrs.clear();
Cameron Zwarich5dd2aa22011-03-02 03:31:46 +00006800 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00006801
Chris Lattner7a277142011-01-15 07:14:54 +00006802 CurInstIterator = BB.begin();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00006803 while (CurInstIterator != BB.end()) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00006804 MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00006805 if (ModifiedDT)
6806 return true;
6807 }
Benjamin Kramer455fa352012-11-23 19:17:06 +00006808
James Molloyf01488e2016-01-15 09:20:19 +00006809 bool MadeBitReverse = true;
6810 while (TLI && MadeBitReverse) {
6811 MadeBitReverse = false;
6812 for (auto &I : reverse(BB)) {
6813 if (makeBitReverse(I, *DL, *TLI)) {
6814 MadeBitReverse = MadeChange = true;
George Burgess IVd4febd12016-03-22 21:25:08 +00006815 ModifiedDT = true;
James Molloyf01488e2016-01-15 09:20:19 +00006816 break;
6817 }
6818 }
6819 }
James Molloy3ef84c42016-01-15 10:36:01 +00006820 MadeChange |= dupRetToEnableTailCallOpts(&BB);
Junmo Park7d6c5f12016-01-28 09:42:39 +00006821
Chris Lattnerf2836d12007-03-31 04:06:36 +00006822 return MadeChange;
6823}
Devang Patel53771ba2011-08-18 00:50:51 +00006824
6825// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +00006826// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +00006827// find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +00006828bool CodeGenPrepare::placeDbgValues(Function &F) {
Devang Patel53771ba2011-08-18 00:50:51 +00006829 bool MadeChange = false;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00006830 for (BasicBlock &BB : F) {
Craig Topperc0196b12014-04-14 00:51:57 +00006831 Instruction *PrevNonDbgInst = nullptr;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00006832 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00006833 Instruction *Insn = &*BI++;
Devang Patel53771ba2011-08-18 00:50:51 +00006834 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
Adrian Prantl32da8892014-04-25 20:49:25 +00006835 // Leave dbg.values that refer to an alloca alone. These
Craig Topper87e715f2017-11-07 20:56:17 +00006836 // intrinsics describe the address of a variable (= the alloca)
Adrian Prantl32da8892014-04-25 20:49:25 +00006837 // being taken. They should not be moved next to the alloca
6838 // (and to the beginning of the scope), but rather stay close to
6839 // where said address is used.
6840 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
Devang Patel53771ba2011-08-18 00:50:51 +00006841 PrevNonDbgInst = Insn;
6842 continue;
6843 }
6844
6845 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
6846 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
Reid Kleckner8de1fe22015-12-08 23:00:03 +00006847 // If VI is a phi in a block with an EHPad terminator, we can't insert
6848 // after it.
6849 if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
6850 continue;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006851 LLVM_DEBUG(dbgs() << "Moving Debug Value before :\n"
6852 << *DVI << ' ' << *VI);
Devang Patel53771ba2011-08-18 00:50:51 +00006853 DVI->removeFromParent();
Reid Klecknere18f92b2015-12-08 22:33:23 +00006854 if (isa<PHINode>(VI))
6855 DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
6856 else
6857 DVI->insertAfter(VI);
Devang Patel53771ba2011-08-18 00:50:51 +00006858 MadeChange = true;
6859 ++NumDbgValueMoved;
6860 }
6861 }
6862 }
6863 return MadeChange;
6864}
Tim Northovercea0abb2014-03-29 08:22:29 +00006865
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006866/// Scale down both weights to fit into uint32_t.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006867static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
6868 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
Eugene Zelenko900b6332017-08-29 22:32:07 +00006869 uint32_t Scale = (NewMax / std::numeric_limits<uint32_t>::max()) + 1;
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006870 NewTrue = NewTrue / Scale;
6871 NewFalse = NewFalse / Scale;
6872}
6873
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006874/// Some targets prefer to split a conditional branch like:
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006875/// \code
6876/// %0 = icmp ne i32 %a, 0
6877/// %1 = icmp ne i32 %b, 0
6878/// %or.cond = or i1 %0, %1
6879/// br i1 %or.cond, label %TrueBB, label %FalseBB
6880/// \endcode
6881/// into multiple branch instructions like:
6882/// \code
6883/// bb1:
6884/// %0 = icmp ne i32 %a, 0
6885/// br i1 %0, label %TrueBB, label %bb2
6886/// bb2:
6887/// %1 = icmp ne i32 %b, 0
6888/// br i1 %1, label %TrueBB, label %FalseBB
6889/// \endcode
6890/// This usually allows instruction selection to do even further optimizations
6891/// and combine the compare with the branch instruction. Currently this is
6892/// applied for targets which have "cheap" jump instructions.
6893///
6894/// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
6895///
6896bool CodeGenPrepare::splitBranchCondition(Function &F) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00006897 if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006898 return false;
6899
6900 bool MadeChange = false;
6901 for (auto &BB : F) {
6902 // Does this BB end with the following?
6903 // %cond1 = icmp|fcmp|binary instruction ...
6904 // %cond2 = icmp|fcmp|binary instruction ...
6905 // %cond.or = or|and i1 %cond1, cond2
6906 // br i1 %cond.or label %dest1, label %dest2"
6907 BinaryOperator *LogicOp;
6908 BasicBlock *TBB, *FBB;
6909 if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
6910 continue;
6911
Sanjay Patel42574202015-09-02 19:23:23 +00006912 auto *Br1 = cast<BranchInst>(BB.getTerminator());
6913 if (Br1->getMetadata(LLVMContext::MD_unpredictable))
6914 continue;
6915
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006916 unsigned Opc;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006917 Value *Cond1, *Cond2;
6918 if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
6919 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006920 Opc = Instruction::And;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006921 else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
6922 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006923 Opc = Instruction::Or;
6924 else
6925 continue;
6926
6927 if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
6928 !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
6929 continue;
6930
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006931 LLVM_DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006932
6933 // Create a new BB.
Duncan P. N. Exon Smitha848c472016-02-21 19:52:15 +00006934 auto TmpBB =
6935 BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split",
6936 BB.getParent(), BB.getNextNode());
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006937
6938 // Update original basic block by using the first condition directly by the
6939 // branch instruction and removing the no longer needed and/or instruction.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006940 Br1->setCondition(Cond1);
6941 LogicOp->eraseFromParent();
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006942
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00006943 // Depending on the condition we have to either replace the true or the
6944 // false successor of the original branch instruction.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006945 if (Opc == Instruction::And)
6946 Br1->setSuccessor(0, TmpBB);
6947 else
6948 Br1->setSuccessor(1, TmpBB);
6949
6950 // Fill in the new basic block.
6951 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006952 if (auto *I = dyn_cast<Instruction>(Cond2)) {
6953 I->removeFromParent();
6954 I->insertBefore(Br2);
6955 }
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006956
6957 // Update PHI nodes in both successors. The original BB needs to be
Hiroshi Inoue6a391bb2017-06-27 10:35:37 +00006958 // replaced in one successor's PHI nodes, because the branch comes now from
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006959 // the newly generated BB (NewBB). In the other successor we need to add one
6960 // incoming edge to the PHI nodes, because both branch instructions target
6961 // now the same successor. Depending on the original branch condition
6962 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
Simon Pilgrimf2fbf432016-11-20 13:47:59 +00006963 // we perform the correct update for the PHI nodes.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006964 // This doesn't change the successor order of the just created branch
6965 // instruction (or any other instruction).
6966 if (Opc == Instruction::Or)
6967 std::swap(TBB, FBB);
6968
6969 // Replace the old BB with the new BB.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00006970 for (PHINode &PN : TBB->phis()) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006971 int i;
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00006972 while ((i = PN.getBasicBlockIndex(&BB)) >= 0)
6973 PN.setIncomingBlock(i, TmpBB);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006974 }
6975
6976 // Add another incoming edge form the new BB.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00006977 for (PHINode &PN : FBB->phis()) {
6978 auto *Val = PN.getIncomingValueForBlock(&BB);
6979 PN.addIncoming(Val, TmpBB);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006980 }
6981
6982 // Update the branch weights (from SelectionDAGBuilder::
6983 // FindMergedConditions).
6984 if (Opc == Instruction::Or) {
6985 // Codegen X | Y as:
6986 // BB1:
6987 // jmp_if_X TBB
6988 // jmp TmpBB
6989 // TmpBB:
6990 // jmp_if_Y TBB
6991 // jmp FBB
6992 //
6993
6994 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
6995 // The requirement is that
6996 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00006997 // = TrueProb for original BB.
6998 // Assuming the original weights are A and B, one choice is to set BB1's
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006999 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
7000 // assumes that
7001 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
7002 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
7003 // TmpBB, but the math is more complicated.
7004 uint64_t TrueWeight, FalseWeight;
Sanjay Pateldc88bd62016-04-23 20:01:22 +00007005 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007006 uint64_t NewTrueWeight = TrueWeight;
7007 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
7008 scaleWeights(NewTrueWeight, NewFalseWeight);
7009 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
7010 .createBranchWeights(TrueWeight, FalseWeight));
7011
7012 NewTrueWeight = TrueWeight;
7013 NewFalseWeight = 2 * FalseWeight;
7014 scaleWeights(NewTrueWeight, NewFalseWeight);
7015 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
7016 .createBranchWeights(TrueWeight, FalseWeight));
7017 }
7018 } else {
7019 // Codegen X & Y as:
7020 // BB1:
7021 // jmp_if_X TmpBB
7022 // jmp FBB
7023 // TmpBB:
7024 // jmp_if_Y TBB
7025 // jmp FBB
7026 //
7027 // This requires creation of TmpBB after CurBB.
7028
7029 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
7030 // The requirement is that
7031 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00007032 // = FalseProb for original BB.
7033 // Assuming the original weights are A and B, one choice is to set BB1's
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007034 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
7035 // assumes that
7036 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
7037 uint64_t TrueWeight, FalseWeight;
Sanjay Pateldc88bd62016-04-23 20:01:22 +00007038 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007039 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
7040 uint64_t NewFalseWeight = FalseWeight;
7041 scaleWeights(NewTrueWeight, NewFalseWeight);
7042 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
7043 .createBranchWeights(TrueWeight, FalseWeight));
7044
7045 NewTrueWeight = 2 * TrueWeight;
7046 NewFalseWeight = FalseWeight;
7047 scaleWeights(NewTrueWeight, NewFalseWeight);
7048 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
7049 .createBranchWeights(TrueWeight, FalseWeight));
7050 }
7051 }
7052
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007053 // Note: No point in getting fancy here, since the DT info is never
Quentin Colombet7bdd50d2015-03-18 23:17:28 +00007054 // available to CodeGenPrepare.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007055 ModifiedDT = true;
7056
7057 MadeChange = true;
7058
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007059 LLVM_DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
7060 TmpBB->dump());
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007061 }
7062 return MadeChange;
7063}