blob: 4335f10117ee54022181f5988674045452c927e1 [file] [log] [blame]
Chris Lattnerf2836d12007-03-31 04:06:36 +00001//===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattnerf2836d12007-03-31 04:06:36 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This pass munges the code in the input function to better prepare it for
Gordon Henriksen829046b2008-05-08 17:46:35 +000010// SelectionDAG-based code generation. This works around limitations in it's
11// basic-block-at-a-time approach. It should eventually be removed.
Chris Lattnerf2836d12007-03-31 04:06:36 +000012//
13//===----------------------------------------------------------------------===//
14
Eugene Zelenko900b6332017-08-29 22:32:07 +000015#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/ArrayRef.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "llvm/ADT/DenseMap.h"
Eric Christopherb6c190d2019-04-12 06:16:33 +000018#include "llvm/ADT/MapVector.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 optimizing for size.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000296 bool OptSize;
297
Mehdi Amini4fe37982015-07-07 18:45:17 +0000298 /// DataLayout for the Function being processed.
Eugene Zelenko900b6332017-08-29 22:32:07 +0000299 const DataLayout *DL = nullptr;
Mehdi Amini4fe37982015-07-07 18:45:17 +0000300
Teresa Johnson3bd4b5a2019-03-25 18:38:48 +0000301 /// Building the dominator tree can be expensive, so we only build it
302 /// lazily and update it when required.
303 std::unique_ptr<DominatorTree> DT;
304
Chris Lattnerf2836d12007-03-31 04:06:36 +0000305 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +0000306 static char ID; // Pass identification, replacement for typeid
Eugene Zelenko900b6332017-08-29 22:32:07 +0000307
308 CodeGenPrepare() : FunctionPass(ID) {
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000309 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
310 }
Eugene Zelenko900b6332017-08-29 22:32:07 +0000311
Craig Topper4584cd52014-03-07 09:26:03 +0000312 bool runOnFunction(Function &F) override;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000313
Mehdi Amini117296c2016-10-01 02:56:57 +0000314 StringRef getPassName() const override { return "CodeGen Prepare"; }
Evan Cheng99cafb12012-12-21 01:48:14 +0000315
Craig Topper4584cd52014-03-07 09:26:03 +0000316 void getAnalysisUsage(AnalysisUsage &AU) const override {
George Burgess IVd4febd12016-03-22 21:25:08 +0000317 // FIXME: When we can selectively preserve passes, preserve the domtree.
Dehao Chen302b69c2016-10-18 20:42:47 +0000318 AU.addRequired<ProfileSummaryInfoWrapperPass>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000319 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000320 AU.addRequired<TargetTransformInfoWrapperPass>();
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000321 AU.addRequired<LoopInfoWrapperPass>();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000322 }
323
Chris Lattnerf2836d12007-03-31 04:06:36 +0000324 private:
James Y Knight72f76bf2018-11-07 15:24:12 +0000325 template <typename F>
326 void resetIteratorIfInvalidatedWhileCalling(BasicBlock *BB, F f) {
327 // Substituting can cause recursive simplifications, which can invalidate
328 // our iterator. Use a WeakTrackingVH to hold onto it in case this
329 // happens.
330 Value *CurValue = &*CurInstIterator;
331 WeakTrackingVH IterHandle(CurValue);
332
333 f();
334
335 // If the iterator instruction was recursively deleted, start over at the
336 // start of the block.
337 if (IterHandle != CurValue) {
338 CurInstIterator = BB->begin();
339 SunkAddrs.clear();
340 }
341 }
342
Teresa Johnson3bd4b5a2019-03-25 18:38:48 +0000343 // Get the DominatorTree, building if necessary.
344 DominatorTree &getDT(Function &F) {
345 if (!DT)
346 DT = llvm::make_unique<DominatorTree>(F);
347 return *DT;
348 }
349
Sanjay Patelfc580a62015-09-21 23:03:16 +0000350 bool eliminateFallThrough(Function &F);
351 bool eliminateMostlyEmptyBlocks(Function &F);
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000352 BasicBlock *findDestBlockOfMergeableEmptyBlock(BasicBlock *BB);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000353 bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
354 void eliminateMostlyEmptyBlock(BasicBlock *BB);
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000355 bool isMergingEmptyBlockProfitable(BasicBlock *BB, BasicBlock *DestBB,
356 bool isPreheader);
Teresa Johnson3bd4b5a2019-03-25 18:38:48 +0000357 bool optimizeBlock(BasicBlock &BB, bool &ModifiedDT);
358 bool optimizeInst(Instruction *I, bool &ModifiedDT);
Fangrui Songcb0bab82018-07-16 18:51:40 +0000359 bool optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
360 Type *AccessTy, unsigned AddrSpace);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000361 bool optimizeInlineAsmInst(CallInst *CS);
Sanjay Patel3b8974b2017-06-08 20:00:09 +0000362 bool optimizeCallInst(CallInst *CI, bool &ModifiedDT);
Jun Bum Limdee55652017-04-03 19:20:07 +0000363 bool optimizeExt(Instruction *&I);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000364 bool optimizeExtUses(Instruction *I);
Fangrui Songcb0bab82018-07-16 18:51:40 +0000365 bool optimizeLoadExt(LoadInst *Load);
Teresa Johnsonb7e21382019-03-27 18:44:25 +0000366 bool optimizeSelectInst(SelectInst *SI);
Fangrui Songcb0bab82018-07-16 18:51:40 +0000367 bool optimizeShuffleVectorInst(ShuffleVectorInst *SVI);
368 bool optimizeSwitchInst(SwitchInst *SI);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000369 bool optimizeExtractElementInst(Instruction *Inst);
Rong Xuce3be452019-03-08 22:46:18 +0000370 bool dupRetToEnableTailCallOpts(BasicBlock *BB, bool &ModifiedDT);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000371 bool placeDbgValues(Function &F);
Jun Bum Lim42301012017-03-17 19:05:21 +0000372 bool canFormExtLd(const SmallVectorImpl<Instruction *> &MovedExts,
373 LoadInst *&LI, Instruction *&Inst, bool HasPromoted);
374 bool tryToPromoteExts(TypePromotionTransaction &TPT,
375 const SmallVectorImpl<Instruction *> &Exts,
376 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
377 unsigned CreatedInstsCost = 0);
Teresa Johnson3bd4b5a2019-03-25 18:38:48 +0000378 bool mergeSExts(Function &F);
Haicheng Wu0aae2bc2018-05-10 18:27:36 +0000379 bool splitLargeGEPOffsets();
Jun Bum Limdee55652017-04-03 19:20:07 +0000380 bool performAddressTypePromotion(
381 Instruction *&Inst,
382 bool AllowPromotionWithoutCommonHeader,
383 bool HasPromoted, TypePromotionTransaction &TPT,
384 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts);
Rong Xuce3be452019-03-08 22:46:18 +0000385 bool splitBranchCondition(Function &F, bool &ModifiedDT);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000386 bool simplifyOffsetableRelocate(Instruction &I);
Florian Hahn3b251962019-02-05 10:27:40 +0000387
388 bool tryToSinkFreeOperands(Instruction *I);
Teresa Johnson4dc85192019-03-24 15:18:50 +0000389 bool replaceMathCmpWithIntrinsic(BinaryOperator *BO, CmpInst *Cmp,
Teresa Johnson3bd4b5a2019-03-25 18:38:48 +0000390 Intrinsic::ID IID);
391 bool optimizeCmp(CmpInst *Cmp, bool &ModifiedDT);
392 bool combineToUSubWithOverflow(CmpInst *Cmp, bool &ModifiedDT);
393 bool combineToUAddWithOverflow(CmpInst *Cmp, bool &ModifiedDT);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000394 };
Eugene Zelenko900b6332017-08-29 22:32:07 +0000395
396} // end anonymous namespace
Devang Patel09f162c2007-05-01 21:15:47 +0000397
Devang Patel8c78a0b2007-05-03 01:11:54 +0000398char CodeGenPrepare::ID = 0;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000399
Matthias Braun1527baa2017-05-25 21:26:32 +0000400INITIALIZE_PASS_BEGIN(CodeGenPrepare, DEBUG_TYPE,
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000401 "Optimize for code generation", false, false)
Dehao Chen302b69c2016-10-18 20:42:47 +0000402INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
Matthias Braun1527baa2017-05-25 21:26:32 +0000403INITIALIZE_PASS_END(CodeGenPrepare, DEBUG_TYPE,
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000404 "Optimize for code generation", false, false)
Chris Lattnerf2836d12007-03-31 04:06:36 +0000405
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000406FunctionPass *llvm::createCodeGenPreparePass() { return new CodeGenPrepare(); }
Chris Lattnerf2836d12007-03-31 04:06:36 +0000407
Chris Lattnerf2836d12007-03-31 04:06:36 +0000408bool CodeGenPrepare::runOnFunction(Function &F) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000409 if (skipFunction(F))
Paul Robinson7c99ec52014-03-31 17:43:35 +0000410 return false;
411
Mehdi Amini4fe37982015-07-07 18:45:17 +0000412 DL = &F.getParent()->getDataLayout();
413
Chris Lattnerf2836d12007-03-31 04:06:36 +0000414 bool EverMadeChange = false;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000415 // Clear per function information.
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000416 InsertedInsts.clear();
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000417 PromotedInsts.clear();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000418
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000419 if (auto *TPC = getAnalysisIfAvailable<TargetPassConfig>()) {
420 TM = &TPC->getTM<TargetMachine>();
Igor Laevsky3be81ba2017-02-07 13:27:20 +0000421 SubtargetInfo = TM->getSubtargetImpl(F);
422 TLI = SubtargetInfo->getTargetLowering();
423 TRI = SubtargetInfo->getRegisterInfo();
424 }
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000425 TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000426 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000427 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Teresa Johnsona4ce3bf2017-12-20 17:53:10 +0000428 BPI.reset(new BranchProbabilityInfo(F, *LI));
429 BFI.reset(new BlockFrequencyInfo(F, *BPI, *LI));
Evandro Menezes85bd3972019-04-04 22:40:06 +0000430 OptSize = F.hasOptSize();
Evan Cheng0663f232011-03-21 01:19:09 +0000431
Easwaran Raman0d55b552017-11-14 19:31:51 +0000432 ProfileSummaryInfo *PSI =
Vedant Kumare7b789b2018-11-19 05:23:16 +0000433 &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
Dehao Chen302b69c2016-10-18 20:42:47 +0000434 if (ProfileGuidedSectionPrefix) {
Teresa Johnsona4ce3bf2017-12-20 17:53:10 +0000435 if (PSI->isFunctionHotInCallGraph(&F, *BFI))
Dehao Chen302b69c2016-10-18 20:42:47 +0000436 F.setSectionPrefix(".hot");
Teresa Johnsona4ce3bf2017-12-20 17:53:10 +0000437 else if (PSI->isFunctionColdInCallGraph(&F, *BFI))
Teresa Johnson720d9b42017-05-09 01:43:24 +0000438 F.setSectionPrefix(".unlikely");
Dehao Chen302b69c2016-10-18 20:42:47 +0000439 }
440
Preston Gurdcdf540d2012-09-04 18:22:17 +0000441 /// This optimization identifies DIV instructions that can be
442 /// profitably bypassed and carried out with a shorter, faster divide.
Easwaran Raman0d55b552017-11-14 19:31:51 +0000443 if (!OptSize && !PSI->hasHugeWorkingSetSize() && TLI &&
444 TLI->isSlowDivBypassed()) {
Preston Gurd0d67f512012-10-04 21:33:40 +0000445 const DenseMap<unsigned int, unsigned int> &BypassWidths =
446 TLI->getBypassSlowDivWidths();
Eric Christopher49a7d6c2016-01-04 23:18:58 +0000447 BasicBlock* BB = &*F.begin();
448 while (BB != nullptr) {
449 // bypassSlowDivision may create new BBs, but we don't want to reapply the
450 // optimization to those blocks.
451 BasicBlock* Next = BB->getNextNode();
452 EverMadeChange |= bypassSlowDivision(BB, BypassWidths);
453 BB = Next;
454 }
Preston Gurdcdf540d2012-09-04 18:22:17 +0000455 }
456
457 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerc3748562007-04-02 01:35:34 +0000458 // unconditional branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000459 EverMadeChange |= eliminateMostlyEmptyBlocks(F);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000460
Rong Xuce3be452019-03-08 22:46:18 +0000461 bool ModifiedDT = false;
Geoff Berry5d534b62017-02-21 18:53:14 +0000462 if (!DisableBranchOpts)
Rong Xuce3be452019-03-08 22:46:18 +0000463 EverMadeChange |= splitBranchCondition(F, ModifiedDT);
Tim Northovercea0abb2014-03-29 08:22:29 +0000464
Michael Kuperstein13bf8a22017-02-28 00:11:34 +0000465 // Split some critical edges where one of the sources is an indirect branch,
466 // to help generate sane code for PHIs involving such edges.
Hiroshi Yamauchi9364fa32017-12-04 20:36:01 +0000467 EverMadeChange |= SplitIndirectBrCriticalEdges(F);
Michael Kuperstein13bf8a22017-02-28 00:11:34 +0000468
Chris Lattnerc3748562007-04-02 01:35:34 +0000469 bool MadeChange = true;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000470 while (MadeChange) {
471 MadeChange = false;
Teresa Johnson3bd4b5a2019-03-25 18:38:48 +0000472 DT.reset();
Hans Wennborg02fbc712012-09-19 07:48:16 +0000473 for (Function::iterator I = F.begin(); I != F.end(); ) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000474 BasicBlock *BB = &*I++;
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000475 bool ModifiedDTOnIteration = false;
Teresa Johnson3bd4b5a2019-03-25 18:38:48 +0000476 MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000477
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000478 // Restart BB iteration if the dominator tree of the Function was changed
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000479 if (ModifiedDTOnIteration)
480 break;
Evan Cheng0663f232011-03-21 01:19:09 +0000481 }
Jun Bum Limdee55652017-04-03 19:20:07 +0000482 if (EnableTypePromotionMerge && !ValToSExtendedUses.empty())
Teresa Johnson3bd4b5a2019-03-25 18:38:48 +0000483 MadeChange |= mergeSExts(F);
Haicheng Wu0aae2bc2018-05-10 18:27:36 +0000484 if (!LargeOffsetGEPMap.empty())
485 MadeChange |= splitLargeGEPOffsets();
Jun Bum Limdee55652017-04-03 19:20:07 +0000486
487 // Really free removed instructions during promotion.
488 for (Instruction *I : RemovedInsts)
Reid Kleckner96ab8722017-05-18 17:24:10 +0000489 I->deleteValue();
Jun Bum Limdee55652017-04-03 19:20:07 +0000490
Chris Lattnerf2836d12007-03-31 04:06:36 +0000491 EverMadeChange |= MadeChange;
Peter Collingbourneabd820a2018-10-23 21:23:18 +0000492 SeenChainsForSExt.clear();
493 ValToSExtendedUses.clear();
494 RemovedInsts.clear();
495 LargeOffsetGEPMap.clear();
496 LargeOffsetGEPID.clear();
Chris Lattnerf2836d12007-03-31 04:06:36 +0000497 }
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000498
499 SunkAddrs.clear();
500
Cameron Zwarich338d3622011-03-11 21:52:04 +0000501 if (!DisableBranchOpts) {
502 MadeChange = false;
David Stenberg23bba562018-07-02 14:23:48 +0000503 // Use a set vector to get deterministic iteration order. The order the
504 // blocks are removed may affect whether or not PHI nodes in successors
505 // are removed.
506 SmallSetVector<BasicBlock*, 8> WorkList;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +0000507 for (BasicBlock &BB : F) {
508 SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
509 MadeChange |= ConstantFoldTerminator(&BB, true);
Bill Wendling97b93592012-03-04 10:46:01 +0000510 if (!MadeChange) continue;
511
512 for (SmallVectorImpl<BasicBlock*>::iterator
513 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
514 if (pred_begin(*II) == pred_end(*II))
515 WorkList.insert(*II);
516 }
517
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000518 // Delete the dead blocks and any of their dead successors.
Bill Wendlingab417b62012-12-06 00:30:20 +0000519 MadeChange |= !WorkList.empty();
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000520 while (!WorkList.empty()) {
David Stenberg23bba562018-07-02 14:23:48 +0000521 BasicBlock *BB = WorkList.pop_back_val();
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000522 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
523
524 DeleteDeadBlock(BB);
Stephen Lin837bba12013-07-15 17:55:02 +0000525
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000526 for (SmallVectorImpl<BasicBlock*>::iterator
527 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
528 if (pred_begin(*II) == pred_end(*II))
529 WorkList.insert(*II);
530 }
Cameron Zwarich338d3622011-03-11 21:52:04 +0000531
Nadav Rotem70409992012-08-14 05:19:07 +0000532 // Merge pairs of basic blocks with unconditional branches, connected by
533 // a single edge.
534 if (EverMadeChange || MadeChange)
Sanjay Patelfc580a62015-09-21 23:03:16 +0000535 MadeChange |= eliminateFallThrough(F);
Nadav Rotem70409992012-08-14 05:19:07 +0000536
Cameron Zwarich338d3622011-03-11 21:52:04 +0000537 EverMadeChange |= MadeChange;
538 }
539
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000540 if (!DisableGCOpts) {
541 SmallVector<Instruction *, 2> Statepoints;
542 for (BasicBlock &BB : F)
543 for (Instruction &I : BB)
544 if (isStatepoint(I))
545 Statepoints.push_back(&I);
546 for (auto &I : Statepoints)
547 EverMadeChange |= simplifyOffsetableRelocate(*I);
548 }
549
Vedant Kumar30406fd2018-08-21 23:43:08 +0000550 // Do this last to clean up use-before-def scenarios introduced by other
551 // preparatory transforms.
552 EverMadeChange |= placeDbgValues(F);
553
Chris Lattnerf2836d12007-03-31 04:06:36 +0000554 return EverMadeChange;
555}
556
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000557/// Merge basic blocks which are connected by a single edge, where one of the
558/// basic blocks has a single successor pointing to the other basic block,
559/// which has a single predecessor.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000560bool CodeGenPrepare::eliminateFallThrough(Function &F) {
Nadav Rotem70409992012-08-14 05:19:07 +0000561 bool Changed = false;
562 // Scan all of the blocks in the function, except for the entry block.
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000563 // Use a temporary array to avoid iterator being invalidated when
564 // deleting blocks.
565 SmallVector<WeakTrackingVH, 16> Blocks;
566 for (auto &Block : llvm::make_range(std::next(F.begin()), F.end()))
567 Blocks.push_back(&Block);
568
569 for (auto &Block : Blocks) {
570 auto *BB = cast_or_null<BasicBlock>(Block);
571 if (!BB)
572 continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000573 // If the destination block has a single pred, then this is a trivial
574 // edge, just collapse it.
575 BasicBlock *SinglePred = BB->getSinglePredecessor();
576
Evan Cheng64a223a2012-09-28 23:58:57 +0000577 // Don't merge if BB's address is taken.
578 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000579
580 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
581 if (Term && !Term->isConditional()) {
582 Changed = true;
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000583 LLVM_DEBUG(dbgs() << "To merge:\n" << *BB << "\n\n\n");
Nadav Rotem70409992012-08-14 05:19:07 +0000584
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000585 // Merge BB into SinglePred and delete it.
586 MergeBlockIntoPredecessor(BB);
Nadav Rotem70409992012-08-14 05:19:07 +0000587 }
588 }
589 return Changed;
590}
591
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000592/// Find a destination block from BB if BB is mergeable empty block.
593BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) {
594 // If this block doesn't end with an uncond branch, ignore it.
595 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
596 if (!BI || !BI->isUnconditional())
597 return nullptr;
598
599 // If the instruction before the branch (skipping debug info) isn't a phi
600 // node, then other stuff is happening here.
601 BasicBlock::iterator BBI = BI->getIterator();
602 if (BBI != BB->begin()) {
603 --BBI;
604 while (isa<DbgInfoIntrinsic>(BBI)) {
605 if (BBI == BB->begin())
606 break;
607 --BBI;
608 }
609 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
610 return nullptr;
611 }
612
613 // Do not break infinite loops.
614 BasicBlock *DestBB = BI->getSuccessor(0);
615 if (DestBB == BB)
616 return nullptr;
617
618 if (!canMergeBlocks(BB, DestBB))
619 DestBB = nullptr;
620
621 return DestBB;
622}
623
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000624/// Eliminate blocks that contain only PHI nodes, debug info directives, and an
625/// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
626/// edges in ways that are non-optimal for isel. Start by eliminating these
627/// blocks so we can split them the way we want them.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000628bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000629 SmallPtrSet<BasicBlock *, 16> Preheaders;
630 SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end());
631 while (!LoopList.empty()) {
632 Loop *L = LoopList.pop_back_val();
633 LoopList.insert(LoopList.end(), L->begin(), L->end());
634 if (BasicBlock *Preheader = L->getLoopPreheader())
635 Preheaders.insert(Preheader);
636 }
637
Chris Lattnerc3748562007-04-02 01:35:34 +0000638 bool MadeChange = false;
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000639 // Copy blocks into a temporary array to avoid iterator invalidation issues
640 // as we remove them.
Chris Lattnerc3748562007-04-02 01:35:34 +0000641 // Note that this intentionally skips the entry block.
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000642 SmallVector<WeakTrackingVH, 16> Blocks;
643 for (auto &Block : llvm::make_range(std::next(F.begin()), F.end()))
644 Blocks.push_back(&Block);
645
646 for (auto &Block : Blocks) {
647 BasicBlock *BB = cast_or_null<BasicBlock>(Block);
648 if (!BB)
649 continue;
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000650 BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB);
651 if (!DestBB ||
652 !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.count(BB)))
Chris Lattnerc3748562007-04-02 01:35:34 +0000653 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000654
Sanjay Patelfc580a62015-09-21 23:03:16 +0000655 eliminateMostlyEmptyBlock(BB);
Chris Lattnerc3748562007-04-02 01:35:34 +0000656 MadeChange = true;
657 }
658 return MadeChange;
659}
660
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000661bool CodeGenPrepare::isMergingEmptyBlockProfitable(BasicBlock *BB,
662 BasicBlock *DestBB,
663 bool isPreheader) {
664 // Do not delete loop preheaders if doing so would create a critical edge.
665 // Loop preheaders can be good locations to spill registers. If the
666 // preheader is deleted and we create a critical edge, registers may be
667 // spilled in the loop body instead.
668 if (!DisablePreheaderProtect && isPreheader &&
669 !(BB->getSinglePredecessor() &&
670 BB->getSinglePredecessor()->getSingleSuccessor()))
671 return false;
672
Craig Topper784929d2019-02-08 20:48:56 +0000673 // Skip merging if the block's successor is also a successor to any callbr
674 // that leads to this block.
675 // FIXME: Is this really needed? Is this a correctness issue?
676 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
677 if (auto *CBI = dyn_cast<CallBrInst>((*PI)->getTerminator()))
678 for (unsigned i = 0, e = CBI->getNumSuccessors(); i != e; ++i)
679 if (DestBB == CBI->getSuccessor(i))
680 return false;
681 }
682
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000683 // Try to skip merging if the unique predecessor of BB is terminated by a
684 // switch or indirect branch instruction, and BB is used as an incoming block
685 // of PHIs in DestBB. In such case, merging BB and DestBB would cause ISel to
686 // add COPY instructions in the predecessor of BB instead of BB (if it is not
687 // merged). Note that the critical edge created by merging such blocks wont be
688 // split in MachineSink because the jump table is not analyzable. By keeping
689 // such empty block (BB), ISel will place COPY instructions in BB, not in the
690 // predecessor of BB.
691 BasicBlock *Pred = BB->getUniquePredecessor();
692 if (!Pred ||
693 !(isa<SwitchInst>(Pred->getTerminator()) ||
694 isa<IndirectBrInst>(Pred->getTerminator())))
695 return true;
696
Jonas Devlieghere42243df2018-08-07 12:14:01 +0000697 if (BB->getTerminator() != BB->getFirstNonPHIOrDbg())
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000698 return true;
699
700 // We use a simple cost heuristic which determine skipping merging is
701 // profitable if the cost of skipping merging is less than the cost of
702 // merging : Cost(skipping merging) < Cost(merging BB), where the
703 // Cost(skipping merging) is Freq(BB) * (Cost(Copy) + Cost(Branch)), and
704 // the Cost(merging BB) is Freq(Pred) * Cost(Copy).
705 // Assuming Cost(Copy) == Cost(Branch), we could simplify it to :
706 // Freq(Pred) / Freq(BB) > 2.
707 // Note that if there are multiple empty blocks sharing the same incoming
708 // value for the PHIs in the DestBB, we consider them together. In such
709 // case, Cost(merging BB) will be the sum of their frequencies.
710
711 if (!isa<PHINode>(DestBB->begin()))
712 return true;
713
714 SmallPtrSet<BasicBlock *, 16> SameIncomingValueBBs;
715
716 // Find all other incoming blocks from which incoming values of all PHIs in
717 // DestBB are the same as the ones from BB.
718 for (pred_iterator PI = pred_begin(DestBB), E = pred_end(DestBB); PI != E;
719 ++PI) {
720 BasicBlock *DestBBPred = *PI;
721 if (DestBBPred == BB)
722 continue;
723
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000724 if (llvm::all_of(DestBB->phis(), [&](const PHINode &DestPN) {
725 return DestPN.getIncomingValueForBlock(BB) ==
726 DestPN.getIncomingValueForBlock(DestBBPred);
727 }))
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000728 SameIncomingValueBBs.insert(DestBBPred);
729 }
730
731 // See if all BB's incoming values are same as the value from Pred. In this
732 // case, no reason to skip merging because COPYs are expected to be place in
733 // Pred already.
734 if (SameIncomingValueBBs.count(Pred))
735 return true;
736
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000737 BlockFrequency PredFreq = BFI->getBlockFreq(Pred);
738 BlockFrequency BBFreq = BFI->getBlockFreq(BB);
739
740 for (auto SameValueBB : SameIncomingValueBBs)
741 if (SameValueBB->getUniquePredecessor() == Pred &&
742 DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB))
743 BBFreq += BFI->getBlockFreq(SameValueBB);
744
745 return PredFreq.getFrequency() <=
746 BBFreq.getFrequency() * FreqRatioToSkipMerge;
747}
748
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000749/// Return true if we can merge BB into DestBB if there is a single
750/// unconditional branch between them, and BB contains no other non-phi
Chris Lattnerc3748562007-04-02 01:35:34 +0000751/// instructions.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000752bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
Chris Lattnerc3748562007-04-02 01:35:34 +0000753 const BasicBlock *DestBB) const {
754 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
755 // the successor. If there are more complex condition (e.g. preheaders),
756 // don't mess around with them.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000757 for (const PHINode &PN : BB->phis()) {
758 for (const User *U : PN.users()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000759 const Instruction *UI = cast<Instruction>(U);
760 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
Chris Lattnerc3748562007-04-02 01:35:34 +0000761 return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000762 // If User is inside DestBB block and it is a PHINode then check
763 // incoming value. If incoming value is not from BB then this is
Devang Pateld3208522007-04-25 00:37:04 +0000764 // a complex condition (e.g. preheaders) we want to avoid here.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000765 if (UI->getParent() == DestBB) {
766 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
Devang Pateld3208522007-04-25 00:37:04 +0000767 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
768 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
769 if (Insn && Insn->getParent() == BB &&
770 Insn->getParent() != UPN->getIncomingBlock(I))
771 return false;
772 }
773 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000774 }
775 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000776
Chris Lattnerc3748562007-04-02 01:35:34 +0000777 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
778 // and DestBB may have conflicting incoming values for the block. If so, we
779 // can't merge the block.
780 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
781 if (!DestBBPN) return true; // no conflict.
Eric Christopherc1ea1492008-09-24 05:32:41 +0000782
Chris Lattnerc3748562007-04-02 01:35:34 +0000783 // Collect the preds of BB.
Chris Lattner8201a9b2007-11-06 22:07:40 +0000784 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerc3748562007-04-02 01:35:34 +0000785 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
786 // It is faster to get preds from a PHI than with pred_iterator.
787 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
788 BBPreds.insert(BBPN->getIncomingBlock(i));
789 } else {
790 BBPreds.insert(pred_begin(BB), pred_end(BB));
791 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000792
Chris Lattnerc3748562007-04-02 01:35:34 +0000793 // Walk the preds of DestBB.
794 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
795 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
796 if (BBPreds.count(Pred)) { // Common predecessor?
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000797 for (const PHINode &PN : DestBB->phis()) {
798 const Value *V1 = PN.getIncomingValueForBlock(Pred);
799 const Value *V2 = PN.getIncomingValueForBlock(BB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000800
Chris Lattnerc3748562007-04-02 01:35:34 +0000801 // If V2 is a phi node in BB, look up what the mapped value will be.
802 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
803 if (V2PN->getParent() == BB)
804 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000805
Chris Lattnerc3748562007-04-02 01:35:34 +0000806 // If there is a conflict, bail out.
807 if (V1 != V2) return false;
808 }
809 }
810 }
811
812 return true;
813}
814
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000815/// Eliminate a basic block that has only phi's and an unconditional branch in
816/// it.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000817void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000818 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
819 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000820
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000821 LLVM_DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n"
822 << *BB << *DestBB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000823
Chris Lattnerc3748562007-04-02 01:35:34 +0000824 // If the destination block has a single pred, then this is a trivial edge,
825 // just collapse it.
Chris Lattner4059f432008-11-27 19:29:14 +0000826 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattner8a172da2008-11-28 19:54:49 +0000827 if (SinglePred != DestBB) {
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000828 assert(SinglePred == BB &&
829 "Single predecessor not the same as predecessor");
830 // Merge DestBB into SinglePred/BB and delete it.
831 MergeBlockIntoPredecessor(DestBB);
832 // Note: BB(=SinglePred) will not be deleted on this path.
833 // DestBB(=its single successor) is the one that was deleted.
834 LLVM_DEBUG(dbgs() << "AFTER:\n" << *SinglePred << "\n\n\n");
Chris Lattner8a172da2008-11-28 19:54:49 +0000835 return;
836 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000837 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000838
Chris Lattnerc3748562007-04-02 01:35:34 +0000839 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
840 // to handle the new incoming edges it is about to have.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000841 for (PHINode &PN : DestBB->phis()) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000842 // Remove the incoming value for BB, and remember it.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000843 Value *InVal = PN.removeIncomingValue(BB, false);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000844
Chris Lattnerc3748562007-04-02 01:35:34 +0000845 // Two options: either the InVal is a phi node defined in BB or it is some
846 // value that dominates BB.
847 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
848 if (InValPhi && InValPhi->getParent() == BB) {
849 // Add all of the input values of the input PHI as inputs of this phi.
850 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000851 PN.addIncoming(InValPhi->getIncomingValue(i),
852 InValPhi->getIncomingBlock(i));
Chris Lattnerc3748562007-04-02 01:35:34 +0000853 } else {
854 // Otherwise, add one instance of the dominating value for each edge that
855 // we will be adding.
856 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
857 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000858 PN.addIncoming(InVal, BBPN->getIncomingBlock(i));
Chris Lattnerc3748562007-04-02 01:35:34 +0000859 } else {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000860 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000861 PN.addIncoming(InVal, *PI);
Chris Lattnerc3748562007-04-02 01:35:34 +0000862 }
863 }
864 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000865
Chris Lattnerc3748562007-04-02 01:35:34 +0000866 // The PHIs are now updated, change everything that refers to BB to use
867 // DestBB and remove BB.
868 BB->replaceAllUsesWith(DestBB);
869 BB->eraseFromParent();
Cameron Zwarichced753f2011-01-05 17:27:27 +0000870 ++NumBlocksElim;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000871
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000872 LLVM_DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerc3748562007-04-02 01:35:34 +0000873}
874
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000875// Computes a map of base pointer relocation instructions to corresponding
876// derived pointer relocation instructions given a vector of all relocate calls
877static void computeBaseDerivedRelocateMap(
Manuel Jacob83eefa62016-01-05 04:03:00 +0000878 const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
879 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>>
880 &RelocateInstMap) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000881 // Collect information in two maps: one primarily for locating the base object
882 // while filling the second map; the second map is the final structure holding
883 // a mapping between Base and corresponding Derived relocate calls
Manuel Jacob83eefa62016-01-05 04:03:00 +0000884 DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap;
885 for (auto *ThisRelocate : AllRelocateCalls) {
886 auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
887 ThisRelocate->getDerivedPtrIndex());
888 RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000889 }
890 for (auto &Item : RelocateIdxMap) {
891 std::pair<unsigned, unsigned> Key = Item.first;
892 if (Key.first == Key.second)
893 // Base relocation: nothing to insert
894 continue;
895
Manuel Jacob83eefa62016-01-05 04:03:00 +0000896 GCRelocateInst *I = Item.second;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000897 auto BaseKey = std::make_pair(Key.first, Key.first);
Sanjoy Dasb8186762015-02-27 02:24:16 +0000898
899 // We're iterating over RelocateIdxMap so we cannot modify it.
900 auto MaybeBase = RelocateIdxMap.find(BaseKey);
901 if (MaybeBase == RelocateIdxMap.end())
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000902 // TODO: We might want to insert a new base object relocate and gep off
903 // that, if there are enough derived object relocates.
904 continue;
Sanjoy Dasb8186762015-02-27 02:24:16 +0000905
906 RelocateInstMap[MaybeBase->second].push_back(I);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000907 }
908}
909
910// Accepts a GEP and extracts the operands into a vector provided they're all
911// small integer constants
912static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
913 SmallVectorImpl<Value *> &OffsetV) {
914 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
915 // Only accept small constant integer operands
916 auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
917 if (!Op || Op->getZExtValue() > 20)
918 return false;
919 }
920
921 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
922 OffsetV.push_back(GEP->getOperand(i));
923 return true;
924}
925
926// Takes a RelocatedBase (base pointer relocation instruction) and Targets to
927// replace, computes a replacement, and affects it.
928static bool
Manuel Jacob83eefa62016-01-05 04:03:00 +0000929simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase,
930 const SmallVectorImpl<GCRelocateInst *> &Targets) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000931 bool MadeChange = false;
Serguei Katkov9e5604d2017-08-17 05:48:30 +0000932 // We must ensure the relocation of derived pointer is defined after
933 // relocation of base pointer. If we find a relocation corresponding to base
934 // defined earlier than relocation of base then we move relocation of base
935 // right before found relocation. We consider only relocation in the same
936 // basic block as relocation of base. Relocations from other basic block will
937 // be skipped by optimization and we do not care about them.
938 for (auto R = RelocatedBase->getParent()->getFirstInsertionPt();
939 &*R != RelocatedBase; ++R)
940 if (auto RI = dyn_cast<GCRelocateInst>(R))
941 if (RI->getStatepoint() == RelocatedBase->getStatepoint())
942 if (RI->getBasePtrIndex() == RelocatedBase->getBasePtrIndex()) {
943 RelocatedBase->moveBefore(RI);
944 break;
945 }
946
Manuel Jacob83eefa62016-01-05 04:03:00 +0000947 for (GCRelocateInst *ToReplace : Targets) {
948 assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000949 "Not relocating a derived object of the original base object");
Manuel Jacob83eefa62016-01-05 04:03:00 +0000950 if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000951 // A duplicate relocate call. TODO: coalesce duplicates.
952 continue;
953 }
954
Igor Laevskyf637b4a2015-11-03 18:37:40 +0000955 if (RelocatedBase->getParent() != ToReplace->getParent()) {
956 // Base and derived relocates are in different basic blocks.
957 // In this case transform is only valid when base dominates derived
958 // relocate. However it would be too expensive to check dominance
959 // for each such relocate, so we skip the whole transformation.
960 continue;
961 }
962
Manuel Jacob83eefa62016-01-05 04:03:00 +0000963 Value *Base = ToReplace->getBasePtr();
964 auto Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000965 if (!Derived || Derived->getPointerOperand() != Base)
966 continue;
967
968 SmallVector<Value *, 2> OffsetV;
969 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
970 continue;
971
972 // Create a Builder and replace the target callsite with a gep
Sanjay Patel545a4562016-01-20 18:59:16 +0000973 assert(RelocatedBase->getNextNode() &&
974 "Should always have one since it's not a terminator");
Sanjoy Das3d705e32015-05-11 23:47:30 +0000975
976 // Insert after RelocatedBase
977 IRBuilder<> Builder(RelocatedBase->getNextNode());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000978 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
Sanjoy Das89c54912015-05-11 18:49:34 +0000979
980 // If gc_relocate does not match the actual type, cast it to the right type.
981 // In theory, there must be a bitcast after gc_relocate if the type does not
982 // match, and we should reuse it to get the derived pointer. But it could be
983 // cases like this:
984 // bb1:
985 // ...
986 // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
987 // br label %merge
988 //
989 // bb2:
990 // ...
991 // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
992 // br label %merge
993 //
994 // merge:
995 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
996 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
997 //
998 // In this case, we can not find the bitcast any more. So we insert a new bitcast
999 // no matter there is already one or not. In this way, we can handle all cases, and
1000 // the extra bitcast should be optimized away in later passes.
Manuel Jacob5b90b142015-12-19 18:38:42 +00001001 Value *ActualRelocatedBase = RelocatedBase;
Sanjoy Das89c54912015-05-11 18:49:34 +00001002 if (RelocatedBase->getType() != Base->getType()) {
1003 ActualRelocatedBase =
Manuel Jacob5b90b142015-12-19 18:38:42 +00001004 Builder.CreateBitCast(RelocatedBase, Base->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +00001005 }
David Blaikie68d535c2015-03-24 22:38:16 +00001006 Value *Replacement = Builder.CreateGEP(
Sanjoy Das89c54912015-05-11 18:49:34 +00001007 Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001008 Replacement->takeName(ToReplace);
Sanjoy Das89c54912015-05-11 18:49:34 +00001009 // If the newly generated derived pointer's type does not match the original derived
1010 // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
Manuel Jacob5b90b142015-12-19 18:38:42 +00001011 Value *ActualReplacement = Replacement;
1012 if (Replacement->getType() != ToReplace->getType()) {
Sanjoy Das89c54912015-05-11 18:49:34 +00001013 ActualReplacement =
Manuel Jacob5b90b142015-12-19 18:38:42 +00001014 Builder.CreateBitCast(Replacement, ToReplace->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +00001015 }
1016 ToReplace->replaceAllUsesWith(ActualReplacement);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001017 ToReplace->eraseFromParent();
1018
1019 MadeChange = true;
1020 }
1021 return MadeChange;
1022}
1023
1024// Turns this:
1025//
1026// %base = ...
1027// %ptr = gep %base + 15
1028// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1029// %base' = relocate(%tok, i32 4, i32 4)
1030// %ptr' = relocate(%tok, i32 4, i32 5)
1031// %val = load %ptr'
1032//
1033// into this:
1034//
1035// %base = ...
1036// %ptr = gep %base + 15
1037// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1038// %base' = gc.relocate(%tok, i32 4, i32 4)
1039// %ptr' = gep %base' + 15
1040// %val = load %ptr'
1041bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
1042 bool MadeChange = false;
Manuel Jacob83eefa62016-01-05 04:03:00 +00001043 SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001044
1045 for (auto *U : I.users())
Manuel Jacob83eefa62016-01-05 04:03:00 +00001046 if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001047 // Collect all the relocate calls associated with a statepoint
Manuel Jacob83eefa62016-01-05 04:03:00 +00001048 AllRelocateCalls.push_back(Relocate);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001049
1050 // We need atleast one base pointer relocation + one derived pointer
1051 // relocation to mangle
1052 if (AllRelocateCalls.size() < 2)
1053 return false;
1054
1055 // RelocateInstMap is a mapping from the base relocate instruction to the
1056 // corresponding derived relocate instructions
Manuel Jacob83eefa62016-01-05 04:03:00 +00001057 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001058 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
1059 if (RelocateInstMap.empty())
1060 return false;
1061
1062 for (auto &Item : RelocateInstMap)
1063 // Item.first is the RelocatedBase to offset against
1064 // Item.second is the vector of Targets to replace
1065 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
1066 return MadeChange;
1067}
1068
Sanjay Patel7d8260f2019-03-10 18:42:30 +00001069/// Sink the specified cast instruction into its user blocks.
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001070static bool SinkCast(CastInst *CI) {
Chris Lattnerf2836d12007-03-31 04:06:36 +00001071 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001072
Chris Lattnerf2836d12007-03-31 04:06:36 +00001073 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001074 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001075
Chris Lattnerf2836d12007-03-31 04:06:36 +00001076 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001077 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Chris Lattnerf2836d12007-03-31 04:06:36 +00001078 UI != E; ) {
1079 Use &TheUse = UI.getUse();
1080 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +00001081
Chris Lattnerf2836d12007-03-31 04:06:36 +00001082 // Figure out which BB this cast is used in. For PHI's this is the
1083 // appropriate predecessor block.
1084 BasicBlock *UserBB = User->getParent();
1085 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001086 UserBB = PN->getIncomingBlock(TheUse);
Chris Lattnerf2836d12007-03-31 04:06:36 +00001087 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001088
Chris Lattnerf2836d12007-03-31 04:06:36 +00001089 // Preincrement use iterator so we don't invalidate it.
1090 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001091
David Majnemer0c80e2e2016-04-27 19:36:38 +00001092 // The first insertion point of a block containing an EH pad is after the
1093 // pad. If the pad is the user, we cannot sink the cast past the pad.
1094 if (User->isEHPad())
1095 continue;
1096
Andrew Kaylord0430e82015-11-23 19:16:15 +00001097 // If the block selected to receive the cast is an EH pad that does not
1098 // allow non-PHI instructions before the terminator, we can't sink the
1099 // cast.
1100 if (UserBB->getTerminator()->isEHPad())
1101 continue;
1102
Chris Lattnerf2836d12007-03-31 04:06:36 +00001103 // If this user is in the same block as the cast, don't change the cast.
1104 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001105
Chris Lattnerf2836d12007-03-31 04:06:36 +00001106 // If we have already inserted a cast into this block, use it.
1107 CastInst *&InsertedCast = InsertedCasts[UserBB];
1108
1109 if (!InsertedCast) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00001110 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001111 assert(InsertPt != UserBB->end());
1112 InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
1113 CI->getType(), "", &*InsertPt);
Vedant Kumar9374c042018-05-23 22:03:48 +00001114 InsertedCast->setDebugLoc(CI->getDebugLoc());
Chris Lattnerf2836d12007-03-31 04:06:36 +00001115 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001116
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001117 // Replace a use of the cast with a use of the new cast.
Chris Lattnerf2836d12007-03-31 04:06:36 +00001118 TheUse = InsertedCast;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001119 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +00001120 ++NumCastUses;
Chris Lattnerf2836d12007-03-31 04:06:36 +00001121 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001122
Chris Lattnerf2836d12007-03-31 04:06:36 +00001123 // If we removed all uses, nuke the cast.
Duncan Sandsafa84da42008-01-20 16:51:46 +00001124 if (CI->use_empty()) {
Adrian Prantl261ac8b2017-11-03 21:55:03 +00001125 salvageDebugInfo(*CI);
Chris Lattnerf2836d12007-03-31 04:06:36 +00001126 CI->eraseFromParent();
Duncan Sandsafa84da42008-01-20 16:51:46 +00001127 MadeChange = true;
1128 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001129
Chris Lattnerf2836d12007-03-31 04:06:36 +00001130 return MadeChange;
1131}
1132
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001133/// If the specified cast instruction is a noop copy (e.g. it's casting from
1134/// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
1135/// reduce the number of virtual registers that must be created and coalesced.
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001136///
1137/// Return true if any changes are made.
Mehdi Amini44ede332015-07-09 02:09:04 +00001138static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
1139 const DataLayout &DL) {
Justin Lebar3e50a5b2016-11-21 22:49:15 +00001140 // Sink only "cheap" (or nop) address-space casts. This is a weaker condition
1141 // than sinking only nop casts, but is helpful on some platforms.
1142 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(CI)) {
1143 if (!TLI.isCheapAddrSpaceCast(ASC->getSrcAddressSpace(),
1144 ASC->getDestAddressSpace()))
1145 return false;
1146 }
1147
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001148 // If this is a noop copy,
Mehdi Amini44ede332015-07-09 02:09:04 +00001149 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
1150 EVT DstVT = TLI.getValueType(DL, CI->getType());
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001151
1152 // This is an fp<->int conversion?
1153 if (SrcVT.isInteger() != DstVT.isInteger())
1154 return false;
1155
1156 // If this is an extension, it will be a zero or sign extension, which
1157 // isn't a noop.
1158 if (SrcVT.bitsLT(DstVT)) return false;
1159
1160 // If these values will be promoted, find out what they will be promoted
1161 // to. This helps us consider truncates on PPC as noop copies when they
1162 // are.
1163 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
1164 TargetLowering::TypePromoteInteger)
1165 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
1166 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
1167 TargetLowering::TypePromoteInteger)
1168 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
1169
1170 // If, after promotion, these are the same types, this is a noop copy.
1171 if (SrcVT != DstVT)
1172 return false;
1173
1174 return SinkCast(CI);
1175}
1176
Teresa Johnson4dc85192019-03-24 15:18:50 +00001177bool CodeGenPrepare::replaceMathCmpWithIntrinsic(BinaryOperator *BO,
1178 CmpInst *Cmp,
Teresa Johnson3bd4b5a2019-03-25 18:38:48 +00001179 Intrinsic::ID IID) {
Sanjay Patelffe1cf52019-02-22 20:20:24 +00001180 // We allow matching the canonical IR (add X, C) back to (usubo X, -C).
Sanjay Pateld8b4efc2019-02-18 23:33:05 +00001181 Value *Arg0 = BO->getOperand(0);
1182 Value *Arg1 = BO->getOperand(1);
Sanjay Pateld8b4efc2019-02-18 23:33:05 +00001183 if (BO->getOpcode() == Instruction::Add &&
1184 IID == Intrinsic::usub_with_overflow) {
1185 assert(isa<Constant>(Arg1) && "Unexpected input for usubo");
1186 Arg1 = ConstantExpr::getNeg(cast<Constant>(Arg1));
1187 }
1188
Sanjay Patelffe1cf52019-02-22 20:20:24 +00001189 Instruction *InsertPt;
1190 if (BO->hasOneUse() && BO->user_back() == Cmp) {
1191 // If the math is only used by the compare, insert at the compare to keep
1192 // the condition in the same block as its users. (CGP aggressively sinks
1193 // compares to help out SDAG.)
1194 InsertPt = Cmp;
1195 } else {
1196 // The math and compare may be independent instructions. Check dominance to
1197 // determine the insertion point for the intrinsic.
Teresa Johnson3bd4b5a2019-03-25 18:38:48 +00001198 bool MathDominates = getDT(*BO->getFunction()).dominates(BO, Cmp);
1199 if (!MathDominates && !getDT(*BO->getFunction()).dominates(Cmp, BO))
Sanjay Patelffe1cf52019-02-22 20:20:24 +00001200 return false;
Sam Parker52760bf2019-03-11 13:19:46 +00001201
Sanjay Patela2250e92019-03-20 16:47:53 +00001202 BasicBlock *MathBB = BO->getParent(), *CmpBB = Cmp->getParent();
1203 if (MathBB != CmpBB) {
Sanjay Pateld47eac52019-03-21 13:57:07 +00001204 // Avoid hoisting an extra op into a dominating block and creating a
1205 // potentially longer critical path.
1206 if (!MathDominates)
1207 return false;
1208 // Check that the insertion doesn't create a value that is live across
1209 // more than two blocks, so to minimise the increase in register pressure.
Sanjay Patela2250e92019-03-20 16:47:53 +00001210 BasicBlock *Dominator = MathDominates ? MathBB : CmpBB;
1211 BasicBlock *Dominated = MathDominates ? CmpBB : MathBB;
Sam Parker52760bf2019-03-11 13:19:46 +00001212 auto Successors = successors(Dominator);
1213 if (llvm::find(Successors, Dominated) == Successors.end())
1214 return false;
1215 }
1216
Sanjay Patelffe1cf52019-02-22 20:20:24 +00001217 InsertPt = MathDominates ? cast<Instruction>(BO) : cast<Instruction>(Cmp);
1218 }
1219
Sanjay Patelc00bdab42019-02-04 16:30:46 +00001220 IRBuilder<> Builder(InsertPt);
Sanjay Pateld8b4efc2019-02-18 23:33:05 +00001221 Value *MathOV = Builder.CreateBinaryIntrinsic(IID, Arg0, Arg1);
Sanjay Patelc00bdab42019-02-04 16:30:46 +00001222 Value *Math = Builder.CreateExtractValue(MathOV, 0, "math");
1223 Value *OV = Builder.CreateExtractValue(MathOV, 1, "ov");
1224 BO->replaceAllUsesWith(Math);
1225 Cmp->replaceAllUsesWith(OV);
1226 BO->eraseFromParent();
1227 Cmp->eraseFromParent();
Sanjay Patelffe1cf52019-02-22 20:20:24 +00001228 return true;
Sanjay Patelc00bdab42019-02-04 16:30:46 +00001229}
1230
Sanjay Patelcb04ba02019-02-24 15:31:27 +00001231/// Match special-case patterns that check for unsigned add overflow.
1232static bool matchUAddWithOverflowConstantEdgeCases(CmpInst *Cmp,
1233 BinaryOperator *&Add) {
1234 // Add = add A, 1; Cmp = icmp eq A,-1 (overflow if A is max val)
1235 // Add = add A,-1; Cmp = icmp ne A, 0 (overflow if A is non-zero)
1236 Value *A = Cmp->getOperand(0), *B = Cmp->getOperand(1);
Sanjay Patel3b2d0bc2019-03-04 22:47:13 +00001237
1238 // We are not expecting non-canonical/degenerate code. Just bail out.
1239 if (isa<Constant>(A))
1240 return false;
1241
Sanjay Patelcb04ba02019-02-24 15:31:27 +00001242 ICmpInst::Predicate Pred = Cmp->getPredicate();
1243 if (Pred == ICmpInst::ICMP_EQ && match(B, m_AllOnes()))
1244 B = ConstantInt::get(B->getType(), 1);
1245 else if (Pred == ICmpInst::ICMP_NE && match(B, m_ZeroInt()))
1246 B = ConstantInt::get(B->getType(), -1);
1247 else
1248 return false;
1249
1250 // Check the users of the variable operand of the compare looking for an add
1251 // with the adjusted constant.
1252 for (User *U : A->users()) {
1253 if (match(U, m_Add(m_Specific(A), m_Specific(B)))) {
1254 Add = cast<BinaryOperator>(U);
1255 return true;
1256 }
1257 }
1258 return false;
1259}
1260
Sanjay Patel00fcc742019-02-03 13:48:03 +00001261/// Try to combine the compare into a call to the llvm.uadd.with.overflow
1262/// intrinsic. Return true if any changes were made.
Teresa Johnson3bd4b5a2019-03-25 18:38:48 +00001263bool CodeGenPrepare::combineToUAddWithOverflow(CmpInst *Cmp,
Teresa Johnson4dc85192019-03-24 15:18:50 +00001264 bool &ModifiedDT) {
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001265 Value *A, *B;
Sanjay Patelc00bdab42019-02-04 16:30:46 +00001266 BinaryOperator *Add;
1267 if (!match(Cmp, m_UAddWithOverflow(m_Value(A), m_Value(B), m_BinOp(Add))))
Sanjay Patelcb04ba02019-02-24 15:31:27 +00001268 if (!matchUAddWithOverflowConstantEdgeCases(Cmp, Add))
1269 return false;
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001270
Teresa Johnson4dc85192019-03-24 15:18:50 +00001271 if (!TLI->shouldFormOverflowOp(ISD::UADDO,
1272 TLI->getValueType(*DL, Add->getType())))
Sanjay Patel84ceae62019-02-03 17:53:09 +00001273 return false;
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001274
Sanjay Patelc00bdab42019-02-04 16:30:46 +00001275 // We don't want to move around uses of condition values this late, so we
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001276 // check if it is legal to create the call to the intrinsic in the basic
Sanjay Patelc00bdab42019-02-04 16:30:46 +00001277 // block containing the icmp.
1278 if (Add->getParent() != Cmp->getParent() && !Add->hasOneUse())
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001279 return false;
1280
Teresa Johnson3bd4b5a2019-03-25 18:38:48 +00001281 if (!replaceMathCmpWithIntrinsic(Add, Cmp, Intrinsic::uadd_with_overflow))
Sanjay Patelffe1cf52019-02-22 20:20:24 +00001282 return false;
1283
1284 // Reset callers - do not crash by iterating over a dead instruction.
1285 ModifiedDT = true;
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001286 return true;
1287}
1288
Teresa Johnson3bd4b5a2019-03-25 18:38:48 +00001289bool CodeGenPrepare::combineToUSubWithOverflow(CmpInst *Cmp,
Teresa Johnson4dc85192019-03-24 15:18:50 +00001290 bool &ModifiedDT) {
Sanjay Patel2c9275a2019-03-14 23:14:31 +00001291 // We are not expecting non-canonical/degenerate code. Just bail out.
Sanjay Pateld8b4efc2019-02-18 23:33:05 +00001292 Value *A = Cmp->getOperand(0), *B = Cmp->getOperand(1);
Sanjay Patel2c9275a2019-03-14 23:14:31 +00001293 if (isa<Constant>(A) && isa<Constant>(B))
1294 return false;
1295
1296 // Convert (A u> B) to (A u< B) to simplify pattern matching.
Sanjay Pateld8b4efc2019-02-18 23:33:05 +00001297 ICmpInst::Predicate Pred = Cmp->getPredicate();
1298 if (Pred == ICmpInst::ICMP_UGT) {
1299 std::swap(A, B);
1300 Pred = ICmpInst::ICMP_ULT;
1301 }
1302 // Convert special-case: (A == 0) is the same as (A u< 1).
1303 if (Pred == ICmpInst::ICMP_EQ && match(B, m_ZeroInt())) {
1304 B = ConstantInt::get(B->getType(), 1);
1305 Pred = ICmpInst::ICMP_ULT;
1306 }
Sanjay Patel198cc302019-02-20 21:23:04 +00001307 // Convert special-case: (A != 0) is the same as (0 u< A).
1308 if (Pred == ICmpInst::ICMP_NE && match(B, m_ZeroInt())) {
1309 std::swap(A, B);
1310 Pred = ICmpInst::ICMP_ULT;
1311 }
Sanjay Pateld8b4efc2019-02-18 23:33:05 +00001312 if (Pred != ICmpInst::ICMP_ULT)
1313 return false;
1314
1315 // Walk the users of a variable operand of a compare looking for a subtract or
1316 // add with that same operand. Also match the 2nd operand of the compare to
1317 // the add/sub, but that may be a negated constant operand of an add.
1318 Value *CmpVariableOperand = isa<Constant>(A) ? B : A;
1319 BinaryOperator *Sub = nullptr;
1320 for (User *U : CmpVariableOperand->users()) {
1321 // A - B, A u< B --> usubo(A, B)
1322 if (match(U, m_Sub(m_Specific(A), m_Specific(B)))) {
1323 Sub = cast<BinaryOperator>(U);
1324 break;
1325 }
1326
1327 // A + (-C), A u< C (canonicalized form of (sub A, C))
1328 const APInt *CmpC, *AddC;
1329 if (match(U, m_Add(m_Specific(A), m_APInt(AddC))) &&
1330 match(B, m_APInt(CmpC)) && *AddC == -(*CmpC)) {
1331 Sub = cast<BinaryOperator>(U);
1332 break;
1333 }
1334 }
1335 if (!Sub)
1336 return false;
1337
Teresa Johnson4dc85192019-03-24 15:18:50 +00001338 if (!TLI->shouldFormOverflowOp(ISD::USUBO,
1339 TLI->getValueType(*DL, Sub->getType())))
Sanjay Pateld8b4efc2019-02-18 23:33:05 +00001340 return false;
1341
Teresa Johnson3bd4b5a2019-03-25 18:38:48 +00001342 if (!replaceMathCmpWithIntrinsic(Sub, Cmp, Intrinsic::usub_with_overflow))
Sanjay Pateld8b4efc2019-02-18 23:33:05 +00001343 return false;
Sanjay Patelffe1cf52019-02-22 20:20:24 +00001344
Sanjay Pateld8b4efc2019-02-18 23:33:05 +00001345 // Reset callers - do not crash by iterating over a dead instruction.
1346 ModifiedDT = true;
1347 return true;
1348}
1349
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001350/// Sink the given CmpInst into user blocks to reduce the number of virtual
1351/// registers that must be created and coalesced. This is a clear win except on
1352/// targets with multiple condition code registers (PowerPC), where it might
1353/// lose; some adjustment may be wanted there.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001354///
1355/// Return true if any changes are made.
Sanjay Patel00fcc742019-02-03 13:48:03 +00001356static bool sinkCmpExpression(CmpInst *Cmp, const TargetLowering &TLI) {
1357 if (TLI.hasMultipleConditionRegisters())
1358 return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001359
Peter Zotov0b6d7bc2016-04-03 16:36:17 +00001360 // Avoid sinking soft-FP comparisons, since this can move them into a loop.
Sanjay Patel00fcc742019-02-03 13:48:03 +00001361 if (TLI.useSoftFloat() && isa<FCmpInst>(Cmp))
Peter Zotov0b6d7bc2016-04-03 16:36:17 +00001362 return false;
1363
1364 // Only insert a cmp in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001365 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001366
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001367 bool MadeChange = false;
Sanjay Patel00fcc742019-02-03 13:48:03 +00001368 for (Value::user_iterator UI = Cmp->user_begin(), E = Cmp->user_end();
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001369 UI != E; ) {
1370 Use &TheUse = UI.getUse();
1371 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +00001372
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001373 // Preincrement use iterator so we don't invalidate it.
1374 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001375
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001376 // Don't bother for PHI nodes.
1377 if (isa<PHINode>(User))
1378 continue;
1379
1380 // Figure out which BB this cmp is used in.
1381 BasicBlock *UserBB = User->getParent();
Sanjay Patel00fcc742019-02-03 13:48:03 +00001382 BasicBlock *DefBB = Cmp->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001383
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001384 // If this user is in the same block as the cmp, don't change the cmp.
1385 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001386
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001387 // If we have already inserted a cmp into this block, use it.
1388 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
1389
1390 if (!InsertedCmp) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00001391 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001392 assert(InsertPt != UserBB->end());
Eric Christopherc1ea1492008-09-24 05:32:41 +00001393 InsertedCmp =
Sanjay Patel00fcc742019-02-03 13:48:03 +00001394 CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(),
1395 Cmp->getOperand(0), Cmp->getOperand(1), "",
1396 &*InsertPt);
Wolfgang Piebe51bede2016-10-06 21:43:45 +00001397 // Propagate the debug info.
Sanjay Patel00fcc742019-02-03 13:48:03 +00001398 InsertedCmp->setDebugLoc(Cmp->getDebugLoc());
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001399 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001400
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001401 // Replace a use of the cmp with a use of the new cmp.
1402 TheUse = InsertedCmp;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001403 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +00001404 ++NumCmpUses;
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001405 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001406
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001407 // If we removed all uses, nuke the cmp.
Sanjay Patel00fcc742019-02-03 13:48:03 +00001408 if (Cmp->use_empty()) {
1409 Cmp->eraseFromParent();
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001410 MadeChange = true;
1411 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001412
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001413 return MadeChange;
1414}
1415
Teresa Johnson3bd4b5a2019-03-25 18:38:48 +00001416bool CodeGenPrepare::optimizeCmp(CmpInst *Cmp, bool &ModifiedDT) {
Teresa Johnson4dc85192019-03-24 15:18:50 +00001417 if (sinkCmpExpression(Cmp, *TLI))
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001418 return true;
1419
Teresa Johnson3bd4b5a2019-03-25 18:38:48 +00001420 if (combineToUAddWithOverflow(Cmp, ModifiedDT))
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001421 return true;
1422
Teresa Johnson3bd4b5a2019-03-25 18:38:48 +00001423 if (combineToUSubWithOverflow(Cmp, ModifiedDT))
Sanjay Pateld8b4efc2019-02-18 23:33:05 +00001424 return true;
1425
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001426 return false;
1427}
1428
Geoff Berry5d534b62017-02-21 18:53:14 +00001429/// Duplicate and sink the given 'and' instruction into user blocks where it is
1430/// used in a compare to allow isel to generate better code for targets where
1431/// this operation can be combined.
1432///
1433/// Return true if any changes are made.
1434static bool sinkAndCmp0Expression(Instruction *AndI,
1435 const TargetLowering &TLI,
1436 SetOfInstrs &InsertedInsts) {
1437 // Double-check that we're not trying to optimize an instruction that was
1438 // already optimized by some other part of this pass.
1439 assert(!InsertedInsts.count(AndI) &&
1440 "Attempting to optimize already optimized and instruction");
1441 (void) InsertedInsts;
1442
1443 // Nothing to do for single use in same basic block.
1444 if (AndI->hasOneUse() &&
1445 AndI->getParent() == cast<Instruction>(*AndI->user_begin())->getParent())
1446 return false;
1447
1448 // Try to avoid cases where sinking/duplicating is likely to increase register
1449 // pressure.
1450 if (!isa<ConstantInt>(AndI->getOperand(0)) &&
1451 !isa<ConstantInt>(AndI->getOperand(1)) &&
1452 AndI->getOperand(0)->hasOneUse() && AndI->getOperand(1)->hasOneUse())
1453 return false;
1454
1455 for (auto *U : AndI->users()) {
1456 Instruction *User = cast<Instruction>(U);
1457
Sanjay Patel7d8260f2019-03-10 18:42:30 +00001458 // Only sink 'and' feeding icmp with 0.
Geoff Berry5d534b62017-02-21 18:53:14 +00001459 if (!isa<ICmpInst>(User))
1460 return false;
1461
1462 auto *CmpC = dyn_cast<ConstantInt>(User->getOperand(1));
1463 if (!CmpC || !CmpC->isZero())
1464 return false;
1465 }
1466
1467 if (!TLI.isMaskAndCmp0FoldingBeneficial(*AndI))
1468 return false;
1469
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001470 LLVM_DEBUG(dbgs() << "found 'and' feeding only icmp 0;\n");
1471 LLVM_DEBUG(AndI->getParent()->dump());
Geoff Berry5d534b62017-02-21 18:53:14 +00001472
1473 // Push the 'and' into the same block as the icmp 0. There should only be
1474 // one (icmp (and, 0)) in each block, since CSE/GVN should have removed any
1475 // others, so we don't need to keep track of which BBs we insert into.
1476 for (Value::user_iterator UI = AndI->user_begin(), E = AndI->user_end();
1477 UI != E; ) {
1478 Use &TheUse = UI.getUse();
1479 Instruction *User = cast<Instruction>(*UI);
1480
1481 // Preincrement use iterator so we don't invalidate it.
1482 ++UI;
1483
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001484 LLVM_DEBUG(dbgs() << "sinking 'and' use: " << *User << "\n");
Geoff Berry5d534b62017-02-21 18:53:14 +00001485
1486 // Keep the 'and' in the same place if the use is already in the same block.
1487 Instruction *InsertPt =
1488 User->getParent() == AndI->getParent() ? AndI : User;
1489 Instruction *InsertedAnd =
1490 BinaryOperator::Create(Instruction::And, AndI->getOperand(0),
1491 AndI->getOperand(1), "", InsertPt);
1492 // Propagate the debug info.
1493 InsertedAnd->setDebugLoc(AndI->getDebugLoc());
1494
1495 // Replace a use of the 'and' with a use of the new 'and'.
1496 TheUse = InsertedAnd;
1497 ++NumAndUses;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001498 LLVM_DEBUG(User->getParent()->dump());
Geoff Berry5d534b62017-02-21 18:53:14 +00001499 }
1500
1501 // We removed all uses, nuke the and.
1502 AndI->eraseFromParent();
1503 return true;
1504}
1505
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001506/// Check if the candidates could be combined with a shift instruction, which
1507/// includes:
Yi Jiangd069f632014-04-21 19:34:27 +00001508/// 1. Truncate instruction
1509/// 2. And instruction and the imm is a mask of the low bits:
1510/// imm & (imm+1) == 0
Benjamin Kramer322053c2014-04-27 14:54:59 +00001511static bool isExtractBitsCandidateUse(Instruction *User) {
Yi Jiangd069f632014-04-21 19:34:27 +00001512 if (!isa<TruncInst>(User)) {
1513 if (User->getOpcode() != Instruction::And ||
1514 !isa<ConstantInt>(User->getOperand(1)))
1515 return false;
1516
Quentin Colombetd4f44692014-04-22 01:20:34 +00001517 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
Yi Jiangd069f632014-04-21 19:34:27 +00001518
Quentin Colombetd4f44692014-04-22 01:20:34 +00001519 if ((Cimm & (Cimm + 1)).getBoolValue())
Yi Jiangd069f632014-04-21 19:34:27 +00001520 return false;
1521 }
1522 return true;
1523}
1524
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001525/// Sink both shift and truncate instruction to the use of truncate's BB.
Benjamin Kramer322053c2014-04-27 14:54:59 +00001526static bool
Yi Jiangd069f632014-04-21 19:34:27 +00001527SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
1528 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
Mehdi Amini44ede332015-07-09 02:09:04 +00001529 const TargetLowering &TLI, const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001530 BasicBlock *UserBB = User->getParent();
1531 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
1532 TruncInst *TruncI = dyn_cast<TruncInst>(User);
1533 bool MadeChange = false;
1534
1535 for (Value::user_iterator TruncUI = TruncI->user_begin(),
1536 TruncE = TruncI->user_end();
1537 TruncUI != TruncE;) {
1538
1539 Use &TruncTheUse = TruncUI.getUse();
1540 Instruction *TruncUser = cast<Instruction>(*TruncUI);
1541 // Preincrement use iterator so we don't invalidate it.
1542
1543 ++TruncUI;
1544
1545 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
1546 if (!ISDOpcode)
1547 continue;
1548
Tim Northovere2239ff2014-07-29 10:20:22 +00001549 // If the use is actually a legal node, there will not be an
1550 // implicit truncate.
1551 // FIXME: always querying the result type is just an
1552 // approximation; some nodes' legality is determined by the
1553 // operand or other means. There's no good way to find out though.
Ahmed Bougacha0788d492014-11-12 22:16:55 +00001554 if (TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00001555 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
Yi Jiangd069f632014-04-21 19:34:27 +00001556 continue;
1557
1558 // Don't bother for PHI nodes.
1559 if (isa<PHINode>(TruncUser))
1560 continue;
1561
1562 BasicBlock *TruncUserBB = TruncUser->getParent();
1563
1564 if (UserBB == TruncUserBB)
1565 continue;
1566
1567 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
1568 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
1569
1570 if (!InsertedShift && !InsertedTrunc) {
1571 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001572 assert(InsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001573 // Sink the shift
1574 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001575 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1576 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001577 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001578 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1579 "", &*InsertPt);
Vedant Kumar1b02dad2018-09-15 04:08:52 +00001580 InsertedShift->setDebugLoc(ShiftI->getDebugLoc());
Yi Jiangd069f632014-04-21 19:34:27 +00001581
1582 // Sink the trunc
1583 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
1584 TruncInsertPt++;
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001585 assert(TruncInsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001586
1587 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001588 TruncI->getType(), "", &*TruncInsertPt);
Vedant Kumar1b02dad2018-09-15 04:08:52 +00001589 InsertedTrunc->setDebugLoc(TruncI->getDebugLoc());
Yi Jiangd069f632014-04-21 19:34:27 +00001590
1591 MadeChange = true;
1592
1593 TruncTheUse = InsertedTrunc;
1594 }
1595 }
1596 return MadeChange;
1597}
1598
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001599/// Sink the shift *right* instruction into user blocks if the uses could
1600/// potentially be combined with this shift instruction and generate BitExtract
1601/// instruction. It will only be applied if the architecture supports BitExtract
1602/// instruction. Here is an example:
Yi Jiangd069f632014-04-21 19:34:27 +00001603/// BB1:
1604/// %x.extract.shift = lshr i64 %arg1, 32
1605/// BB2:
1606/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
1607/// ==>
1608///
1609/// BB2:
1610/// %x.extract.shift.1 = lshr i64 %arg1, 32
1611/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
1612///
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00001613/// CodeGen will recognize the pattern in BB2 and generate BitExtract
Yi Jiangd069f632014-04-21 19:34:27 +00001614/// instruction.
1615/// Return true if any changes are made.
1616static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
Mehdi Amini44ede332015-07-09 02:09:04 +00001617 const TargetLowering &TLI,
1618 const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001619 BasicBlock *DefBB = ShiftI->getParent();
1620
1621 /// Only insert instructions in each block once.
1622 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
1623
Mehdi Amini44ede332015-07-09 02:09:04 +00001624 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
Yi Jiangd069f632014-04-21 19:34:27 +00001625
1626 bool MadeChange = false;
1627 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
1628 UI != E;) {
1629 Use &TheUse = UI.getUse();
1630 Instruction *User = cast<Instruction>(*UI);
1631 // Preincrement use iterator so we don't invalidate it.
1632 ++UI;
1633
1634 // Don't bother for PHI nodes.
1635 if (isa<PHINode>(User))
1636 continue;
1637
1638 if (!isExtractBitsCandidateUse(User))
1639 continue;
1640
1641 BasicBlock *UserBB = User->getParent();
1642
1643 if (UserBB == DefBB) {
1644 // If the shift and truncate instruction are in the same BB. The use of
1645 // the truncate(TruncUse) may still introduce another truncate if not
1646 // legal. In this case, we would like to sink both shift and truncate
1647 // instruction to the BB of TruncUse.
1648 // for example:
1649 // BB1:
1650 // i64 shift.result = lshr i64 opnd, imm
1651 // trunc.result = trunc shift.result to i16
1652 //
1653 // BB2:
1654 // ----> We will have an implicit truncate here if the architecture does
1655 // not have i16 compare.
1656 // cmp i16 trunc.result, opnd2
1657 //
1658 if (isa<TruncInst>(User) && shiftIsLegal
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00001659 // If the type of the truncate is legal, no truncate will be
Yi Jiangd069f632014-04-21 19:34:27 +00001660 // introduced in other basic blocks.
Mehdi Amini44ede332015-07-09 02:09:04 +00001661 &&
1662 (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
Yi Jiangd069f632014-04-21 19:34:27 +00001663 MadeChange =
Mehdi Amini44ede332015-07-09 02:09:04 +00001664 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
Yi Jiangd069f632014-04-21 19:34:27 +00001665
1666 continue;
1667 }
1668 // If we have already inserted a shift into this block, use it.
1669 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
1670
1671 if (!InsertedShift) {
1672 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001673 assert(InsertPt != UserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001674
1675 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001676 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1677 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001678 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001679 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1680 "", &*InsertPt);
Vedant Kumar1b02dad2018-09-15 04:08:52 +00001681 InsertedShift->setDebugLoc(ShiftI->getDebugLoc());
Yi Jiangd069f632014-04-21 19:34:27 +00001682
1683 MadeChange = true;
1684 }
1685
1686 // Replace a use of the shift with a use of the new shift.
1687 TheUse = InsertedShift;
1688 }
1689
1690 // If we removed all uses, nuke the shift.
Vedant Kumar1b02dad2018-09-15 04:08:52 +00001691 if (ShiftI->use_empty()) {
1692 salvageDebugInfo(*ShiftI);
Yi Jiangd069f632014-04-21 19:34:27 +00001693 ShiftI->eraseFromParent();
Vedant Kumar1b02dad2018-09-15 04:08:52 +00001694 }
Yi Jiangd069f632014-04-21 19:34:27 +00001695
1696 return MadeChange;
1697}
1698
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001699/// If counting leading or trailing zeros is an expensive operation and a zero
1700/// input is defined, add a check for zero to avoid calling the intrinsic.
1701///
1702/// We want to transform:
1703/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
1704///
1705/// into:
1706/// entry:
1707/// %cmpz = icmp eq i64 %A, 0
1708/// br i1 %cmpz, label %cond.end, label %cond.false
1709/// cond.false:
1710/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
1711/// br label %cond.end
1712/// cond.end:
1713/// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
1714///
1715/// If the transform is performed, return true and set ModifiedDT to true.
1716static bool despeculateCountZeros(IntrinsicInst *CountZeros,
1717 const TargetLowering *TLI,
1718 const DataLayout *DL,
1719 bool &ModifiedDT) {
1720 if (!TLI || !DL)
1721 return false;
1722
1723 // If a zero input is undefined, it doesn't make sense to despeculate that.
1724 if (match(CountZeros->getOperand(1), m_One()))
1725 return false;
1726
1727 // If it's cheap to speculate, there's nothing to do.
1728 auto IntrinsicID = CountZeros->getIntrinsicID();
1729 if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) ||
1730 (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz()))
1731 return false;
1732
1733 // Only handle legal scalar cases. Anything else requires too much work.
1734 Type *Ty = CountZeros->getType();
1735 unsigned SizeInBits = Ty->getPrimitiveSizeInBits();
Jun Bum Limbe11bdc2016-05-13 18:38:35 +00001736 if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSizeInBits())
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001737 return false;
1738
1739 // The intrinsic will be sunk behind a compare against zero and branch.
1740 BasicBlock *StartBlock = CountZeros->getParent();
1741 BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
1742
1743 // Create another block after the count zero intrinsic. A PHI will be added
1744 // in this block to select the result of the intrinsic or the bit-width
1745 // constant if the input to the intrinsic is zero.
1746 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
1747 BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
1748
1749 // Set up a builder to create a compare, conditional branch, and PHI.
1750 IRBuilder<> Builder(CountZeros->getContext());
1751 Builder.SetInsertPoint(StartBlock->getTerminator());
1752 Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
1753
1754 // Replace the unconditional branch that was created by the first split with
1755 // a compare against zero and a conditional branch.
1756 Value *Zero = Constant::getNullValue(Ty);
1757 Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz");
1758 Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
1759 StartBlock->getTerminator()->eraseFromParent();
1760
1761 // Create a PHI in the end block to select either the output of the intrinsic
1762 // or the bit width of the operand.
1763 Builder.SetInsertPoint(&EndBlock->front());
1764 PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
1765 CountZeros->replaceAllUsesWith(PN);
1766 Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
1767 PN->addIncoming(BitWidth, StartBlock);
1768 PN->addIncoming(CountZeros, CallBlock);
1769
1770 // We are explicitly handling the zero case, so we can set the intrinsic's
1771 // undefined zero argument to 'true'. This will also prevent reprocessing the
1772 // intrinsic; we only despeculate when a zero input is defined.
1773 CountZeros->setArgOperand(1, Builder.getTrue());
1774 ModifiedDT = true;
1775 return true;
1776}
1777
Sanjay Patel3b8974b2017-06-08 20:00:09 +00001778bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool &ModifiedDT) {
Chris Lattner7a277142011-01-15 07:14:54 +00001779 BasicBlock *BB = CI->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00001780
Chris Lattner7a277142011-01-15 07:14:54 +00001781 // Lower inline assembly if we can.
1782 // If we found an inline asm expession, and if the target knows how to
1783 // lower it to normal LLVM code, do so now.
1784 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
1785 if (TLI->ExpandInlineAsm(CI)) {
1786 // Avoid invalidating the iterator.
1787 CurInstIterator = BB->begin();
1788 // Avoid processing instructions out of order, which could cause
1789 // reuse before a value is defined.
1790 SunkAddrs.clear();
1791 return true;
1792 }
1793 // Sink address computing for memory operands into the block.
Sanjay Patelfc580a62015-09-21 23:03:16 +00001794 if (optimizeInlineAsmInst(CI))
Chris Lattner7a277142011-01-15 07:14:54 +00001795 return true;
1796 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001797
John Brawn0dbcd652015-03-18 12:01:59 +00001798 // Align the pointer arguments to this call if the target thinks it's a good
1799 // idea
1800 unsigned MinSize, PrefAlign;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001801 if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
John Brawn0dbcd652015-03-18 12:01:59 +00001802 for (auto &Arg : CI->arg_operands()) {
1803 // We want to align both objects whose address is used directly and
1804 // objects whose address is used in casts and GEPs, though it only makes
1805 // sense for GEPs if the offset is a multiple of the desired alignment and
1806 // if size - offset meets the size threshold.
1807 if (!Arg->getType()->isPointerTy())
1808 continue;
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00001809 APInt Offset(DL->getIndexSizeInBits(
Mehdi Amini4fe37982015-07-07 18:45:17 +00001810 cast<PointerType>(Arg->getType())->getAddressSpace()),
1811 0);
1812 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
John Brawn0dbcd652015-03-18 12:01:59 +00001813 uint64_t Offset2 = Offset.getLimitedValue();
John Brawne8fd6c82015-04-13 10:47:39 +00001814 if ((Offset2 & (PrefAlign-1)) != 0)
1815 continue;
John Brawn0dbcd652015-03-18 12:01:59 +00001816 AllocaInst *AI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001817 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
1818 DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
John Brawn0dbcd652015-03-18 12:01:59 +00001819 AI->setAlignment(PrefAlign);
John Brawne8fd6c82015-04-13 10:47:39 +00001820 // Global variables can only be aligned if they are defined in this
1821 // object (i.e. they are uniquely initialized in this object), and
1822 // over-aligning global variables that have an explicit section is
1823 // forbidden.
1824 GlobalVariable *GV;
James Y Knightac03dca2016-01-15 16:33:06 +00001825 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
Tim Northover918f0502016-07-18 18:28:52 +00001826 GV->getPointerAlignment(*DL) < PrefAlign &&
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001827 DL->getTypeAllocSize(GV->getValueType()) >=
Mehdi Amini4fe37982015-07-07 18:45:17 +00001828 MinSize + Offset2)
John Brawne8fd6c82015-04-13 10:47:39 +00001829 GV->setAlignment(PrefAlign);
John Brawn0dbcd652015-03-18 12:01:59 +00001830 }
1831 // If this is a memcpy (or similar) then we may be able to improve the
1832 // alignment
1833 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
Daniel Neilsonbe58a222018-01-31 17:24:53 +00001834 unsigned DestAlign = getKnownAlignment(MI->getDest(), *DL);
1835 if (DestAlign > MI->getDestAlignment())
1836 MI->setDestAlignment(DestAlign);
1837 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
1838 unsigned SrcAlign = getKnownAlignment(MTI->getSource(), *DL);
1839 if (SrcAlign > MTI->getSourceAlignment())
1840 MTI->setSourceAlignment(SrcAlign);
1841 }
John Brawn0dbcd652015-03-18 12:01:59 +00001842 }
1843 }
1844
Philip Reamesac115ed2016-03-09 23:13:12 +00001845 // If we have a cold call site, try to sink addressing computation into the
1846 // cold block. This interacts with our handling for loads and stores to
1847 // ensure that we can fold all uses of a potential addressing computation
1848 // into their uses. TODO: generalize this to work over profiling data
1849 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
1850 for (auto &Arg : CI->arg_operands()) {
1851 if (!Arg->getType()->isPointerTy())
1852 continue;
1853 unsigned AS = Arg->getType()->getPointerAddressSpace();
1854 return optimizeMemoryInst(CI, Arg, Arg->getType(), AS);
1855 }
Junmo Park6098cbb2016-03-11 07:05:32 +00001856
Eric Christopher4b7948e2010-03-11 02:41:03 +00001857 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001858 if (II) {
1859 switch (II->getIntrinsicID()) {
1860 default: break;
Philip Reamesede49dd2019-01-31 18:45:46 +00001861 case Intrinsic::experimental_widenable_condition: {
1862 // Give up on future widening oppurtunties so that we can fold away dead
1863 // paths and merge blocks before going into block-local instruction
1864 // selection.
1865 if (II->use_empty()) {
1866 II->eraseFromParent();
1867 return true;
1868 }
1869 Constant *RetVal = ConstantInt::getTrue(II->getContext());
1870 resetIteratorIfInvalidatedWhileCalling(BB, [&]() {
1871 replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
1872 });
1873 return true;
1874 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001875 case Intrinsic::objectsize: {
1876 // Lower all uses of llvm.objectsize.*
Erik Pilkington600e9de2019-01-30 20:34:35 +00001877 Value *RetVal =
George Burgess IV3f089142016-12-20 23:46:36 +00001878 lowerObjectSizeCall(II, *DL, TLInfo, /*MustSucceed=*/true);
Nadav Rotem465834c2012-07-24 10:51:42 +00001879
James Y Knight72f76bf2018-11-07 15:24:12 +00001880 resetIteratorIfInvalidatedWhileCalling(BB, [&]() {
1881 replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
1882 });
1883 return true;
1884 }
1885 case Intrinsic::is_constant: {
1886 // If is_constant hasn't folded away yet, lower it to false now.
1887 Constant *RetVal = ConstantInt::get(II->getType(), 0);
1888 resetIteratorIfInvalidatedWhileCalling(BB, [&]() {
1889 replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
1890 });
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001891 return true;
Chris Lattner86d56c62011-01-18 20:53:04 +00001892 }
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001893 case Intrinsic::aarch64_stlxr:
1894 case Intrinsic::aarch64_stxr: {
1895 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
1896 if (!ExtVal || !ExtVal->hasOneUse() ||
1897 ExtVal->getParent() == CI->getParent())
1898 return false;
1899 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
1900 ExtVal->moveBefore(CI);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00001901 // Mark this instruction as "inserted by CGP", so that other
1902 // optimizations don't touch it.
1903 InsertedInsts.insert(ExtVal);
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001904 return true;
1905 }
Florian Hahn3b251962019-02-05 10:27:40 +00001906
Piotr Padlewski5dde8092018-05-03 11:03:01 +00001907 case Intrinsic::launder_invariant_group:
Krzysztof Pszeniczny2bfe7592018-10-19 19:02:16 +00001908 case Intrinsic::strip_invariant_group: {
1909 Value *ArgVal = II->getArgOperand(0);
1910 auto it = LargeOffsetGEPMap.find(II);
1911 if (it != LargeOffsetGEPMap.end()) {
1912 // Merge entries in LargeOffsetGEPMap to reflect the RAUW.
1913 // Make sure not to have to deal with iterator invalidation
1914 // after possibly adding ArgVal to LargeOffsetGEPMap.
1915 auto GEPs = std::move(it->second);
1916 LargeOffsetGEPMap[ArgVal].append(GEPs.begin(), GEPs.end());
1917 LargeOffsetGEPMap.erase(II);
1918 }
1919
1920 II->replaceAllUsesWith(ArgVal);
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00001921 II->eraseFromParent();
1922 return true;
Krzysztof Pszeniczny2bfe7592018-10-19 19:02:16 +00001923 }
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001924 case Intrinsic::cttz:
1925 case Intrinsic::ctlz:
1926 // If counting zeros is expensive, try to avoid it.
1927 return despeculateCountZeros(II, TLI, DL, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001928 }
Eric Christopher4b7948e2010-03-11 02:41:03 +00001929
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001930 if (TLI) {
1931 SmallVector<Value*, 2> PtrOps;
1932 Type *AccessTy;
Matt Arsenault1672b1b2017-02-08 07:09:03 +00001933 if (TLI->getAddrModeArguments(II, PtrOps, AccessTy))
1934 while (!PtrOps.empty()) {
1935 Value *PtrVal = PtrOps.pop_back_val();
1936 unsigned AS = PtrVal->getType()->getPointerAddressSpace();
1937 if (optimizeMemoryInst(II, PtrVal, AccessTy, AS))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001938 return true;
Matt Arsenault1672b1b2017-02-08 07:09:03 +00001939 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001940 }
Pete Cooper615fd892012-03-13 20:59:56 +00001941 }
1942
Eric Christopher4b7948e2010-03-11 02:41:03 +00001943 // From here on out we're working with named functions.
Craig Topperc0196b12014-04-14 00:51:57 +00001944 if (!CI->getCalledFunction()) return false;
Devang Patel0da52502011-05-26 21:51:06 +00001945
Benjamin Kramer7b88a492010-03-12 09:27:41 +00001946 // Lower all default uses of _chk calls. This is very similar
1947 // to what InstCombineCalls does, but here we are only lowering calls
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001948 // to fortified library functions (e.g. __memcpy_chk) that have the default
1949 // "don't know" as the objectsize. Anything else should be left alone.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001950 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001951 if (Value *V = Simplifier.optimizeCall(CI)) {
1952 CI->replaceAllUsesWith(V);
1953 CI->eraseFromParent();
1954 return true;
1955 }
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001956
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001957 return false;
Eric Christopher4b7948e2010-03-11 02:41:03 +00001958}
Chris Lattner1b93be52011-01-15 07:25:29 +00001959
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001960/// Look for opportunities to duplicate return instructions to the predecessor
1961/// to enable tail call optimizations. The case it is currently looking for is:
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001962/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001963/// bb0:
1964/// %tmp0 = tail call i32 @f0()
1965/// br label %return
1966/// bb1:
1967/// %tmp1 = tail call i32 @f1()
1968/// br label %return
1969/// bb2:
1970/// %tmp2 = tail call i32 @f2()
1971/// br label %return
1972/// return:
1973/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
1974/// ret i32 %retval
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001975/// @endcode
Evan Cheng0663f232011-03-21 01:19:09 +00001976///
1977/// =>
1978///
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001979/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001980/// bb0:
1981/// %tmp0 = tail call i32 @f0()
1982/// ret i32 %tmp0
1983/// bb1:
1984/// %tmp1 = tail call i32 @f1()
1985/// ret i32 %tmp1
1986/// bb2:
1987/// %tmp2 = tail call i32 @f2()
1988/// ret i32 %tmp2
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001989/// @endcode
Rong Xuce3be452019-03-08 22:46:18 +00001990bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB, bool &ModifiedDT) {
Cameron Zwarich47e71752011-03-24 04:51:51 +00001991 if (!TLI)
1992 return false;
1993
Michael Kuperstein71321562016-09-07 20:29:49 +00001994 ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator());
1995 if (!RetI)
Benjamin Kramer455fa352012-11-23 19:17:06 +00001996 return false;
1997
Craig Topperc0196b12014-04-14 00:51:57 +00001998 PHINode *PN = nullptr;
1999 BitCastInst *BCI = nullptr;
Michael Kuperstein71321562016-09-07 20:29:49 +00002000 Value *V = RetI->getReturnValue();
Evan Cheng249716e2012-07-27 21:21:26 +00002001 if (V) {
2002 BCI = dyn_cast<BitCastInst>(V);
2003 if (BCI)
2004 V = BCI->getOperand(0);
2005
2006 PN = dyn_cast<PHINode>(V);
2007 if (!PN)
2008 return false;
2009 }
Evan Cheng0663f232011-03-21 01:19:09 +00002010
Cameron Zwarich4649f172011-03-24 04:52:10 +00002011 if (PN && PN->getParent() != BB)
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002012 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00002013
Cameron Zwarich4649f172011-03-24 04:52:10 +00002014 // Make sure there are no instructions between the PHI and return, or that the
2015 // return is the first instruction in the block.
2016 if (PN) {
2017 BasicBlock::iterator BI = BB->begin();
Jonas Paulsson5ed4d462019-01-29 09:03:35 +00002018 // Skip over debug and the bitcast.
2019 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI) || &*BI == BCI);
Michael Kuperstein71321562016-09-07 20:29:49 +00002020 if (&*BI != RetI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002021 return false;
2022 } else {
Cameron Zwarich74157ab2011-03-24 16:34:59 +00002023 BasicBlock::iterator BI = BB->begin();
2024 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
Michael Kuperstein71321562016-09-07 20:29:49 +00002025 if (&*BI != RetI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002026 return false;
2027 }
Evan Cheng0663f232011-03-21 01:19:09 +00002028
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002029 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
2030 /// call.
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00002031 const Function *F = BB->getParent();
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002032 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich4649f172011-03-24 04:52:10 +00002033 if (PN) {
2034 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
Francis Visoiu Mistrih16468512019-04-23 21:57:46 +00002035 // Look through bitcasts.
2036 Value *IncomingVal = PN->getIncomingValue(I)->stripPointerCasts();
2037 CallInst *CI = dyn_cast<CallInst>(IncomingVal);
Cameron Zwarich4649f172011-03-24 04:52:10 +00002038 // Make sure the phi value is indeed produced by the tail call.
2039 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00002040 TLI->mayBeEmittedAsTailCall(CI) &&
2041 attributesPermitTailCall(F, CI, RetI, *TLI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00002042 TailCalls.push_back(CI);
2043 }
2044 } else {
2045 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002046 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
David Blaikie70573dc2014-11-19 07:49:26 +00002047 if (!VisitedBBs.insert(*PI).second)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002048 continue;
2049
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002050 BasicBlock::InstListType &InstList = (*PI)->getInstList();
Cameron Zwarich4649f172011-03-24 04:52:10 +00002051 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
2052 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich74157ab2011-03-24 16:34:59 +00002053 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
2054 if (RI == RE)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002055 continue;
Cameron Zwarich74157ab2011-03-24 16:34:59 +00002056
Cameron Zwarich4649f172011-03-24 04:52:10 +00002057 CallInst *CI = dyn_cast<CallInst>(&*RI);
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00002058 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI) &&
2059 attributesPermitTailCall(F, CI, RetI, *TLI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00002060 TailCalls.push_back(CI);
2061 }
Evan Cheng0663f232011-03-21 01:19:09 +00002062 }
2063
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002064 bool Changed = false;
2065 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
2066 CallInst *CI = TailCalls[i];
2067 CallSite CS(CI);
2068
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002069 // Make sure the call instruction is followed by an unconditional branch to
2070 // the return block.
2071 BasicBlock *CallBB = CI->getParent();
2072 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
2073 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
2074 continue;
2075
2076 // Duplicate the return into CallBB.
Michael Kuperstein71321562016-09-07 20:29:49 +00002077 (void)FoldReturnIntoUncondBranch(RetI, BB, CallBB);
Devang Patel8f606d72011-03-24 15:35:25 +00002078 ModifiedDT = Changed = true;
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002079 ++NumRetsDup;
2080 }
2081
2082 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng64a223a2012-09-28 23:58:57 +00002083 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002084 BB->eraseFromParent();
2085
2086 return Changed;
Evan Cheng0663f232011-03-21 01:19:09 +00002087}
2088
Chris Lattner728f9022008-11-25 07:09:13 +00002089//===----------------------------------------------------------------------===//
Chris Lattner728f9022008-11-25 07:09:13 +00002090// Memory Optimization
2091//===----------------------------------------------------------------------===//
2092
Chandler Carruthc8925912013-01-05 02:09:22 +00002093namespace {
2094
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002095/// This is an extended version of TargetLowering::AddrMode
Chandler Carruthc8925912013-01-05 02:09:22 +00002096/// which holds actual Value*'s for register values.
Chandler Carruth95f83e02013-01-07 15:14:13 +00002097struct ExtAddrMode : public TargetLowering::AddrMode {
Eugene Zelenko900b6332017-08-29 22:32:07 +00002098 Value *BaseReg = nullptr;
2099 Value *ScaledReg = nullptr;
John Brawn736bf002017-10-03 13:08:22 +00002100 Value *OriginalValue = nullptr;
Tim Northover8935aca2019-03-12 15:22:23 +00002101 bool InBounds = true;
John Brawn736bf002017-10-03 13:08:22 +00002102
2103 enum FieldName {
2104 NoField = 0x00,
2105 BaseRegField = 0x01,
2106 BaseGVField = 0x02,
2107 BaseOffsField = 0x04,
2108 ScaledRegField = 0x08,
2109 ScaleField = 0x10,
2110 MultipleFields = 0xff
2111 };
Eugene Zelenko900b6332017-08-29 22:32:07 +00002112
Tim Northover8935aca2019-03-12 15:22:23 +00002113
Eugene Zelenko900b6332017-08-29 22:32:07 +00002114 ExtAddrMode() = default;
2115
Chandler Carruthc8925912013-01-05 02:09:22 +00002116 void print(raw_ostream &OS) const;
2117 void dump() const;
Stephen Lin837bba12013-07-15 17:55:02 +00002118
John Brawn736bf002017-10-03 13:08:22 +00002119 FieldName compare(const ExtAddrMode &other) {
2120 // First check that the types are the same on each field, as differing types
2121 // is something we can't cope with later on.
2122 if (BaseReg && other.BaseReg &&
2123 BaseReg->getType() != other.BaseReg->getType())
2124 return MultipleFields;
2125 if (BaseGV && other.BaseGV &&
2126 BaseGV->getType() != other.BaseGV->getType())
2127 return MultipleFields;
2128 if (ScaledReg && other.ScaledReg &&
2129 ScaledReg->getType() != other.ScaledReg->getType())
2130 return MultipleFields;
2131
Tim Northover8935aca2019-03-12 15:22:23 +00002132 // Conservatively reject 'inbounds' mismatches.
2133 if (InBounds != other.InBounds)
2134 return MultipleFields;
2135
John Brawn736bf002017-10-03 13:08:22 +00002136 // Check each field to see if it differs.
2137 unsigned Result = NoField;
2138 if (BaseReg != other.BaseReg)
2139 Result |= BaseRegField;
2140 if (BaseGV != other.BaseGV)
2141 Result |= BaseGVField;
2142 if (BaseOffs != other.BaseOffs)
2143 Result |= BaseOffsField;
2144 if (ScaledReg != other.ScaledReg)
2145 Result |= ScaledRegField;
2146 // Don't count 0 as being a different scale, because that actually means
2147 // unscaled (which will already be counted by having no ScaledReg).
2148 if (Scale && other.Scale && Scale != other.Scale)
2149 Result |= ScaleField;
2150
2151 if (countPopulation(Result) > 1)
2152 return MultipleFields;
2153 else
2154 return static_cast<FieldName>(Result);
2155 }
2156
John Brawn4b476482017-11-27 11:29:15 +00002157 // An AddrMode is trivial if it involves no calculation i.e. it is just a base
2158 // with no offset.
John Brawn736bf002017-10-03 13:08:22 +00002159 bool isTrivial() {
John Brawn4b476482017-11-27 11:29:15 +00002160 // An AddrMode is (BaseGV + BaseReg + BaseOffs + ScaleReg * Scale) so it is
2161 // trivial if at most one of these terms is nonzero, except that BaseGV and
2162 // BaseReg both being zero actually means a null pointer value, which we
2163 // consider to be 'non-zero' here.
2164 return !BaseOffs && !Scale && !(BaseGV && BaseReg);
Chandler Carruthc8925912013-01-05 02:09:22 +00002165 }
John Brawn70cdb5b2017-11-24 14:10:45 +00002166
2167 Value *GetFieldAsValue(FieldName Field, Type *IntPtrTy) {
2168 switch (Field) {
2169 default:
2170 return nullptr;
2171 case BaseRegField:
2172 return BaseReg;
2173 case BaseGVField:
2174 return BaseGV;
2175 case ScaledRegField:
2176 return ScaledReg;
2177 case BaseOffsField:
2178 return ConstantInt::get(IntPtrTy, BaseOffs);
2179 }
2180 }
2181
2182 void SetCombinedField(FieldName Field, Value *V,
2183 const SmallVectorImpl<ExtAddrMode> &AddrModes) {
2184 switch (Field) {
2185 default:
2186 llvm_unreachable("Unhandled fields are expected to be rejected earlier");
2187 break;
2188 case ExtAddrMode::BaseRegField:
2189 BaseReg = V;
2190 break;
2191 case ExtAddrMode::BaseGVField:
2192 // A combined BaseGV is an Instruction, not a GlobalValue, so it goes
2193 // in the BaseReg field.
2194 assert(BaseReg == nullptr);
2195 BaseReg = V;
2196 BaseGV = nullptr;
2197 break;
2198 case ExtAddrMode::ScaledRegField:
2199 ScaledReg = V;
2200 // If we have a mix of scaled and unscaled addrmodes then we want scale
2201 // to be the scale and not zero.
2202 if (!Scale)
2203 for (const ExtAddrMode &AM : AddrModes)
2204 if (AM.Scale) {
2205 Scale = AM.Scale;
2206 break;
2207 }
2208 break;
2209 case ExtAddrMode::BaseOffsField:
2210 // The offset is no longer a constant, so it goes in ScaledReg with a
2211 // scale of 1.
2212 assert(ScaledReg == nullptr);
2213 ScaledReg = V;
2214 Scale = 1;
2215 BaseOffs = 0;
2216 break;
2217 }
2218 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002219};
2220
Eugene Zelenko900b6332017-08-29 22:32:07 +00002221} // end anonymous namespace
2222
Eli Friedmanc1f1f852013-09-10 23:09:24 +00002223#ifndef NDEBUG
2224static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
2225 AM.print(OS);
2226 return OS;
2227}
2228#endif
2229
Aaron Ballman615eb472017-10-15 14:32:27 +00002230#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruthc8925912013-01-05 02:09:22 +00002231void ExtAddrMode::print(raw_ostream &OS) const {
2232 bool NeedPlus = false;
2233 OS << "[";
Tim Northover8935aca2019-03-12 15:22:23 +00002234 if (InBounds)
2235 OS << "inbounds ";
Chandler Carruthc8925912013-01-05 02:09:22 +00002236 if (BaseGV) {
2237 OS << (NeedPlus ? " + " : "")
2238 << "GV:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002239 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002240 NeedPlus = true;
2241 }
2242
Richard Trieuc0f91212014-05-30 03:15:17 +00002243 if (BaseOffs) {
2244 OS << (NeedPlus ? " + " : "")
2245 << BaseOffs;
2246 NeedPlus = true;
2247 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002248
2249 if (BaseReg) {
2250 OS << (NeedPlus ? " + " : "")
2251 << "Base:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002252 BaseReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002253 NeedPlus = true;
2254 }
2255 if (Scale) {
2256 OS << (NeedPlus ? " + " : "")
2257 << Scale << "*";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002258 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002259 }
2260
2261 OS << ']';
2262}
2263
Yaron Kereneb2a2542016-01-29 20:50:44 +00002264LLVM_DUMP_METHOD void ExtAddrMode::dump() const {
Chandler Carruthc8925912013-01-05 02:09:22 +00002265 print(dbgs());
2266 dbgs() << '\n';
2267}
2268#endif
2269
Eugene Zelenko900b6332017-08-29 22:32:07 +00002270namespace {
2271
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002272/// This class provides transaction based operation on the IR.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002273/// Every change made through this class is recorded in the internal state and
2274/// can be undone (rollback) until commit is called.
2275class TypePromotionTransaction {
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002276 /// This represents the common interface of the individual transaction.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002277 /// Each class implements the logic for doing one specific modification on
2278 /// the IR via the TypePromotionTransaction.
2279 class TypePromotionAction {
2280 protected:
2281 /// The Instruction modified.
2282 Instruction *Inst;
2283
2284 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002285 /// Constructor of the action.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002286 /// The constructor performs the related action on the IR.
2287 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
2288
Eugene Zelenko900b6332017-08-29 22:32:07 +00002289 virtual ~TypePromotionAction() = default;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002290
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002291 /// Undo the modification done by this action.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002292 /// When this method is called, the IR must be in the same state as it was
2293 /// before this action was applied.
2294 /// \pre Undoing the action works if and only if the IR is in the exact same
2295 /// state as it was directly after this action was applied.
2296 virtual void undo() = 0;
2297
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002298 /// Advocate every change made by this action.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002299 /// When the results on the IR of the action are to be kept, it is important
2300 /// to call this function, otherwise hidden information may be kept forever.
2301 virtual void commit() {
2302 // Nothing to be done, this action is not doing anything.
2303 }
2304 };
2305
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002306 /// Utility to remember the position of an instruction.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002307 class InsertionHandler {
2308 /// Position of an instruction.
2309 /// Either an instruction:
2310 /// - Is the first in a basic block: BB is used.
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00002311 /// - Has a previous instruction: PrevInst is used.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002312 union {
2313 Instruction *PrevInst;
2314 BasicBlock *BB;
2315 } Point;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002316
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002317 /// Remember whether or not the instruction had a previous instruction.
2318 bool HasPrevInstruction;
2319
2320 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002321 /// Record the position of \p Inst.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002322 InsertionHandler(Instruction *Inst) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002323 BasicBlock::iterator It = Inst->getIterator();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002324 HasPrevInstruction = (It != (Inst->getParent()->begin()));
2325 if (HasPrevInstruction)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002326 Point.PrevInst = &*--It;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002327 else
2328 Point.BB = Inst->getParent();
2329 }
2330
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002331 /// Insert \p Inst at the recorded position.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002332 void insert(Instruction *Inst) {
2333 if (HasPrevInstruction) {
2334 if (Inst->getParent())
2335 Inst->removeFromParent();
2336 Inst->insertAfter(Point.PrevInst);
2337 } else {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002338 Instruction *Position = &*Point.BB->getFirstInsertionPt();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002339 if (Inst->getParent())
2340 Inst->moveBefore(Position);
2341 else
2342 Inst->insertBefore(Position);
2343 }
2344 }
2345 };
2346
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002347 /// Move an instruction before another.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002348 class InstructionMoveBefore : public TypePromotionAction {
2349 /// Original position of the instruction.
2350 InsertionHandler Position;
2351
2352 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002353 /// Move \p Inst before \p Before.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002354 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
2355 : TypePromotionAction(Inst), Position(Inst) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002356 LLVM_DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before
2357 << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002358 Inst->moveBefore(Before);
2359 }
2360
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002361 /// Move the instruction back to its original position.
Craig Topper4584cd52014-03-07 09:26:03 +00002362 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002363 LLVM_DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002364 Position.insert(Inst);
2365 }
2366 };
2367
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002368 /// Set the operand of an instruction with a new value.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002369 class OperandSetter : public TypePromotionAction {
2370 /// Original operand of the instruction.
2371 Value *Origin;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002372
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002373 /// Index of the modified instruction.
2374 unsigned Idx;
2375
2376 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002377 /// Set \p Idx operand of \p Inst with \p NewVal.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002378 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
2379 : TypePromotionAction(Inst), Idx(Idx) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002380 LLVM_DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
2381 << "for:" << *Inst << "\n"
2382 << "with:" << *NewVal << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002383 Origin = Inst->getOperand(Idx);
2384 Inst->setOperand(Idx, NewVal);
2385 }
2386
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002387 /// Restore the original value of the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002388 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002389 LLVM_DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
2390 << "for: " << *Inst << "\n"
2391 << "with: " << *Origin << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002392 Inst->setOperand(Idx, Origin);
2393 }
2394 };
2395
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002396 /// Hide the operands of an instruction.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002397 /// Do as if this instruction was not using any of its operands.
2398 class OperandsHider : public TypePromotionAction {
2399 /// The list of original operands.
2400 SmallVector<Value *, 4> OriginalValues;
2401
2402 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002403 /// Remove \p Inst from the uses of the operands of \p Inst.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002404 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002405 LLVM_DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002406 unsigned NumOpnds = Inst->getNumOperands();
2407 OriginalValues.reserve(NumOpnds);
2408 for (unsigned It = 0; It < NumOpnds; ++It) {
2409 // Save the current operand.
2410 Value *Val = Inst->getOperand(It);
2411 OriginalValues.push_back(Val);
2412 // Set a dummy one.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002413 // We could use OperandSetter here, but that would imply an overhead
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002414 // that we are not willing to pay.
2415 Inst->setOperand(It, UndefValue::get(Val->getType()));
2416 }
2417 }
2418
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002419 /// Restore the original list of uses.
Craig Topper4584cd52014-03-07 09:26:03 +00002420 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002421 LLVM_DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002422 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
2423 Inst->setOperand(It, OriginalValues[It]);
2424 }
2425 };
2426
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002427 /// Build a truncate instruction.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002428 class TruncBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002429 Value *Val;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002430
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002431 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002432 /// Build a truncate instruction of \p Opnd producing a \p Ty
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002433 /// result.
2434 /// trunc Opnd to Ty.
2435 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
2436 IRBuilder<> Builder(Opnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00002437 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002438 LLVM_DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002439 }
2440
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002441 /// Get the built value.
Quentin Colombetac55b152014-09-16 22:36:07 +00002442 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002443
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002444 /// Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002445 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002446 LLVM_DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
Quentin Colombetac55b152014-09-16 22:36:07 +00002447 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2448 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002449 }
2450 };
2451
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002452 /// Build a sign extension instruction.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002453 class SExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002454 Value *Val;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002455
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002456 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002457 /// Build a sign extension instruction of \p Opnd producing a \p Ty
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002458 /// result.
2459 /// sext Opnd to Ty.
2460 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002461 : TypePromotionAction(InsertPt) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002462 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002463 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002464 LLVM_DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002465 }
2466
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002467 /// Get the built value.
Quentin Colombetac55b152014-09-16 22:36:07 +00002468 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002469
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002470 /// Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002471 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002472 LLVM_DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
Quentin Colombetac55b152014-09-16 22:36:07 +00002473 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2474 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002475 }
2476 };
2477
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002478 /// Build a zero extension instruction.
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002479 class ZExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002480 Value *Val;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002481
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002482 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002483 /// Build a zero extension instruction of \p Opnd producing a \p Ty
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002484 /// result.
2485 /// zext Opnd to Ty.
2486 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002487 : TypePromotionAction(InsertPt) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002488 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002489 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002490 LLVM_DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002491 }
2492
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002493 /// Get the built value.
Quentin Colombetac55b152014-09-16 22:36:07 +00002494 Value *getBuiltValue() { return Val; }
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002495
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002496 /// Remove the built instruction.
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002497 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002498 LLVM_DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
Quentin Colombetac55b152014-09-16 22:36:07 +00002499 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2500 IVal->eraseFromParent();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002501 }
2502 };
2503
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002504 /// Mutate an instruction to another type.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002505 class TypeMutator : public TypePromotionAction {
2506 /// Record the original type.
2507 Type *OrigTy;
2508
2509 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002510 /// Mutate the type of \p Inst into \p NewTy.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002511 TypeMutator(Instruction *Inst, Type *NewTy)
2512 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002513 LLVM_DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
2514 << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002515 Inst->mutateType(NewTy);
2516 }
2517
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002518 /// Mutate the instruction back to its original type.
Craig Topper4584cd52014-03-07 09:26:03 +00002519 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002520 LLVM_DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
2521 << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002522 Inst->mutateType(OrigTy);
2523 }
2524 };
2525
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002526 /// Replace the uses of an instruction by another instruction.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002527 class UsesReplacer : public TypePromotionAction {
2528 /// Helper structure to keep track of the replaced uses.
2529 struct InstructionAndIdx {
2530 /// The instruction using the instruction.
2531 Instruction *Inst;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002532
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002533 /// The index where this instruction is used for Inst.
2534 unsigned Idx;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002535
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002536 InstructionAndIdx(Instruction *Inst, unsigned Idx)
2537 : Inst(Inst), Idx(Idx) {}
2538 };
2539
2540 /// Keep track of the original uses (pair Instruction, Index).
2541 SmallVector<InstructionAndIdx, 4> OriginalUses;
Wolfgang Piebac874c42018-12-11 21:13:53 +00002542 /// Keep track of the debug users.
2543 SmallVector<DbgValueInst *, 1> DbgValues;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002544
2545 using use_iterator = SmallVectorImpl<InstructionAndIdx>::iterator;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002546
2547 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002548 /// Replace all the use of \p Inst by \p New.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002549 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002550 LLVM_DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
2551 << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002552 // Record the original uses.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002553 for (Use &U : Inst->uses()) {
2554 Instruction *UserI = cast<Instruction>(U.getUser());
2555 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002556 }
Wolfgang Piebac874c42018-12-11 21:13:53 +00002557 // Record the debug uses separately. They are not in the instruction's
2558 // use list, but they are replaced by RAUW.
2559 findDbgValues(DbgValues, Inst);
2560
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002561 // Now, we can replace the uses.
2562 Inst->replaceAllUsesWith(New);
2563 }
2564
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002565 /// Reassign the original uses of Inst to Inst.
Craig Topper4584cd52014-03-07 09:26:03 +00002566 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002567 LLVM_DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002568 for (use_iterator UseIt = OriginalUses.begin(),
2569 EndIt = OriginalUses.end();
2570 UseIt != EndIt; ++UseIt) {
2571 UseIt->Inst->setOperand(UseIt->Idx, Inst);
2572 }
Wolfgang Piebac874c42018-12-11 21:13:53 +00002573 // RAUW has replaced all original uses with references to the new value,
2574 // including the debug uses. Since we are undoing the replacements,
2575 // the original debug uses must also be reinstated to maintain the
2576 // correctness and utility of debug value instructions.
2577 for (auto *DVI: DbgValues) {
2578 LLVMContext &Ctx = Inst->getType()->getContext();
2579 auto *MV = MetadataAsValue::get(Ctx, ValueAsMetadata::get(Inst));
2580 DVI->setOperand(0, MV);
2581 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002582 }
2583 };
2584
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002585 /// Remove an instruction from the IR.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002586 class InstructionRemover : public TypePromotionAction {
2587 /// Original position of the instruction.
2588 InsertionHandler Inserter;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002589
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002590 /// Helper structure to hide all the link to the instruction. In other
2591 /// words, this helps to do as if the instruction was removed.
2592 OperandsHider Hider;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002593
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002594 /// Keep track of the uses replaced, if any.
Eugene Zelenko900b6332017-08-29 22:32:07 +00002595 UsesReplacer *Replacer = nullptr;
2596
Jun Bum Limdee55652017-04-03 19:20:07 +00002597 /// Keep track of instructions removed.
2598 SetOfInstrs &RemovedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002599
2600 public:
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00002601 /// Remove all reference of \p Inst and optionally replace all its
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002602 /// uses with New.
Jun Bum Limdee55652017-04-03 19:20:07 +00002603 /// \p RemovedInsts Keep track of the instructions removed by this Action.
Craig Topperc0196b12014-04-14 00:51:57 +00002604 /// \pre If !Inst->use_empty(), then New != nullptr
Jun Bum Limdee55652017-04-03 19:20:07 +00002605 InstructionRemover(Instruction *Inst, SetOfInstrs &RemovedInsts,
2606 Value *New = nullptr)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002607 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
Eugene Zelenko900b6332017-08-29 22:32:07 +00002608 RemovedInsts(RemovedInsts) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002609 if (New)
2610 Replacer = new UsesReplacer(Inst, New);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002611 LLVM_DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
Jun Bum Limdee55652017-04-03 19:20:07 +00002612 RemovedInsts.insert(Inst);
2613 /// The instructions removed here will be freed after completing
2614 /// optimizeBlock() for all blocks as we need to keep track of the
2615 /// removed instructions during promotion.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002616 Inst->removeFromParent();
2617 }
2618
Alexander Kornienkof817c1c2015-04-11 02:11:45 +00002619 ~InstructionRemover() override { delete Replacer; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002620
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002621 /// Resurrect the instruction and reassign it to the proper uses if
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002622 /// new value was provided when build this action.
Craig Topper4584cd52014-03-07 09:26:03 +00002623 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002624 LLVM_DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002625 Inserter.insert(Inst);
2626 if (Replacer)
2627 Replacer->undo();
2628 Hider.undo();
Jun Bum Limdee55652017-04-03 19:20:07 +00002629 RemovedInsts.erase(Inst);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002630 }
2631 };
2632
2633public:
2634 /// Restoration point.
2635 /// The restoration point is a pointer to an action instead of an iterator
2636 /// because the iterator may be invalidated but not the pointer.
Eugene Zelenko900b6332017-08-29 22:32:07 +00002637 using ConstRestorationPt = const TypePromotionAction *;
Jun Bum Limdee55652017-04-03 19:20:07 +00002638
2639 TypePromotionTransaction(SetOfInstrs &RemovedInsts)
2640 : RemovedInsts(RemovedInsts) {}
2641
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002642 /// Advocate every changes made in that transaction.
2643 void commit();
Eugene Zelenko900b6332017-08-29 22:32:07 +00002644
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002645 /// Undo all the changes made after the given point.
2646 void rollback(ConstRestorationPt Point);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002647
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002648 /// Get the current restoration point.
2649 ConstRestorationPt getRestorationPoint() const;
2650
2651 /// \name API for IR modification with state keeping to support rollback.
2652 /// @{
2653 /// Same as Instruction::setOperand.
2654 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002655
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002656 /// Same as Instruction::eraseFromParent.
Craig Topperc0196b12014-04-14 00:51:57 +00002657 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002658
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002659 /// Same as Value::replaceAllUsesWith.
2660 void replaceAllUsesWith(Instruction *Inst, Value *New);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002661
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002662 /// Same as Value::mutateType.
2663 void mutateType(Instruction *Inst, Type *NewTy);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002664
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002665 /// Same as IRBuilder::createTrunc.
Quentin Colombetac55b152014-09-16 22:36:07 +00002666 Value *createTrunc(Instruction *Opnd, Type *Ty);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002667
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002668 /// Same as IRBuilder::createSExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002669 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002670
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002671 /// Same as IRBuilder::createZExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002672 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002673
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002674 /// Same as Instruction::moveBefore.
2675 void moveBefore(Instruction *Inst, Instruction *Before);
2676 /// @}
2677
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002678private:
2679 /// The ordered list of actions made so far.
David Blaikie7620b312014-04-15 06:17:44 +00002680 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002681
2682 using CommitPt = SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator;
2683
Jun Bum Limdee55652017-04-03 19:20:07 +00002684 SetOfInstrs &RemovedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002685};
2686
Eugene Zelenko900b6332017-08-29 22:32:07 +00002687} // end anonymous namespace
2688
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002689void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
2690 Value *NewVal) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00002691 Actions.push_back(llvm::make_unique<TypePromotionTransaction::OperandSetter>(
2692 Inst, Idx, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002693}
2694
2695void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
2696 Value *NewVal) {
2697 Actions.push_back(
Eugene Zelenko900b6332017-08-29 22:32:07 +00002698 llvm::make_unique<TypePromotionTransaction::InstructionRemover>(
2699 Inst, RemovedInsts, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002700}
2701
2702void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
2703 Value *New) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00002704 Actions.push_back(
2705 llvm::make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002706}
2707
2708void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00002709 Actions.push_back(
2710 llvm::make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002711}
2712
Quentin Colombetac55b152014-09-16 22:36:07 +00002713Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
2714 Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002715 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002716 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002717 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002718 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002719}
2720
Quentin Colombetac55b152014-09-16 22:36:07 +00002721Value *TypePromotionTransaction::createSExt(Instruction *Inst,
2722 Value *Opnd, Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002723 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002724 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002725 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002726 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002727}
2728
Quentin Colombetac55b152014-09-16 22:36:07 +00002729Value *TypePromotionTransaction::createZExt(Instruction *Inst,
2730 Value *Opnd, Type *Ty) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002731 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002732 Value *Val = Ptr->getBuiltValue();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002733 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002734 return Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002735}
2736
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002737void TypePromotionTransaction::moveBefore(Instruction *Inst,
2738 Instruction *Before) {
2739 Actions.push_back(
Eugene Zelenko900b6332017-08-29 22:32:07 +00002740 llvm::make_unique<TypePromotionTransaction::InstructionMoveBefore>(
2741 Inst, Before));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002742}
2743
2744TypePromotionTransaction::ConstRestorationPt
2745TypePromotionTransaction::getRestorationPoint() const {
David Blaikie7620b312014-04-15 06:17:44 +00002746 return !Actions.empty() ? Actions.back().get() : nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002747}
2748
2749void TypePromotionTransaction::commit() {
2750 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
David Blaikie7620b312014-04-15 06:17:44 +00002751 ++It)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002752 (*It)->commit();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002753 Actions.clear();
2754}
2755
2756void TypePromotionTransaction::rollback(
2757 TypePromotionTransaction::ConstRestorationPt Point) {
David Blaikie7620b312014-04-15 06:17:44 +00002758 while (!Actions.empty() && Point != Actions.back().get()) {
2759 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002760 Curr->undo();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002761 }
2762}
2763
Eugene Zelenko900b6332017-08-29 22:32:07 +00002764namespace {
2765
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002766/// A helper class for matching addressing modes.
Chandler Carruthc8925912013-01-05 02:09:22 +00002767///
2768/// This encapsulates the logic for matching the target-legal addressing modes.
2769class AddressingModeMatcher {
2770 SmallVectorImpl<Instruction*> &AddrModeInsts;
2771 const TargetLowering &TLI;
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002772 const TargetRegisterInfo &TRI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00002773 const DataLayout &DL;
Chandler Carruthc8925912013-01-05 02:09:22 +00002774
2775 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
2776 /// the memory instruction that we're computing this address for.
2777 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002778 unsigned AddrSpace;
Chandler Carruthc8925912013-01-05 02:09:22 +00002779 Instruction *MemoryInst;
Stephen Lin837bba12013-07-15 17:55:02 +00002780
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002781 /// This is the addressing mode that we're building up. This is
Chandler Carruthc8925912013-01-05 02:09:22 +00002782 /// part of the return value of this addressing mode matching stuff.
2783 ExtAddrMode &AddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002784
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002785 /// The instructions inserted by other CodeGenPrepare optimizations.
2786 const SetOfInstrs &InsertedInsts;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002787
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002788 /// A map from the instructions to their type before promotion.
2789 InstrToOrigTy &PromotedInsts;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002790
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002791 /// The ongoing transaction where every action should be registered.
2792 TypePromotionTransaction &TPT;
2793
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00002794 // A GEP which has too large offset to be folded into the addressing mode.
2795 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP;
2796
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002797 /// This is set to true when we should not do profitability checks.
2798 /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
Chandler Carruthc8925912013-01-05 02:09:22 +00002799 bool IgnoreProfitability;
Stephen Lin837bba12013-07-15 17:55:02 +00002800
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00002801 AddressingModeMatcher(
2802 SmallVectorImpl<Instruction *> &AMI, const TargetLowering &TLI,
2803 const TargetRegisterInfo &TRI, Type *AT, unsigned AS, Instruction *MI,
2804 ExtAddrMode &AM, const SetOfInstrs &InsertedInsts,
2805 InstrToOrigTy &PromotedInsts, TypePromotionTransaction &TPT,
2806 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP)
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002807 : AddrModeInsts(AMI), TLI(TLI), TRI(TRI),
Mehdi Amini4fe37982015-07-07 18:45:17 +00002808 DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
2809 MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00002810 PromotedInsts(PromotedInsts), TPT(TPT), LargeOffsetGEP(LargeOffsetGEP) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002811 IgnoreProfitability = false;
2812 }
Stephen Lin837bba12013-07-15 17:55:02 +00002813
Eugene Zelenko900b6332017-08-29 22:32:07 +00002814public:
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002815 /// Find the maximal addressing mode that a load/store of V can fold,
Chandler Carruthc8925912013-01-05 02:09:22 +00002816 /// give an access type of AccessTy. This returns a list of involved
2817 /// instructions in AddrModeInsts.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002818 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002819 /// optimizations.
2820 /// \p PromotedInsts maps the instructions to their type before promotion.
2821 /// \p The ongoing transaction where every action should be registered.
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00002822 static ExtAddrMode
2823 Match(Value *V, Type *AccessTy, unsigned AS, Instruction *MemoryInst,
2824 SmallVectorImpl<Instruction *> &AddrModeInsts,
2825 const TargetLowering &TLI, const TargetRegisterInfo &TRI,
2826 const SetOfInstrs &InsertedInsts, InstrToOrigTy &PromotedInsts,
2827 TypePromotionTransaction &TPT,
2828 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002829 ExtAddrMode Result;
2830
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00002831 bool Success = AddressingModeMatcher(AddrModeInsts, TLI, TRI, AccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002832 MemoryInst, Result, InsertedInsts,
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00002833 PromotedInsts, TPT, LargeOffsetGEP)
2834 .matchAddr(V, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00002835 (void)Success; assert(Success && "Couldn't select *anything*?");
2836 return Result;
2837 }
Eugene Zelenko900b6332017-08-29 22:32:07 +00002838
Chandler Carruthc8925912013-01-05 02:09:22 +00002839private:
Sanjay Patelfc580a62015-09-21 23:03:16 +00002840 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
Fangrui Songcb0bab82018-07-16 18:51:40 +00002841 bool matchAddr(Value *Addr, unsigned Depth);
2842 bool matchOperationAddr(User *AddrInst, unsigned Opcode, unsigned Depth,
Craig Topperc0196b12014-04-14 00:51:57 +00002843 bool *MovedAway = nullptr);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002844 bool isProfitableToFoldIntoAddressingMode(Instruction *I,
Chandler Carruthc8925912013-01-05 02:09:22 +00002845 ExtAddrMode &AMBefore,
2846 ExtAddrMode &AMAfter);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002847 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
2848 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
Quentin Colombet867c5502014-02-14 22:23:22 +00002849 Value *PromotedOperand) const;
Chandler Carruthc8925912013-01-05 02:09:22 +00002850};
2851
Ali Tamurd482b012018-11-12 21:43:43 +00002852class PhiNodeSet;
2853
2854/// An iterator for PhiNodeSet.
2855class PhiNodeSetIterator {
2856 PhiNodeSet * const Set;
2857 size_t CurrentIndex = 0;
2858
2859public:
2860 /// The constructor. Start should point to either a valid element, or be equal
2861 /// to the size of the underlying SmallVector of the PhiNodeSet.
2862 PhiNodeSetIterator(PhiNodeSet * const Set, size_t Start);
2863 PHINode * operator*() const;
2864 PhiNodeSetIterator& operator++();
2865 bool operator==(const PhiNodeSetIterator &RHS) const;
2866 bool operator!=(const PhiNodeSetIterator &RHS) const;
2867};
2868
2869/// Keeps a set of PHINodes.
2870///
2871/// This is a minimal set implementation for a specific use case:
2872/// It is very fast when there are very few elements, but also provides good
2873/// performance when there are many. It is similar to SmallPtrSet, but also
2874/// provides iteration by insertion order, which is deterministic and stable
2875/// across runs. It is also similar to SmallSetVector, but provides removing
2876/// elements in O(1) time. This is achieved by not actually removing the element
2877/// from the underlying vector, so comes at the cost of using more memory, but
2878/// that is fine, since PhiNodeSets are used as short lived objects.
2879class PhiNodeSet {
2880 friend class PhiNodeSetIterator;
2881
2882 using MapType = SmallDenseMap<PHINode *, size_t, 32>;
2883 using iterator = PhiNodeSetIterator;
2884
2885 /// Keeps the elements in the order of their insertion in the underlying
2886 /// vector. To achieve constant time removal, it never deletes any element.
2887 SmallVector<PHINode *, 32> NodeList;
2888
2889 /// Keeps the elements in the underlying set implementation. This (and not the
2890 /// NodeList defined above) is the source of truth on whether an element
2891 /// is actually in the collection.
2892 MapType NodeMap;
2893
2894 /// Points to the first valid (not deleted) element when the set is not empty
2895 /// and the value is not zero. Equals to the size of the underlying vector
2896 /// when the set is empty. When the value is 0, as in the beginning, the
2897 /// first element may or may not be valid.
2898 size_t FirstValidElement = 0;
2899
2900public:
2901 /// Inserts a new element to the collection.
2902 /// \returns true if the element is actually added, i.e. was not in the
2903 /// collection before the operation.
2904 bool insert(PHINode *Ptr) {
2905 if (NodeMap.insert(std::make_pair(Ptr, NodeList.size())).second) {
2906 NodeList.push_back(Ptr);
2907 return true;
2908 }
2909 return false;
2910 }
2911
2912 /// Removes the element from the collection.
2913 /// \returns whether the element is actually removed, i.e. was in the
2914 /// collection before the operation.
2915 bool erase(PHINode *Ptr) {
2916 auto it = NodeMap.find(Ptr);
2917 if (it != NodeMap.end()) {
2918 NodeMap.erase(Ptr);
2919 SkipRemovedElements(FirstValidElement);
2920 return true;
2921 }
2922 return false;
2923 }
2924
2925 /// Removes all elements and clears the collection.
2926 void clear() {
2927 NodeMap.clear();
2928 NodeList.clear();
2929 FirstValidElement = 0;
2930 }
2931
2932 /// \returns an iterator that will iterate the elements in the order of
2933 /// insertion.
2934 iterator begin() {
2935 if (FirstValidElement == 0)
2936 SkipRemovedElements(FirstValidElement);
2937 return PhiNodeSetIterator(this, FirstValidElement);
2938 }
2939
2940 /// \returns an iterator that points to the end of the collection.
2941 iterator end() { return PhiNodeSetIterator(this, NodeList.size()); }
2942
2943 /// Returns the number of elements in the collection.
2944 size_t size() const {
2945 return NodeMap.size();
2946 }
2947
2948 /// \returns 1 if the given element is in the collection, and 0 if otherwise.
2949 size_t count(PHINode *Ptr) const {
2950 return NodeMap.count(Ptr);
2951 }
2952
2953private:
2954 /// Updates the CurrentIndex so that it will point to a valid element.
2955 ///
2956 /// If the element of NodeList at CurrentIndex is valid, it does not
2957 /// change it. If there are no more valid elements, it updates CurrentIndex
2958 /// to point to the end of the NodeList.
2959 void SkipRemovedElements(size_t &CurrentIndex) {
2960 while (CurrentIndex < NodeList.size()) {
2961 auto it = NodeMap.find(NodeList[CurrentIndex]);
2962 // If the element has been deleted and added again later, NodeMap will
2963 // point to a different index, so CurrentIndex will still be invalid.
2964 if (it != NodeMap.end() && it->second == CurrentIndex)
2965 break;
2966 ++CurrentIndex;
2967 }
2968 }
2969};
2970
2971PhiNodeSetIterator::PhiNodeSetIterator(PhiNodeSet *const Set, size_t Start)
2972 : Set(Set), CurrentIndex(Start) {}
2973
2974PHINode * PhiNodeSetIterator::operator*() const {
2975 assert(CurrentIndex < Set->NodeList.size() &&
2976 "PhiNodeSet access out of range");
2977 return Set->NodeList[CurrentIndex];
2978}
2979
2980PhiNodeSetIterator& PhiNodeSetIterator::operator++() {
2981 assert(CurrentIndex < Set->NodeList.size() &&
2982 "PhiNodeSet access out of range");
2983 ++CurrentIndex;
2984 Set->SkipRemovedElements(CurrentIndex);
2985 return *this;
2986}
2987
2988bool PhiNodeSetIterator::operator==(const PhiNodeSetIterator &RHS) const {
2989 return CurrentIndex == RHS.CurrentIndex;
2990}
2991
2992bool PhiNodeSetIterator::operator!=(const PhiNodeSetIterator &RHS) const {
Serge Guelton12c7a962018-11-19 10:05:28 +00002993 return !((*this) == RHS);
Ali Tamurd482b012018-11-12 21:43:43 +00002994}
2995
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002996/// Keep track of simplification of Phi nodes.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002997/// Accept the set of all phi nodes and erase phi node from this set
2998/// if it is simplified.
2999class SimplificationTracker {
3000 DenseMap<Value *, Value *> Storage;
3001 const SimplifyQuery &SQ;
Ali Tamurd482b012018-11-12 21:43:43 +00003002 // Tracks newly created Phi nodes. The elements are iterated by insertion
3003 // order.
3004 PhiNodeSet AllPhiNodes;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003005 // Tracks newly created Select nodes.
3006 SmallPtrSet<SelectInst *, 32> AllSelectNodes;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003007
3008public:
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003009 SimplificationTracker(const SimplifyQuery &sq)
3010 : SQ(sq) {}
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003011
3012 Value *Get(Value *V) {
3013 do {
3014 auto SV = Storage.find(V);
3015 if (SV == Storage.end())
3016 return V;
3017 V = SV->second;
3018 } while (true);
3019 }
3020
3021 Value *Simplify(Value *Val) {
3022 SmallVector<Value *, 32> WorkList;
3023 SmallPtrSet<Value *, 32> Visited;
3024 WorkList.push_back(Val);
3025 while (!WorkList.empty()) {
3026 auto P = WorkList.pop_back_val();
3027 if (!Visited.insert(P).second)
3028 continue;
3029 if (auto *PI = dyn_cast<Instruction>(P))
3030 if (Value *V = SimplifyInstruction(cast<Instruction>(PI), SQ)) {
3031 for (auto *U : PI->users())
3032 WorkList.push_back(cast<Value>(U));
3033 Put(PI, V);
3034 PI->replaceAllUsesWith(V);
3035 if (auto *PHI = dyn_cast<PHINode>(PI))
Ali Tamurd482b012018-11-12 21:43:43 +00003036 AllPhiNodes.erase(PHI);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003037 if (auto *Select = dyn_cast<SelectInst>(PI))
3038 AllSelectNodes.erase(Select);
3039 PI->eraseFromParent();
3040 }
3041 }
3042 return Get(Val);
3043 }
3044
3045 void Put(Value *From, Value *To) {
3046 Storage.insert({ From, To });
3047 }
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003048
3049 void ReplacePhi(PHINode *From, PHINode *To) {
3050 Value* OldReplacement = Get(From);
3051 while (OldReplacement != From) {
3052 From = To;
3053 To = dyn_cast<PHINode>(OldReplacement);
3054 OldReplacement = Get(From);
3055 }
3056 assert(Get(To) == To && "Replacement PHI node is already replaced.");
3057 Put(From, To);
3058 From->replaceAllUsesWith(To);
Ali Tamurd482b012018-11-12 21:43:43 +00003059 AllPhiNodes.erase(From);
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003060 From->eraseFromParent();
3061 }
3062
Ali Tamurd482b012018-11-12 21:43:43 +00003063 PhiNodeSet& newPhiNodes() { return AllPhiNodes; }
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003064
3065 void insertNewPhi(PHINode *PN) { AllPhiNodes.insert(PN); }
3066
3067 void insertNewSelect(SelectInst *SI) { AllSelectNodes.insert(SI); }
3068
3069 unsigned countNewPhiNodes() const { return AllPhiNodes.size(); }
3070
3071 unsigned countNewSelectNodes() const { return AllSelectNodes.size(); }
3072
3073 void destroyNewNodes(Type *CommonType) {
3074 // For safe erasing, replace the uses with dummy value first.
3075 auto Dummy = UndefValue::get(CommonType);
3076 for (auto I : AllPhiNodes) {
3077 I->replaceAllUsesWith(Dummy);
3078 I->eraseFromParent();
3079 }
3080 AllPhiNodes.clear();
3081 for (auto I : AllSelectNodes) {
3082 I->replaceAllUsesWith(Dummy);
3083 I->eraseFromParent();
3084 }
3085 AllSelectNodes.clear();
3086 }
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003087};
3088
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003089/// A helper class for combining addressing modes.
John Brawn736bf002017-10-03 13:08:22 +00003090class AddressingModeCombiner {
Serguei Katkov2673f172018-11-29 06:45:18 +00003091 typedef DenseMap<Value *, Value *> FoldAddrToValueMapping;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003092 typedef std::pair<PHINode *, PHINode *> PHIPair;
3093
John Brawn736bf002017-10-03 13:08:22 +00003094private:
3095 /// The addressing modes we've collected.
3096 SmallVector<ExtAddrMode, 16> AddrModes;
3097
3098 /// The field in which the AddrModes differ, when we have more than one.
3099 ExtAddrMode::FieldName DifferentField = ExtAddrMode::NoField;
3100
3101 /// Are the AddrModes that we have all just equal to their original values?
3102 bool AllAddrModesTrivial = true;
3103
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003104 /// Common Type for all different fields in addressing modes.
3105 Type *CommonType;
3106
3107 /// SimplifyQuery for simplifyInstruction utility.
3108 const SimplifyQuery &SQ;
3109
3110 /// Original Address.
Serguei Katkov2673f172018-11-29 06:45:18 +00003111 Value *Original;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003112
John Brawn736bf002017-10-03 13:08:22 +00003113public:
Serguei Katkov2673f172018-11-29 06:45:18 +00003114 AddressingModeCombiner(const SimplifyQuery &_SQ, Value *OriginalValue)
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003115 : CommonType(nullptr), SQ(_SQ), Original(OriginalValue) {}
3116
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003117 /// Get the combined AddrMode
John Brawn736bf002017-10-03 13:08:22 +00003118 const ExtAddrMode &getAddrMode() const {
3119 return AddrModes[0];
3120 }
3121
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003122 /// Add a new AddrMode if it's compatible with the AddrModes we already
John Brawn736bf002017-10-03 13:08:22 +00003123 /// have.
3124 /// \return True iff we succeeded in doing so.
3125 bool addNewAddrMode(ExtAddrMode &NewAddrMode) {
3126 // Take note of if we have any non-trivial AddrModes, as we need to detect
3127 // when all AddrModes are trivial as then we would introduce a phi or select
3128 // which just duplicates what's already there.
3129 AllAddrModesTrivial = AllAddrModesTrivial && NewAddrMode.isTrivial();
3130
3131 // If this is the first addrmode then everything is fine.
3132 if (AddrModes.empty()) {
3133 AddrModes.emplace_back(NewAddrMode);
3134 return true;
3135 }
3136
3137 // Figure out how different this is from the other address modes, which we
3138 // can do just by comparing against the first one given that we only care
3139 // about the cumulative difference.
3140 ExtAddrMode::FieldName ThisDifferentField =
3141 AddrModes[0].compare(NewAddrMode);
3142 if (DifferentField == ExtAddrMode::NoField)
3143 DifferentField = ThisDifferentField;
3144 else if (DifferentField != ThisDifferentField)
3145 DifferentField = ExtAddrMode::MultipleFields;
3146
Serguei Katkov17e57942018-01-23 12:07:49 +00003147 // If NewAddrMode differs in more than one dimension we cannot handle it.
3148 bool CanHandle = DifferentField != ExtAddrMode::MultipleFields;
3149
3150 // If Scale Field is different then we reject.
3151 CanHandle = CanHandle && DifferentField != ExtAddrMode::ScaleField;
3152
Serguei Katkov4d1dd6b2018-01-09 04:37:06 +00003153 // We also must reject the case when base offset is different and
3154 // scale reg is not null, we cannot handle this case due to merge of
3155 // different offsets will be used as ScaleReg.
Serguei Katkov17e57942018-01-23 12:07:49 +00003156 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseOffsField ||
3157 !NewAddrMode.ScaledReg);
John Brawn736bf002017-10-03 13:08:22 +00003158
Serguei Katkov17e57942018-01-23 12:07:49 +00003159 // We also must reject the case when GV is different and BaseReg installed
3160 // due to we want to use base reg as a merge of GV values.
3161 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseGVField ||
3162 !NewAddrMode.HasBaseReg);
3163
3164 // Even if NewAddMode is the same we still need to collect it due to
3165 // original value is different. And later we will need all original values
3166 // as anchors during finding the common Phi node.
3167 if (CanHandle)
3168 AddrModes.emplace_back(NewAddrMode);
3169 else
3170 AddrModes.clear();
3171
3172 return CanHandle;
John Brawn736bf002017-10-03 13:08:22 +00003173 }
3174
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003175 /// Combine the addressing modes we've collected into a single
John Brawn736bf002017-10-03 13:08:22 +00003176 /// addressing mode.
3177 /// \return True iff we successfully combined them or we only had one so
3178 /// didn't need to combine them anyway.
3179 bool combineAddrModes() {
3180 // If we have no AddrModes then they can't be combined.
3181 if (AddrModes.size() == 0)
3182 return false;
3183
3184 // A single AddrMode can trivially be combined.
Serguei Katkov505359f2017-11-20 05:42:36 +00003185 if (AddrModes.size() == 1 || DifferentField == ExtAddrMode::NoField)
John Brawn736bf002017-10-03 13:08:22 +00003186 return true;
3187
3188 // If the AddrModes we collected are all just equal to the value they are
3189 // derived from then combining them wouldn't do anything useful.
3190 if (AllAddrModesTrivial)
3191 return false;
3192
John Brawn70cdb5b2017-11-24 14:10:45 +00003193 if (!addrModeCombiningAllowed())
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003194 return false;
3195
3196 // Build a map between <original value, basic block where we saw it> to
3197 // value of base register.
Serguei Katkov50364592017-11-29 05:51:26 +00003198 // Bail out if there is no common type.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003199 FoldAddrToValueMapping Map;
Serguei Katkov50364592017-11-29 05:51:26 +00003200 if (!initializeMap(Map))
3201 return false;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003202
3203 Value *CommonValue = findCommon(Map);
3204 if (CommonValue)
John Brawn70cdb5b2017-11-24 14:10:45 +00003205 AddrModes[0].SetCombinedField(DifferentField, CommonValue, AddrModes);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003206 return CommonValue != nullptr;
3207 }
3208
3209private:
Serguei Katkov2673f172018-11-29 06:45:18 +00003210 /// Initialize Map with anchor values. For address seen
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003211 /// we set the value of different field saw in this address.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003212 /// At the same time we find a common type for different field we will
3213 /// use to create new Phi/Select nodes. Keep it in CommonType field.
Serguei Katkov50364592017-11-29 05:51:26 +00003214 /// Return false if there is no common type found.
3215 bool initializeMap(FoldAddrToValueMapping &Map) {
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003216 // Keep track of keys where the value is null. We will need to replace it
3217 // with constant null when we know the common type.
Serguei Katkov2673f172018-11-29 06:45:18 +00003218 SmallVector<Value *, 2> NullValue;
John Brawn70cdb5b2017-11-24 14:10:45 +00003219 Type *IntPtrTy = SQ.DL.getIntPtrType(AddrModes[0].OriginalValue->getType());
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003220 for (auto &AM : AddrModes) {
John Brawn70cdb5b2017-11-24 14:10:45 +00003221 Value *DV = AM.GetFieldAsValue(DifferentField, IntPtrTy);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003222 if (DV) {
Serguei Katkov50364592017-11-29 05:51:26 +00003223 auto *Type = DV->getType();
3224 if (CommonType && CommonType != Type)
3225 return false;
3226 CommonType = Type;
Serguei Katkov2673f172018-11-29 06:45:18 +00003227 Map[AM.OriginalValue] = DV;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003228 } else {
Serguei Katkov2673f172018-11-29 06:45:18 +00003229 NullValue.push_back(AM.OriginalValue);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003230 }
3231 }
3232 assert(CommonType && "At least one non-null value must be!");
Serguei Katkov2673f172018-11-29 06:45:18 +00003233 for (auto *V : NullValue)
3234 Map[V] = Constant::getNullValue(CommonType);
Serguei Katkov50364592017-11-29 05:51:26 +00003235 return true;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003236 }
3237
Serguei Katkov2673f172018-11-29 06:45:18 +00003238 /// We have mapping between value A and other value B where B was a field in
3239 /// addressing mode represented by A. Also we have an original value C
3240 /// representing an address we start with. Traversing from C through phi and
3241 /// selects we ended up with A's in a map. This utility function tries to find
3242 /// a value V which is a field in addressing mode C and traversing through phi
3243 /// nodes and selects we will end up in corresponded values B in a map.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003244 /// The utility will create a new Phi/Selects if needed.
3245 // The simple example looks as follows:
3246 // BB1:
3247 // p1 = b1 + 40
3248 // br cond BB2, BB3
3249 // BB2:
3250 // p2 = b2 + 40
3251 // br BB3
3252 // BB3:
3253 // p = phi [p1, BB1], [p2, BB2]
3254 // v = load p
3255 // Map is
Serguei Katkov2673f172018-11-29 06:45:18 +00003256 // p1 -> b1
3257 // p2 -> b2
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003258 // Request is
Serguei Katkov2673f172018-11-29 06:45:18 +00003259 // p -> ?
3260 // The function tries to find or build phi [b1, BB1], [b2, BB2] in BB3.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003261 Value *findCommon(FoldAddrToValueMapping &Map) {
Eric Christopherd72f78e2018-01-09 23:25:38 +00003262 // Tracks the simplification of newly created phi nodes. The reason we use
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003263 // this mapping is because we will add new created Phi nodes in AddrToBase.
3264 // Simplification of Phi nodes is recursive, so some Phi node may
Serguei Katkov2673f172018-11-29 06:45:18 +00003265 // be simplified after we added it to AddrToBase. In reality this
3266 // simplification is possible only if original phi/selects were not
3267 // simplified yet.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003268 // Using this mapping we can find the current value in AddrToBase.
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003269 SimplificationTracker ST(SQ);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003270
3271 // First step, DFS to create PHI nodes for all intermediate blocks.
3272 // Also fill traverse order for the second step.
Serguei Katkov2673f172018-11-29 06:45:18 +00003273 SmallVector<Value *, 32> TraverseOrder;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003274 InsertPlaceholders(Map, TraverseOrder, ST);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003275
3276 // Second Step, fill new nodes by merged values and simplify if possible.
3277 FillPlaceholders(Map, TraverseOrder, ST);
3278
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003279 if (!AddrSinkNewSelects && ST.countNewSelectNodes() > 0) {
3280 ST.destroyNewNodes(CommonType);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003281 return nullptr;
3282 }
3283
3284 // Now we'd like to match New Phi nodes to existed ones.
3285 unsigned PhiNotMatchedCount = 0;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003286 if (!MatchPhiSet(ST, AddrSinkNewPhis, PhiNotMatchedCount)) {
3287 ST.destroyNewNodes(CommonType);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003288 return nullptr;
3289 }
3290
3291 auto *Result = ST.Get(Map.find(Original)->second);
3292 if (Result) {
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003293 NumMemoryInstsPhiCreated += ST.countNewPhiNodes() + PhiNotMatchedCount;
3294 NumMemoryInstsSelectCreated += ST.countNewSelectNodes();
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003295 }
3296 return Result;
3297 }
3298
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003299 /// Try to match PHI node to Candidate.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003300 /// Matcher tracks the matched Phi nodes.
3301 bool MatchPhiNode(PHINode *PHI, PHINode *Candidate,
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003302 SmallSetVector<PHIPair, 8> &Matcher,
Ali Tamurd482b012018-11-12 21:43:43 +00003303 PhiNodeSet &PhiNodesToMatch) {
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003304 SmallVector<PHIPair, 8> WorkList;
3305 Matcher.insert({ PHI, Candidate });
Mikael Holmen339daae2019-03-15 13:51:05 +00003306 SmallSet<PHINode *, 8> MatchedPHIs;
3307 MatchedPHIs.insert(PHI);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003308 WorkList.push_back({ PHI, Candidate });
3309 SmallSet<PHIPair, 8> Visited;
3310 while (!WorkList.empty()) {
3311 auto Item = WorkList.pop_back_val();
3312 if (!Visited.insert(Item).second)
3313 continue;
3314 // We iterate over all incoming values to Phi to compare them.
3315 // If values are different and both of them Phi and the first one is a
3316 // Phi we added (subject to match) and both of them is in the same basic
3317 // block then we can match our pair if values match. So we state that
3318 // these values match and add it to work list to verify that.
3319 for (auto B : Item.first->blocks()) {
3320 Value *FirstValue = Item.first->getIncomingValueForBlock(B);
3321 Value *SecondValue = Item.second->getIncomingValueForBlock(B);
3322 if (FirstValue == SecondValue)
3323 continue;
3324
3325 PHINode *FirstPhi = dyn_cast<PHINode>(FirstValue);
3326 PHINode *SecondPhi = dyn_cast<PHINode>(SecondValue);
3327
3328 // One of them is not Phi or
3329 // The first one is not Phi node from the set we'd like to match or
3330 // Phi nodes from different basic blocks then
3331 // we will not be able to match.
3332 if (!FirstPhi || !SecondPhi || !PhiNodesToMatch.count(FirstPhi) ||
3333 FirstPhi->getParent() != SecondPhi->getParent())
3334 return false;
3335
3336 // If we already matched them then continue.
3337 if (Matcher.count({ FirstPhi, SecondPhi }))
3338 continue;
3339 // So the values are different and does not match. So we need them to
Mikael Holmen339daae2019-03-15 13:51:05 +00003340 // match. (But we register no more than one match per PHI node, so that
3341 // we won't later try to replace them twice.)
3342 if (!MatchedPHIs.insert(FirstPhi).second)
3343 Matcher.insert({ FirstPhi, SecondPhi });
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003344 // But me must check it.
3345 WorkList.push_back({ FirstPhi, SecondPhi });
3346 }
3347 }
3348 return true;
3349 }
3350
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003351 /// For the given set of PHI nodes (in the SimplificationTracker) try
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003352 /// to find their equivalents.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003353 /// Returns false if this matching fails and creation of new Phi is disabled.
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003354 bool MatchPhiSet(SimplificationTracker &ST, bool AllowNewPhiNodes,
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003355 unsigned &PhiNotMatchedCount) {
Ali Tamurd482b012018-11-12 21:43:43 +00003356 // Matched and PhiNodesToMatch iterate their elements in a deterministic
3357 // order, so the replacements (ReplacePhi) are also done in a deterministic
3358 // order.
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003359 SmallSetVector<PHIPair, 8> Matched;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003360 SmallPtrSet<PHINode *, 8> WillNotMatch;
Ali Tamurd482b012018-11-12 21:43:43 +00003361 PhiNodeSet &PhiNodesToMatch = ST.newPhiNodes();
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003362 while (PhiNodesToMatch.size()) {
3363 PHINode *PHI = *PhiNodesToMatch.begin();
3364
3365 // Add us, if no Phi nodes in the basic block we do not match.
3366 WillNotMatch.clear();
3367 WillNotMatch.insert(PHI);
3368
3369 // Traverse all Phis until we found equivalent or fail to do that.
3370 bool IsMatched = false;
3371 for (auto &P : PHI->getParent()->phis()) {
3372 if (&P == PHI)
3373 continue;
3374 if ((IsMatched = MatchPhiNode(PHI, &P, Matched, PhiNodesToMatch)))
3375 break;
3376 // If it does not match, collect all Phi nodes from matcher.
3377 // if we end up with no match, them all these Phi nodes will not match
3378 // later.
3379 for (auto M : Matched)
3380 WillNotMatch.insert(M.first);
3381 Matched.clear();
3382 }
3383 if (IsMatched) {
Serguei Katkova20e05b2018-03-12 03:50:07 +00003384 // Replace all matched values and erase them.
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003385 for (auto MV : Matched)
3386 ST.ReplacePhi(MV.first, MV.second);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003387 Matched.clear();
3388 continue;
3389 }
3390 // If we are not allowed to create new nodes then bail out.
3391 if (!AllowNewPhiNodes)
3392 return false;
3393 // Just remove all seen values in matcher. They will not match anything.
3394 PhiNotMatchedCount += WillNotMatch.size();
3395 for (auto *P : WillNotMatch)
Ali Tamurd482b012018-11-12 21:43:43 +00003396 PhiNodesToMatch.erase(P);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003397 }
3398 return true;
3399 }
Serguei Katkov2673f172018-11-29 06:45:18 +00003400 /// Fill the placeholders with values from predecessors and simplify them.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003401 void FillPlaceholders(FoldAddrToValueMapping &Map,
Serguei Katkov2673f172018-11-29 06:45:18 +00003402 SmallVectorImpl<Value *> &TraverseOrder,
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003403 SimplificationTracker &ST) {
3404 while (!TraverseOrder.empty()) {
Serguei Katkov2673f172018-11-29 06:45:18 +00003405 Value *Current = TraverseOrder.pop_back_val();
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003406 assert(Map.find(Current) != Map.end() && "No node to fill!!!");
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003407 Value *V = Map[Current];
3408
3409 if (SelectInst *Select = dyn_cast<SelectInst>(V)) {
3410 // CurrentValue also must be Select.
Serguei Katkov2673f172018-11-29 06:45:18 +00003411 auto *CurrentSelect = cast<SelectInst>(Current);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003412 auto *TrueValue = CurrentSelect->getTrueValue();
Serguei Katkov2673f172018-11-29 06:45:18 +00003413 assert(Map.find(TrueValue) != Map.end() && "No True Value!");
3414 Select->setTrueValue(ST.Get(Map[TrueValue]));
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003415 auto *FalseValue = CurrentSelect->getFalseValue();
Serguei Katkov2673f172018-11-29 06:45:18 +00003416 assert(Map.find(FalseValue) != Map.end() && "No False Value!");
3417 Select->setFalseValue(ST.Get(Map[FalseValue]));
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003418 } else {
3419 // Must be a Phi node then.
3420 PHINode *PHI = cast<PHINode>(V);
Serguei Katkov2673f172018-11-29 06:45:18 +00003421 auto *CurrentPhi = dyn_cast<PHINode>(Current);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003422 // Fill the Phi node with values from predecessors.
Serguei Katkov2673f172018-11-29 06:45:18 +00003423 for (auto B : predecessors(PHI->getParent())) {
3424 Value *PV = CurrentPhi->getIncomingValueForBlock(B);
3425 assert(Map.find(PV) != Map.end() && "No predecessor Value!");
3426 PHI->addIncoming(ST.Get(Map[PV]), B);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003427 }
3428 }
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003429 Map[Current] = ST.Simplify(V);
3430 }
3431 }
3432
Serguei Katkov2673f172018-11-29 06:45:18 +00003433 /// Starting from original value recursively iterates over def-use chain up to
3434 /// known ending values represented in a map. For each traversed phi/select
3435 /// inserts a placeholder Phi or Select.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003436 /// Reports all new created Phi/Select nodes by adding them to set.
Serguei Katkov2673f172018-11-29 06:45:18 +00003437 /// Also reports and order in what values have been traversed.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003438 void InsertPlaceholders(FoldAddrToValueMapping &Map,
Serguei Katkov2673f172018-11-29 06:45:18 +00003439 SmallVectorImpl<Value *> &TraverseOrder,
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003440 SimplificationTracker &ST) {
Serguei Katkov2673f172018-11-29 06:45:18 +00003441 SmallVector<Value *, 32> Worklist;
3442 assert((isa<PHINode>(Original) || isa<SelectInst>(Original)) &&
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003443 "Address must be a Phi or Select node");
3444 auto *Dummy = UndefValue::get(CommonType);
3445 Worklist.push_back(Original);
3446 while (!Worklist.empty()) {
Serguei Katkov2673f172018-11-29 06:45:18 +00003447 Value *Current = Worklist.pop_back_val();
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003448 // if it is already visited or it is an ending value then skip it.
3449 if (Map.find(Current) != Map.end())
3450 continue;
3451 TraverseOrder.push_back(Current);
3452
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003453 // CurrentValue must be a Phi node or select. All others must be covered
3454 // by anchors.
Serguei Katkov2673f172018-11-29 06:45:18 +00003455 if (SelectInst *CurrentSelect = dyn_cast<SelectInst>(Current)) {
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003456 // Is it OK to get metadata from OrigSelect?!
3457 // Create a Select placeholder with dummy value.
Serguei Katkov2673f172018-11-29 06:45:18 +00003458 SelectInst *Select = SelectInst::Create(
3459 CurrentSelect->getCondition(), Dummy, Dummy,
3460 CurrentSelect->getName(), CurrentSelect, CurrentSelect);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003461 Map[Current] = Select;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003462 ST.insertNewSelect(Select);
Serguei Katkov2673f172018-11-29 06:45:18 +00003463 // We are interested in True and False values.
3464 Worklist.push_back(CurrentSelect->getTrueValue());
3465 Worklist.push_back(CurrentSelect->getFalseValue());
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003466 } else {
3467 // It must be a Phi node then.
Serguei Katkov2673f172018-11-29 06:45:18 +00003468 PHINode *CurrentPhi = cast<PHINode>(Current);
3469 unsigned PredCount = CurrentPhi->getNumIncomingValues();
3470 PHINode *PHI =
3471 PHINode::Create(CommonType, PredCount, "sunk_phi", CurrentPhi);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003472 Map[Current] = PHI;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003473 ST.insertNewPhi(PHI);
Serguei Katkov2673f172018-11-29 06:45:18 +00003474 for (Value *P : CurrentPhi->incoming_values())
3475 Worklist.push_back(P);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003476 }
3477 }
John Brawn736bf002017-10-03 13:08:22 +00003478 }
John Brawn70cdb5b2017-11-24 14:10:45 +00003479
3480 bool addrModeCombiningAllowed() {
3481 if (DisableComplexAddrModes)
3482 return false;
3483 switch (DifferentField) {
3484 default:
3485 return false;
3486 case ExtAddrMode::BaseRegField:
3487 return AddrSinkCombineBaseReg;
3488 case ExtAddrMode::BaseGVField:
3489 return AddrSinkCombineBaseGV;
3490 case ExtAddrMode::BaseOffsField:
3491 return AddrSinkCombineBaseOffs;
3492 case ExtAddrMode::ScaledRegField:
3493 return AddrSinkCombineScaledReg;
3494 }
3495 }
John Brawn736bf002017-10-03 13:08:22 +00003496};
Eugene Zelenko900b6332017-08-29 22:32:07 +00003497} // end anonymous namespace
3498
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003499/// Try adding ScaleReg*Scale to the current addressing mode.
Chandler Carruthc8925912013-01-05 02:09:22 +00003500/// Return true and update AddrMode if this addr mode is legal for the target,
3501/// false if not.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003502bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
Chandler Carruthc8925912013-01-05 02:09:22 +00003503 unsigned Depth) {
3504 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
3505 // mode. Just process that directly.
3506 if (Scale == 1)
Sanjay Patelfc580a62015-09-21 23:03:16 +00003507 return matchAddr(ScaleReg, Depth);
Stephen Lin837bba12013-07-15 17:55:02 +00003508
Chandler Carruthc8925912013-01-05 02:09:22 +00003509 // If the scale is 0, it takes nothing to add this.
3510 if (Scale == 0)
3511 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003512
Chandler Carruthc8925912013-01-05 02:09:22 +00003513 // If we already have a scale of this value, we can add to it, otherwise, we
3514 // need an available scale field.
3515 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
3516 return false;
3517
3518 ExtAddrMode TestAddrMode = AddrMode;
3519
3520 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
3521 // [A+B + A*7] -> [B+A*8].
3522 TestAddrMode.Scale += Scale;
3523 TestAddrMode.ScaledReg = ScaleReg;
3524
3525 // If the new address isn't legal, bail out.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003526 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003527 return false;
3528
3529 // It was legal, so commit it.
3530 AddrMode = TestAddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00003531
Chandler Carruthc8925912013-01-05 02:09:22 +00003532 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
3533 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
3534 // X*Scale + C*Scale to addr mode.
Craig Topperc0196b12014-04-14 00:51:57 +00003535 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003536 if (isa<Instruction>(ScaleReg) && // not a constant expr.
3537 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
Tim Northover8935aca2019-03-12 15:22:23 +00003538 TestAddrMode.InBounds = false;
Chandler Carruthc8925912013-01-05 02:09:22 +00003539 TestAddrMode.ScaledReg = AddLHS;
3540 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00003541
Chandler Carruthc8925912013-01-05 02:09:22 +00003542 // If this addressing mode is legal, commit it and remember that we folded
3543 // this instruction.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003544 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003545 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
3546 AddrMode = TestAddrMode;
3547 return true;
3548 }
3549 }
3550
3551 // Otherwise, not (x+c)*scale, just return what we have.
3552 return true;
3553}
3554
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003555/// This is a little filter, which returns true if an addressing computation
3556/// involving I might be folded into a load/store accessing it.
3557/// This doesn't need to be perfect, but needs to accept at least
Chandler Carruthc8925912013-01-05 02:09:22 +00003558/// the set of instructions that MatchOperationAddr can.
3559static bool MightBeFoldableInst(Instruction *I) {
3560 switch (I->getOpcode()) {
3561 case Instruction::BitCast:
Eli Benderskyf13a0562014-05-22 00:02:52 +00003562 case Instruction::AddrSpaceCast:
Chandler Carruthc8925912013-01-05 02:09:22 +00003563 // Don't touch identity bitcasts.
3564 if (I->getType() == I->getOperand(0)->getType())
3565 return false;
Vedant Kumarb3091da2018-07-06 20:17:42 +00003566 return I->getType()->isIntOrPtrTy();
Chandler Carruthc8925912013-01-05 02:09:22 +00003567 case Instruction::PtrToInt:
3568 // PtrToInt is always a noop, as we know that the int type is pointer sized.
3569 return true;
3570 case Instruction::IntToPtr:
3571 // We know the input is intptr_t, so this is foldable.
3572 return true;
3573 case Instruction::Add:
3574 return true;
3575 case Instruction::Mul:
3576 case Instruction::Shl:
3577 // Can only handle X*C and X << C.
3578 return isa<ConstantInt>(I->getOperand(1));
3579 case Instruction::GetElementPtr:
3580 return true;
3581 default:
3582 return false;
3583 }
3584}
3585
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003586/// Check whether or not \p Val is a legal instruction for \p TLI.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003587/// \note \p Val is assumed to be the product of some type promotion.
3588/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
3589/// to be legal, as the non-promoted value would have had the same state.
Mehdi Amini44ede332015-07-09 02:09:04 +00003590static bool isPromotedInstructionLegal(const TargetLowering &TLI,
3591 const DataLayout &DL, Value *Val) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003592 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
3593 if (!PromotedInst)
3594 return false;
3595 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
3596 // If the ISDOpcode is undefined, it was undefined before the promotion.
3597 if (!ISDOpcode)
3598 return true;
3599 // Otherwise, check if the promoted instruction is legal or not.
3600 return TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00003601 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003602}
3603
Eugene Zelenko900b6332017-08-29 22:32:07 +00003604namespace {
3605
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003606/// Hepler class to perform type promotion.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003607class TypePromotionHelper {
Guozhi Wei8c17f9a2018-08-15 22:08:26 +00003608 /// Utility function to add a promoted instruction \p ExtOpnd to
3609 /// \p PromotedInsts and record the type of extension we have seen.
3610 static void addPromotedInst(InstrToOrigTy &PromotedInsts,
3611 Instruction *ExtOpnd,
3612 bool IsSExt) {
3613 ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension;
3614 InstrToOrigTy::iterator It = PromotedInsts.find(ExtOpnd);
3615 if (It != PromotedInsts.end()) {
3616 // If the new extension is same as original, the information in
3617 // PromotedInsts[ExtOpnd] is still correct.
3618 if (It->second.getInt() == ExtTy)
3619 return;
3620
3621 // Now the new extension is different from old extension, we make
3622 // the type information invalid by setting extension type to
3623 // BothExtension.
3624 ExtTy = BothExtension;
3625 }
3626 PromotedInsts[ExtOpnd] = TypeIsSExt(ExtOpnd->getType(), ExtTy);
3627 }
3628
3629 /// Utility function to query the original type of instruction \p Opnd
3630 /// with a matched extension type. If the extension doesn't match, we
3631 /// cannot use the information we had on the original type.
3632 /// BothExtension doesn't match any extension type.
3633 static const Type *getOrigType(const InstrToOrigTy &PromotedInsts,
3634 Instruction *Opnd,
3635 bool IsSExt) {
3636 ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension;
3637 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
3638 if (It != PromotedInsts.end() && It->second.getInt() == ExtTy)
3639 return It->second.getPointer();
3640 return nullptr;
3641 }
3642
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003643 /// Utility function to check whether or not a sign or zero extension
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003644 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
3645 /// either using the operands of \p Inst or promoting \p Inst.
3646 /// The type of the extension is defined by \p IsSExt.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003647 /// In other words, check if:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003648 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003649 /// #1 Promotion applies:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003650 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003651 /// #2 Operand reuses:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003652 /// ext opnd1 to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003653 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003654 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
3655 const InstrToOrigTy &PromotedInsts, bool IsSExt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003656
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003657 /// Utility function to determine if \p OpIdx should be promoted when
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003658 /// promoting \p Inst.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003659 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
Rafael Espindola84921b92015-10-24 23:11:13 +00003660 return !(isa<SelectInst>(Inst) && OpIdx == 0);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003661 }
3662
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003663 /// Utility function to promote the operand of \p Ext when this
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003664 /// operand is a promotable trunc or sext or zext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003665 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003666 /// \p CreatedInstsCost[out] contains the cost of all instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003667 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003668 /// Newly added extensions are inserted in \p Exts.
3669 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003670 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003671 /// \return The promoted value which is used instead of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003672 static Value *promoteOperandForTruncAndAnyExt(
3673 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003674 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003675 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003676 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003677
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003678 /// Utility function to promote the operand of \p Ext when this
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003679 /// operand is promotable and is not a supported trunc or sext.
3680 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003681 /// \p CreatedInstsCost[out] contains the cost of all the instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003682 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003683 /// Newly added extensions are inserted in \p Exts.
3684 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003685 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003686 /// \return The promoted value which is used instead of Ext.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003687 static Value *promoteOperandForOther(Instruction *Ext,
3688 TypePromotionTransaction &TPT,
3689 InstrToOrigTy &PromotedInsts,
3690 unsigned &CreatedInstsCost,
3691 SmallVectorImpl<Instruction *> *Exts,
3692 SmallVectorImpl<Instruction *> *Truncs,
3693 const TargetLowering &TLI, bool IsSExt);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003694
3695 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003696 static Value *signExtendOperandForOther(
3697 Instruction *Ext, TypePromotionTransaction &TPT,
3698 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3699 SmallVectorImpl<Instruction *> *Exts,
3700 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3701 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3702 Exts, Truncs, TLI, true);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003703 }
3704
3705 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003706 static Value *zeroExtendOperandForOther(
3707 Instruction *Ext, TypePromotionTransaction &TPT,
3708 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3709 SmallVectorImpl<Instruction *> *Exts,
3710 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3711 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3712 Exts, Truncs, TLI, false);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003713 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003714
3715public:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003716 /// Type for the utility function that promotes the operand of Ext.
Eugene Zelenko900b6332017-08-29 22:32:07 +00003717 using Action = Value *(*)(Instruction *Ext, TypePromotionTransaction &TPT,
3718 InstrToOrigTy &PromotedInsts,
3719 unsigned &CreatedInstsCost,
3720 SmallVectorImpl<Instruction *> *Exts,
3721 SmallVectorImpl<Instruction *> *Truncs,
3722 const TargetLowering &TLI);
3723
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00003724 /// Given a sign/zero extend instruction \p Ext, return the appropriate
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003725 /// action to promote the operand of \p Ext instead of using Ext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003726 /// \return NULL if no promotable action is possible with the current
3727 /// sign extension.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003728 /// \p InsertedInsts keeps track of all the instructions inserted by the
3729 /// other CodeGenPrepare optimizations. This information is important
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003730 /// because we do not want to promote these instructions as CodeGenPrepare
3731 /// will reinsert them later. Thus creating an infinite loop: create/remove.
3732 /// \p PromotedInsts maps the instructions to their type before promotion.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003733 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003734 const TargetLowering &TLI,
3735 const InstrToOrigTy &PromotedInsts);
3736};
3737
Eugene Zelenko900b6332017-08-29 22:32:07 +00003738} // end anonymous namespace
3739
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003740bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003741 Type *ConsideredExtType,
3742 const InstrToOrigTy &PromotedInsts,
3743 bool IsSExt) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003744 // The promotion helper does not know how to deal with vector types yet.
3745 // To be able to fix that, we would need to fix the places where we
3746 // statically extend, e.g., constants and such.
3747 if (Inst->getType()->isVectorTy())
3748 return false;
3749
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003750 // We can always get through zext.
3751 if (isa<ZExtInst>(Inst))
3752 return true;
3753
3754 // sext(sext) is ok too.
3755 if (IsSExt && isa<SExtInst>(Inst))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003756 return true;
3757
3758 // We can get through binary operator, if it is legal. In other words, the
3759 // binary operator must have a nuw or nsw flag.
3760 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
3761 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003762 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
3763 (IsSExt && BinOp->hasNoSignedWrap())))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003764 return true;
3765
Guozhi Weic4c6b542018-06-05 21:03:52 +00003766 // ext(and(opnd, cst)) --> and(ext(opnd), ext(cst))
3767 if ((Inst->getOpcode() == Instruction::And ||
3768 Inst->getOpcode() == Instruction::Or))
3769 return true;
3770
3771 // ext(xor(opnd, cst)) --> xor(ext(opnd), ext(cst))
3772 if (Inst->getOpcode() == Instruction::Xor) {
3773 const ConstantInt *Cst = dyn_cast<ConstantInt>(Inst->getOperand(1));
3774 // Make sure it is not a NOT.
3775 if (Cst && !Cst->getValue().isAllOnesValue())
3776 return true;
3777 }
3778
3779 // zext(shrl(opnd, cst)) --> shrl(zext(opnd), zext(cst))
3780 // It may change a poisoned value into a regular value, like
3781 // zext i32 (shrl i8 %val, 12) --> shrl i32 (zext i8 %val), 12
3782 // poisoned value regular value
3783 // It should be OK since undef covers valid value.
3784 if (Inst->getOpcode() == Instruction::LShr && !IsSExt)
3785 return true;
3786
3787 // and(ext(shl(opnd, cst)), cst) --> and(shl(ext(opnd), ext(cst)), cst)
3788 // It may change a poisoned value into a regular value, like
3789 // zext i32 (shl i8 %val, 12) --> shl i32 (zext i8 %val), 12
3790 // poisoned value regular value
3791 // It should be OK since undef covers valid value.
3792 if (Inst->getOpcode() == Instruction::Shl && Inst->hasOneUse()) {
3793 const Instruction *ExtInst =
3794 dyn_cast<const Instruction>(*Inst->user_begin());
3795 if (ExtInst->hasOneUse()) {
3796 const Instruction *AndInst =
3797 dyn_cast<const Instruction>(*ExtInst->user_begin());
3798 if (AndInst && AndInst->getOpcode() == Instruction::And) {
3799 const ConstantInt *Cst = dyn_cast<ConstantInt>(AndInst->getOperand(1));
3800 if (Cst &&
3801 Cst->getValue().isIntN(Inst->getType()->getIntegerBitWidth()))
3802 return true;
3803 }
3804 }
3805 }
3806
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003807 // Check if we can do the following simplification.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003808 // ext(trunc(opnd)) --> ext(opnd)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003809 if (!isa<TruncInst>(Inst))
3810 return false;
3811
3812 Value *OpndVal = Inst->getOperand(0);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003813 // Check if we can use this operand in the extension.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003814 // If the type is larger than the result type of the extension, we cannot.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003815 if (!OpndVal->getType()->isIntegerTy() ||
3816 OpndVal->getType()->getIntegerBitWidth() >
3817 ConsideredExtType->getIntegerBitWidth())
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003818 return false;
3819
3820 // If the operand of the truncate is not an instruction, we will not have
3821 // any information on the dropped bits.
3822 // (Actually we could for constant but it is not worth the extra logic).
3823 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
3824 if (!Opnd)
3825 return false;
3826
3827 // Check if the source of the type is narrow enough.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003828 // I.e., check that trunc just drops extended bits of the same kind of
3829 // the extension.
3830 // #1 get the type of the operand and check the kind of the extended bits.
Guozhi Wei8c17f9a2018-08-15 22:08:26 +00003831 const Type *OpndType = getOrigType(PromotedInsts, Opnd, IsSExt);
3832 if (OpndType)
3833 ;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003834 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
3835 OpndType = Opnd->getOperand(0)->getType();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003836 else
3837 return false;
3838
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003839 // #2 check that the truncate just drops extended bits.
Rafael Espindola84921b92015-10-24 23:11:13 +00003840 return Inst->getType()->getIntegerBitWidth() >=
3841 OpndType->getIntegerBitWidth();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003842}
3843
3844TypePromotionHelper::Action TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003845 Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003846 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003847 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
3848 "Unexpected instruction type");
3849 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
3850 Type *ExtTy = Ext->getType();
3851 bool IsSExt = isa<SExtInst>(Ext);
3852 // If the operand of the extension is not an instruction, we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003853 // get through.
3854 // If it, check we can get through.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003855 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
Craig Topperc0196b12014-04-14 00:51:57 +00003856 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003857
3858 // Do not promote if the operand has been added by codegenprepare.
3859 // Otherwise, it means we are undoing an optimization that is likely to be
3860 // redone, thus causing potential infinite loop.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003861 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
Craig Topperc0196b12014-04-14 00:51:57 +00003862 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003863
3864 // SExt or Trunc instructions.
3865 // Return the related handler.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003866 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
3867 isa<ZExtInst>(ExtOpnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003868 return promoteOperandForTruncAndAnyExt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003869
3870 // Regular instruction.
3871 // Abort early if we will have to insert non-free instructions.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003872 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
Craig Topperc0196b12014-04-14 00:51:57 +00003873 return nullptr;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003874 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003875}
3876
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003877Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
Eugene Zelenko900b6332017-08-29 22:32:07 +00003878 Instruction *SExt, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003879 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003880 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003881 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003882 // By construction, the operand of SExt is an instruction. Otherwise we cannot
3883 // get through it and this method should not be called.
3884 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
Quentin Colombetac55b152014-09-16 22:36:07 +00003885 Value *ExtVal = SExt;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003886 bool HasMergedNonFreeExt = false;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003887 if (isa<ZExtInst>(SExtOpnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003888 // Replace s|zext(zext(opnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003889 // => zext(opnd).
Quentin Colombet1b274f92015-03-10 21:48:15 +00003890 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00003891 Value *ZExt =
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003892 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
3893 TPT.replaceAllUsesWith(SExt, ZExt);
3894 TPT.eraseInstruction(SExt);
Quentin Colombetac55b152014-09-16 22:36:07 +00003895 ExtVal = ZExt;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003896 } else {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003897 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
3898 // => z|sext(opnd).
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003899 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
3900 }
Quentin Colombet1b274f92015-03-10 21:48:15 +00003901 CreatedInstsCost = 0;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003902
3903 // Remove dead code.
3904 if (SExtOpnd->use_empty())
3905 TPT.eraseInstruction(SExtOpnd);
3906
Quentin Colombet9dcb7242014-09-15 18:26:58 +00003907 // Check if the extension is still needed.
Quentin Colombetac55b152014-09-16 22:36:07 +00003908 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003909 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
Quentin Colombet1b274f92015-03-10 21:48:15 +00003910 if (ExtInst) {
3911 if (Exts)
3912 Exts->push_back(ExtInst);
3913 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
3914 }
Quentin Colombetac55b152014-09-16 22:36:07 +00003915 return ExtVal;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003916 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003917
Quentin Colombet9dcb7242014-09-15 18:26:58 +00003918 // At this point we have: ext ty opnd to ty.
3919 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
3920 Value *NextVal = ExtInst->getOperand(0);
3921 TPT.eraseInstruction(ExtInst, NextVal);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003922 return NextVal;
3923}
3924
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003925Value *TypePromotionHelper::promoteOperandForOther(
3926 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003927 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003928 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003929 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
3930 bool IsSExt) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003931 // By construction, the operand of Ext is an instruction. Otherwise we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003932 // get through it and this method should not be called.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003933 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
Quentin Colombet1b274f92015-03-10 21:48:15 +00003934 CreatedInstsCost = 0;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003935 if (!ExtOpnd->hasOneUse()) {
3936 // ExtOpnd will be promoted.
3937 // All its uses, but Ext, will need to use a truncated value of the
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003938 // promoted version.
3939 // Create the truncate now.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003940 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
Quentin Colombetac55b152014-09-16 22:36:07 +00003941 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
Quentin Colombetac55b152014-09-16 22:36:07 +00003942 // Insert it just after the definition.
Sanjay Patel674d2c22017-08-29 14:07:48 +00003943 ITrunc->moveAfter(ExtOpnd);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003944 if (Truncs)
3945 Truncs->push_back(ITrunc);
Quentin Colombetac55b152014-09-16 22:36:07 +00003946 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003947
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003948 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003949 // Restore the operand of Ext (which has been replaced by the previous call
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003950 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003951 TPT.setOperand(Ext, 0, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003952 }
3953
3954 // Get through the Instruction:
3955 // 1. Update its type.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003956 // 2. Replace the uses of Ext by Inst.
3957 // 3. Extend each operand that needs to be extended.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003958
3959 // Remember the original type of the instruction before promotion.
3960 // This is useful to know that the high bits are sign extended bits.
Guozhi Wei8c17f9a2018-08-15 22:08:26 +00003961 addPromotedInst(PromotedInsts, ExtOpnd, IsSExt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003962 // Step #1.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003963 TPT.mutateType(ExtOpnd, Ext->getType());
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003964 // Step #2.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003965 TPT.replaceAllUsesWith(Ext, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003966 // Step #3.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003967 Instruction *ExtForOpnd = Ext;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003968
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003969 LLVM_DEBUG(dbgs() << "Propagate Ext to operands\n");
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003970 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003971 ++OpIdx) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003972 LLVM_DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003973 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
3974 !shouldExtOperand(ExtOpnd, OpIdx)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003975 LLVM_DEBUG(dbgs() << "No need to propagate\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003976 continue;
3977 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003978 // Check if we can statically extend the operand.
3979 Value *Opnd = ExtOpnd->getOperand(OpIdx);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003980 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003981 LLVM_DEBUG(dbgs() << "Statically extend\n");
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003982 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
3983 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
3984 : Cst->getValue().zext(BitWidth);
3985 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003986 continue;
3987 }
3988 // UndefValue are typed, so we have to statically sign extend them.
3989 if (isa<UndefValue>(Opnd)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003990 LLVM_DEBUG(dbgs() << "Statically extend\n");
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003991 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003992 continue;
3993 }
3994
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00003995 // Otherwise we have to explicitly sign extend the operand.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003996 // Check if Ext was reused to extend an operand.
3997 if (!ExtForOpnd) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003998 // If yes, create a new one.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003999 LLVM_DEBUG(dbgs() << "More operands to ext\n");
Quentin Colombet84f89cc2014-12-22 18:11:52 +00004000 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
4001 : TPT.createZExt(Ext, Opnd, Ext->getType());
4002 if (!isa<Instruction>(ValForExtOpnd)) {
4003 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
4004 continue;
4005 }
4006 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004007 }
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004008 if (Exts)
4009 Exts->push_back(ExtForOpnd);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00004010 TPT.setOperand(ExtForOpnd, 0, Opnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004011
4012 // Move the sign extension before the insertion point.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00004013 TPT.moveBefore(ExtForOpnd, ExtOpnd);
4014 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
Quentin Colombet1b274f92015-03-10 21:48:15 +00004015 CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004016 // If more sext are required, new instructions will have to be created.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00004017 ExtForOpnd = nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004018 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00004019 if (ExtForOpnd == Ext) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004020 LLVM_DEBUG(dbgs() << "Extension is useless now\n");
Quentin Colombetf5485bb2014-11-13 01:44:51 +00004021 TPT.eraseInstruction(Ext);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004022 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00004023 return ExtOpnd;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004024}
4025
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004026/// Check whether or not promoting an instruction to a wider type is profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004027/// \p NewCost gives the cost of extension instructions created by the
4028/// promotion.
4029/// \p OldCost gives the cost of extension instructions before the promotion
4030/// plus the number of instructions that have been
4031/// matched in the addressing mode the promotion.
Quentin Colombet867c5502014-02-14 22:23:22 +00004032/// \p PromotedOperand is the value that has been promoted.
4033/// \return True if the promotion is profitable, false otherwise.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004034bool AddressingModeMatcher::isPromotionProfitable(
Quentin Colombet1b274f92015-03-10 21:48:15 +00004035 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004036 LLVM_DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost
4037 << '\n');
Quentin Colombet1b274f92015-03-10 21:48:15 +00004038 // The cost of the new extensions is greater than the cost of the
4039 // old extension plus what we folded.
Quentin Colombet867c5502014-02-14 22:23:22 +00004040 // This is not profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004041 if (NewCost > OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00004042 return false;
Quentin Colombet1b274f92015-03-10 21:48:15 +00004043 if (NewCost < OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00004044 return true;
4045 // The promotion is neutral but it may help folding the sign extension in
4046 // loads for instance.
4047 // Check that we did not create an illegal instruction.
Mehdi Amini44ede332015-07-09 02:09:04 +00004048 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
Quentin Colombet867c5502014-02-14 22:23:22 +00004049}
4050
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004051/// Given an instruction or constant expr, see if we can fold the operation
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00004052/// into the addressing mode. If so, update the addressing mode and return
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004053/// true, otherwise return false without modifying AddrMode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004054/// If \p MovedAway is not NULL, it contains the information of whether or
4055/// not AddrInst has to be folded into the addressing mode on success.
4056/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
4057/// because it has been moved away.
4058/// Thus AddrInst must not be added in the matched instructions.
4059/// This state can happen when AddrInst is a sext, since it may be moved away.
4060/// Therefore, AddrInst may not be valid when MovedAway is true and it must
4061/// not be referenced anymore.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004062bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004063 unsigned Depth,
4064 bool *MovedAway) {
Chandler Carruthc8925912013-01-05 02:09:22 +00004065 // Avoid exponential behavior on extremely deep expression trees.
4066 if (Depth >= 5) return false;
Stephen Lin837bba12013-07-15 17:55:02 +00004067
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004068 // By default, all matched instructions stay in place.
4069 if (MovedAway)
4070 *MovedAway = false;
4071
Chandler Carruthc8925912013-01-05 02:09:22 +00004072 switch (Opcode) {
4073 case Instruction::PtrToInt:
4074 // PtrToInt is always a noop, as we know that the int type is pointer sized.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004075 return matchAddr(AddrInst->getOperand(0), Depth);
Mehdi Amini44ede332015-07-09 02:09:04 +00004076 case Instruction::IntToPtr: {
4077 auto AS = AddrInst->getType()->getPointerAddressSpace();
4078 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
Chandler Carruthc8925912013-01-05 02:09:22 +00004079 // This inttoptr is a no-op if the integer type is pointer sized.
Mehdi Amini44ede332015-07-09 02:09:04 +00004080 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
Sanjay Patelfc580a62015-09-21 23:03:16 +00004081 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00004082 return false;
Mehdi Amini44ede332015-07-09 02:09:04 +00004083 }
Chandler Carruthc8925912013-01-05 02:09:22 +00004084 case Instruction::BitCast:
4085 // BitCast is always a noop, and we can handle it as long as it is
4086 // int->int or pointer->pointer (we don't want int<->fp or something).
Vedant Kumarb3091da2018-07-06 20:17:42 +00004087 if (AddrInst->getOperand(0)->getType()->isIntOrPtrTy() &&
Chandler Carruthc8925912013-01-05 02:09:22 +00004088 // Don't touch identity bitcasts. These were probably put here by LSR,
4089 // and we don't want to mess around with them. Assume it knows what it
4090 // is doing.
4091 AddrInst->getOperand(0)->getType() != AddrInst->getType())
Sanjay Patelfc580a62015-09-21 23:03:16 +00004092 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00004093 return false;
Matt Arsenaultf05b0232015-05-26 16:59:43 +00004094 case Instruction::AddrSpaceCast: {
4095 unsigned SrcAS
4096 = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
4097 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
4098 if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
Sanjay Patelfc580a62015-09-21 23:03:16 +00004099 return matchAddr(AddrInst->getOperand(0), Depth);
Matt Arsenaultf05b0232015-05-26 16:59:43 +00004100 return false;
4101 }
Chandler Carruthc8925912013-01-05 02:09:22 +00004102 case Instruction::Add: {
4103 // Check to see if we can merge in the RHS then the LHS. If so, we win.
4104 ExtAddrMode BackupAddrMode = AddrMode;
4105 unsigned OldSize = AddrModeInsts.size();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004106 // Start a transaction at this point.
4107 // The LHS may match but not the RHS.
4108 // Therefore, we need a higher level restoration point to undo partially
4109 // matched operation.
4110 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4111 TPT.getRestorationPoint();
4112
Tim Northover8935aca2019-03-12 15:22:23 +00004113 AddrMode.InBounds = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004114 if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
4115 matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00004116 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004117
Chandler Carruthc8925912013-01-05 02:09:22 +00004118 // Restore the old addr mode info.
4119 AddrMode = BackupAddrMode;
4120 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004121 TPT.rollback(LastKnownGood);
Stephen Lin837bba12013-07-15 17:55:02 +00004122
Chandler Carruthc8925912013-01-05 02:09:22 +00004123 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004124 if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
4125 matchAddr(AddrInst->getOperand(1), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00004126 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004127
Chandler Carruthc8925912013-01-05 02:09:22 +00004128 // Otherwise we definitely can't merge the ADD in.
4129 AddrMode = BackupAddrMode;
4130 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004131 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00004132 break;
4133 }
4134 //case Instruction::Or:
4135 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
4136 //break;
4137 case Instruction::Mul:
4138 case Instruction::Shl: {
4139 // Can only handle X*C and X << C.
Tim Northover8935aca2019-03-12 15:22:23 +00004140 AddrMode.InBounds = false;
Chandler Carruthc8925912013-01-05 02:09:22 +00004141 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
Philip Reames9c3cbee2017-10-30 23:59:51 +00004142 if (!RHS || RHS->getBitWidth() > 64)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00004143 return false;
Chandler Carruthc8925912013-01-05 02:09:22 +00004144 int64_t Scale = RHS->getSExtValue();
4145 if (Opcode == Instruction::Shl)
4146 Scale = 1LL << Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00004147
Sanjay Patelfc580a62015-09-21 23:03:16 +00004148 return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00004149 }
4150 case Instruction::GetElementPtr: {
4151 // Scan the GEP. We check it if it contains constant offsets and at most
4152 // one variable offset.
4153 int VariableOperand = -1;
4154 unsigned VariableScale = 0;
Stephen Lin837bba12013-07-15 17:55:02 +00004155
Chandler Carruthc8925912013-01-05 02:09:22 +00004156 int64_t ConstantOffset = 0;
Chandler Carruthc8925912013-01-05 02:09:22 +00004157 gep_type_iterator GTI = gep_type_begin(AddrInst);
4158 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
Peter Collingbourneab85225b2016-12-02 02:24:42 +00004159 if (StructType *STy = GTI.getStructTypeOrNull()) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00004160 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruthc8925912013-01-05 02:09:22 +00004161 unsigned Idx =
4162 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
4163 ConstantOffset += SL->getElementOffset(Idx);
4164 } else {
Mehdi Amini4fe37982015-07-07 18:45:17 +00004165 uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
Chandler Carruthc8925912013-01-05 02:09:22 +00004166 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
Simon Pilgrimee82a792018-08-13 12:10:09 +00004167 const APInt &CVal = CI->getValue();
4168 if (CVal.getMinSignedBits() <= 64) {
4169 ConstantOffset += CVal.getSExtValue() * TypeSize;
4170 continue;
4171 }
4172 }
4173 if (TypeSize) { // Scales of zero don't do anything.
Chandler Carruthc8925912013-01-05 02:09:22 +00004174 // We only allow one variable index at the moment.
4175 if (VariableOperand != -1)
4176 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00004177
Chandler Carruthc8925912013-01-05 02:09:22 +00004178 // Remember the variable index.
4179 VariableOperand = i;
4180 VariableScale = TypeSize;
4181 }
4182 }
4183 }
Stephen Lin837bba12013-07-15 17:55:02 +00004184
Chandler Carruthc8925912013-01-05 02:09:22 +00004185 // A common case is for the GEP to only do a constant offset. In this case,
4186 // just add it to the disp field and check validity.
4187 if (VariableOperand == -1) {
4188 AddrMode.BaseOffs += ConstantOffset;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004189 if (ConstantOffset == 0 ||
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00004190 TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00004191 // Check to see if we can fold the base pointer in too.
Tim Northover8935aca2019-03-12 15:22:23 +00004192 if (matchAddr(AddrInst->getOperand(0), Depth+1)) {
4193 if (!cast<GEPOperator>(AddrInst)->isInBounds())
4194 AddrMode.InBounds = false;
Chandler Carruthc8925912013-01-05 02:09:22 +00004195 return true;
Tim Northover8935aca2019-03-12 15:22:23 +00004196 }
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00004197 } else if (EnableGEPOffsetSplit && isa<GetElementPtrInst>(AddrInst) &&
4198 TLI.shouldConsiderGEPOffsetSplit() && Depth == 0 &&
4199 ConstantOffset > 0) {
4200 // Record GEPs with non-zero offsets as candidates for splitting in the
4201 // event that the offset cannot fit into the r+i addressing mode.
4202 // Simple and common case that only one GEP is used in calculating the
4203 // address for the memory access.
4204 Value *Base = AddrInst->getOperand(0);
4205 auto *BaseI = dyn_cast<Instruction>(Base);
4206 auto *GEP = cast<GetElementPtrInst>(AddrInst);
4207 if (isa<Argument>(Base) || isa<GlobalValue>(Base) ||
4208 (BaseI && !isa<CastInst>(BaseI) &&
4209 !isa<GetElementPtrInst>(BaseI))) {
4210 // If the base is an instruction, make sure the GEP is not in the same
4211 // basic block as the base. If the base is an argument or global
4212 // value, make sure the GEP is not in the entry block. Otherwise,
4213 // instruction selection can undo the split. Also make sure the
4214 // parent block allows inserting non-PHI instructions before the
4215 // terminator.
4216 BasicBlock *Parent =
4217 BaseI ? BaseI->getParent() : &GEP->getFunction()->getEntryBlock();
4218 if (GEP->getParent() != Parent && !Parent->getTerminator()->isEHPad())
4219 LargeOffsetGEP = std::make_pair(GEP, ConstantOffset);
4220 }
Chandler Carruthc8925912013-01-05 02:09:22 +00004221 }
4222 AddrMode.BaseOffs -= ConstantOffset;
4223 return false;
4224 }
4225
4226 // Save the valid addressing mode in case we can't match.
4227 ExtAddrMode BackupAddrMode = AddrMode;
4228 unsigned OldSize = AddrModeInsts.size();
4229
4230 // See if the scale and offset amount is valid for this target.
4231 AddrMode.BaseOffs += ConstantOffset;
Tim Northover8935aca2019-03-12 15:22:23 +00004232 if (!cast<GEPOperator>(AddrInst)->isInBounds())
4233 AddrMode.InBounds = false;
Chandler Carruthc8925912013-01-05 02:09:22 +00004234
4235 // Match the base operand of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004236 if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00004237 // If it couldn't be matched, just stuff the value in a register.
4238 if (AddrMode.HasBaseReg) {
4239 AddrMode = BackupAddrMode;
4240 AddrModeInsts.resize(OldSize);
4241 return false;
4242 }
4243 AddrMode.HasBaseReg = true;
4244 AddrMode.BaseReg = AddrInst->getOperand(0);
4245 }
4246
4247 // Match the remaining variable portion of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004248 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
Chandler Carruthc8925912013-01-05 02:09:22 +00004249 Depth)) {
4250 // If it couldn't be matched, try stuffing the base into a register
4251 // instead of matching it, and retrying the match of the scale.
4252 AddrMode = BackupAddrMode;
4253 AddrModeInsts.resize(OldSize);
4254 if (AddrMode.HasBaseReg)
4255 return false;
4256 AddrMode.HasBaseReg = true;
4257 AddrMode.BaseReg = AddrInst->getOperand(0);
4258 AddrMode.BaseOffs += ConstantOffset;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004259 if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
Chandler Carruthc8925912013-01-05 02:09:22 +00004260 VariableScale, Depth)) {
4261 // If even that didn't work, bail.
4262 AddrMode = BackupAddrMode;
4263 AddrModeInsts.resize(OldSize);
4264 return false;
4265 }
4266 }
4267
4268 return true;
4269 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00004270 case Instruction::SExt:
4271 case Instruction::ZExt: {
4272 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
4273 if (!Ext)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00004274 return false;
Sanjay Patelab60d042014-07-16 21:08:10 +00004275
Quentin Colombetf5485bb2014-11-13 01:44:51 +00004276 // Try to move this ext out of the way of the addressing mode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004277 // Ask for a method for doing so.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00004278 TypePromotionHelper::Action TPH =
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004279 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004280 if (!TPH)
4281 return false;
4282
4283 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4284 TPT.getRestorationPoint();
Quentin Colombet1b274f92015-03-10 21:48:15 +00004285 unsigned CreatedInstsCost = 0;
4286 unsigned ExtCost = !TLI.isExtFree(Ext);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004287 Value *PromotedOperand =
Quentin Colombet1b274f92015-03-10 21:48:15 +00004288 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004289 // SExt has been moved away.
4290 // Thus either it will be rematched later in the recursive calls or it is
4291 // gone. Anyway, we must not fold it into the addressing mode at this point.
4292 // E.g.,
4293 // op = add opnd, 1
Quentin Colombetf5485bb2014-11-13 01:44:51 +00004294 // idx = ext op
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004295 // addr = gep base, idx
4296 // is now:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00004297 // promotedOpnd = ext opnd <- no match here
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004298 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
4299 // addr = gep base, op <- match
4300 if (MovedAway)
4301 *MovedAway = true;
4302
4303 assert(PromotedOperand &&
4304 "TypePromotionHelper should have filtered out those cases");
4305
4306 ExtAddrMode BackupAddrMode = AddrMode;
4307 unsigned OldSize = AddrModeInsts.size();
4308
Sanjay Patelfc580a62015-09-21 23:03:16 +00004309 if (!matchAddr(PromotedOperand, Depth) ||
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00004310 // The total of the new cost is equal to the cost of the created
Quentin Colombet1b274f92015-03-10 21:48:15 +00004311 // instructions.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00004312 // The total of the old cost is equal to the cost of the extension plus
Quentin Colombet1b274f92015-03-10 21:48:15 +00004313 // what we have saved in the addressing mode.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004314 !isPromotionProfitable(CreatedInstsCost,
Quentin Colombet1b274f92015-03-10 21:48:15 +00004315 ExtCost + (AddrModeInsts.size() - OldSize),
Quentin Colombet867c5502014-02-14 22:23:22 +00004316 PromotedOperand)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004317 AddrMode = BackupAddrMode;
4318 AddrModeInsts.resize(OldSize);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004319 LLVM_DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004320 TPT.rollback(LastKnownGood);
4321 return false;
4322 }
4323 return true;
4324 }
Chandler Carruthc8925912013-01-05 02:09:22 +00004325 }
4326 return false;
4327}
4328
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004329/// If we can, try to add the value of 'Addr' into the current addressing mode.
4330/// If Addr can't be added to AddrMode this returns false and leaves AddrMode
4331/// unmodified. This assumes that Addr is either a pointer type or intptr_t
4332/// for the target.
Chandler Carruthc8925912013-01-05 02:09:22 +00004333///
Sanjay Patelfc580a62015-09-21 23:03:16 +00004334bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004335 // Start a transaction at this point that we will rollback if the matching
4336 // fails.
4337 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4338 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00004339 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
4340 // Fold in immediates if legal for the target.
4341 AddrMode.BaseOffs += CI->getSExtValue();
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00004342 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00004343 return true;
4344 AddrMode.BaseOffs -= CI->getSExtValue();
4345 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
4346 // If this is a global variable, try to fold it into the addressing mode.
Craig Topperc0196b12014-04-14 00:51:57 +00004347 if (!AddrMode.BaseGV) {
Chandler Carruthc8925912013-01-05 02:09:22 +00004348 AddrMode.BaseGV = GV;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00004349 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00004350 return true;
Craig Topperc0196b12014-04-14 00:51:57 +00004351 AddrMode.BaseGV = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00004352 }
4353 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
4354 ExtAddrMode BackupAddrMode = AddrMode;
4355 unsigned OldSize = AddrModeInsts.size();
4356
4357 // Check to see if it is possible to fold this operation.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004358 bool MovedAway = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004359 if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00004360 // This instruction may have been moved away. If so, there is nothing
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004361 // to check here.
4362 if (MovedAway)
4363 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00004364 // Okay, it's possible to fold this. Check to see if it is actually
4365 // *profitable* to do so. We use a simple cost model to avoid increasing
4366 // register pressure too much.
4367 if (I->hasOneUse() ||
Sanjay Patelfc580a62015-09-21 23:03:16 +00004368 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00004369 AddrModeInsts.push_back(I);
4370 return true;
4371 }
Stephen Lin837bba12013-07-15 17:55:02 +00004372
Chandler Carruthc8925912013-01-05 02:09:22 +00004373 // It isn't profitable to do this, roll back.
4374 //cerr << "NOT FOLDING: " << *I;
4375 AddrMode = BackupAddrMode;
4376 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004377 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00004378 }
4379 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
Sanjay Patelfc580a62015-09-21 23:03:16 +00004380 if (matchOperationAddr(CE, CE->getOpcode(), Depth))
Chandler Carruthc8925912013-01-05 02:09:22 +00004381 return true;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004382 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00004383 } else if (isa<ConstantPointerNull>(Addr)) {
4384 // Null pointer gets folded without affecting the addressing mode.
4385 return true;
4386 }
4387
4388 // Worse case, the target should support [reg] addressing modes. :)
4389 if (!AddrMode.HasBaseReg) {
4390 AddrMode.HasBaseReg = true;
4391 AddrMode.BaseReg = Addr;
4392 // Still check for legality in case the target supports [imm] but not [i+r].
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00004393 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00004394 return true;
4395 AddrMode.HasBaseReg = false;
Craig Topperc0196b12014-04-14 00:51:57 +00004396 AddrMode.BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00004397 }
4398
4399 // If the base register is already taken, see if we can do [r+r].
4400 if (AddrMode.Scale == 0) {
4401 AddrMode.Scale = 1;
4402 AddrMode.ScaledReg = Addr;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00004403 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00004404 return true;
4405 AddrMode.Scale = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00004406 AddrMode.ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00004407 }
4408 // Couldn't match.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004409 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00004410 return false;
4411}
4412
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004413/// Check to see if all uses of OpVal by the specified inline asm call are due
4414/// to memory operands. If so, return true, otherwise return false.
Chandler Carruthc8925912013-01-05 02:09:22 +00004415static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004416 const TargetLowering &TLI,
4417 const TargetRegisterInfo &TRI) {
Sanjay Patel4137d512017-06-07 14:29:52 +00004418 const Function *F = CI->getFunction();
Eric Christopherd75c00c2015-02-26 22:38:34 +00004419 TargetLowering::AsmOperandInfoVector TargetConstraints =
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004420 TLI.ParseConstraints(F->getParent()->getDataLayout(), &TRI,
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00004421 ImmutableCallSite(CI));
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004422
Chandler Carruthc8925912013-01-05 02:09:22 +00004423 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
4424 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Stephen Lin837bba12013-07-15 17:55:02 +00004425
Chandler Carruthc8925912013-01-05 02:09:22 +00004426 // Compute the constraint code and ConstraintType to use.
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004427 TLI.ComputeConstraintToUse(OpInfo, SDValue());
Chandler Carruthc8925912013-01-05 02:09:22 +00004428
4429 // If this asm operand is our Value*, and if it isn't an indirect memory
4430 // operand, we can't fold it!
4431 if (OpInfo.CallOperandVal == OpVal &&
4432 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
4433 !OpInfo.isIndirect))
4434 return false;
4435 }
4436
4437 return true;
4438}
4439
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004440// Max number of memory uses to look at before aborting the search to conserve
4441// compile time.
4442static constexpr int MaxMemoryUsesToScan = 20;
4443
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004444/// Recursively walk all the uses of I until we find a memory use.
4445/// If we find an obviously non-foldable instruction, return true.
Chandler Carruthc8925912013-01-05 02:09:22 +00004446/// Add the ultimately found memory instructions to MemoryUses.
Eric Christopher11e4df72015-02-26 22:38:43 +00004447static bool FindAllMemoryUses(
4448 Instruction *I,
4449 SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004450 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetLowering &TLI,
4451 const TargetRegisterInfo &TRI, int SeenInsts = 0) {
Chandler Carruthc8925912013-01-05 02:09:22 +00004452 // If we already considered this instruction, we're done.
David Blaikie70573dc2014-11-19 07:49:26 +00004453 if (!ConsideredInsts.insert(I).second)
Chandler Carruthc8925912013-01-05 02:09:22 +00004454 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00004455
Chandler Carruthc8925912013-01-05 02:09:22 +00004456 // If this is an obviously unfoldable instruction, bail out.
4457 if (!MightBeFoldableInst(I))
4458 return true;
4459
Evandro Menezes85bd3972019-04-04 22:40:06 +00004460 const bool OptSize = I->getFunction()->hasOptSize();
Philip Reamesac115ed2016-03-09 23:13:12 +00004461
Chandler Carruthc8925912013-01-05 02:09:22 +00004462 // Loop over all the uses, recursively processing them.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004463 for (Use &U : I->uses()) {
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004464 // Conservatively return true if we're seeing a large number or a deep chain
4465 // of users. This avoids excessive compilation times in pathological cases.
4466 if (SeenInsts++ >= MaxMemoryUsesToScan)
4467 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00004468
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004469 Instruction *UserI = cast<Instruction>(U.getUser());
Chandler Carruthcdf47882014-03-09 03:16:01 +00004470 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
4471 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
Chandler Carruthc8925912013-01-05 02:09:22 +00004472 continue;
4473 }
Stephen Lin837bba12013-07-15 17:55:02 +00004474
Chandler Carruthcdf47882014-03-09 03:16:01 +00004475 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
4476 unsigned opNo = U.getOperandNo();
Matt Arsenault02d915b2017-03-15 22:35:20 +00004477 if (opNo != StoreInst::getPointerOperandIndex())
4478 return true; // Storing addr, not into addr.
Chandler Carruthc8925912013-01-05 02:09:22 +00004479 MemoryUses.push_back(std::make_pair(SI, opNo));
4480 continue;
4481 }
Stephen Lin837bba12013-07-15 17:55:02 +00004482
Matt Arsenault02d915b2017-03-15 22:35:20 +00004483 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UserI)) {
4484 unsigned opNo = U.getOperandNo();
4485 if (opNo != AtomicRMWInst::getPointerOperandIndex())
4486 return true; // Storing addr, not into addr.
4487 MemoryUses.push_back(std::make_pair(RMW, opNo));
4488 continue;
4489 }
4490
4491 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(UserI)) {
4492 unsigned opNo = U.getOperandNo();
4493 if (opNo != AtomicCmpXchgInst::getPointerOperandIndex())
4494 return true; // Storing addr, not into addr.
4495 MemoryUses.push_back(std::make_pair(CmpX, opNo));
4496 continue;
4497 }
4498
Chandler Carruthcdf47882014-03-09 03:16:01 +00004499 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
Philip Reamesac115ed2016-03-09 23:13:12 +00004500 // If this is a cold call, we can sink the addressing calculation into
4501 // the cold path. See optimizeCallInst
4502 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
4503 continue;
Junmo Park6098cbb2016-03-11 07:05:32 +00004504
Chandler Carruthc8925912013-01-05 02:09:22 +00004505 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
4506 if (!IA) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004507
Chandler Carruthc8925912013-01-05 02:09:22 +00004508 // If this is a memory operand, we're cool, otherwise bail out.
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004509 if (!IsOperandAMemoryOperand(CI, IA, I, TLI, TRI))
Chandler Carruthc8925912013-01-05 02:09:22 +00004510 return true;
4511 continue;
4512 }
Stephen Lin837bba12013-07-15 17:55:02 +00004513
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004514 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI, TRI,
4515 SeenInsts))
Chandler Carruthc8925912013-01-05 02:09:22 +00004516 return true;
4517 }
4518
4519 return false;
4520}
4521
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00004522/// Return true if Val is already known to be live at the use site that we're
4523/// folding it into. If so, there is no cost to include it in the addressing
4524/// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
4525/// instruction already.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004526bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
Chandler Carruthc8925912013-01-05 02:09:22 +00004527 Value *KnownLive2) {
4528 // If Val is either of the known-live values, we know it is live!
Craig Topperc0196b12014-04-14 00:51:57 +00004529 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
Chandler Carruthc8925912013-01-05 02:09:22 +00004530 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004531
Chandler Carruthc8925912013-01-05 02:09:22 +00004532 // All values other than instructions and arguments (e.g. constants) are live.
4533 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004534
Chandler Carruthc8925912013-01-05 02:09:22 +00004535 // If Val is a constant sized alloca in the entry block, it is live, this is
4536 // true because it is just a reference to the stack/frame pointer, which is
4537 // live for the whole function.
4538 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
4539 if (AI->isStaticAlloca())
4540 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004541
Chandler Carruthc8925912013-01-05 02:09:22 +00004542 // Check to see if this value is already used in the memory instruction's
4543 // block. If so, it's already live into the block at the very least, so we
4544 // can reasonably fold it.
4545 return Val->isUsedInBasicBlock(MemoryInst->getParent());
4546}
4547
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004548/// It is possible for the addressing mode of the machine to fold the specified
4549/// instruction into a load or store that ultimately uses it.
4550/// However, the specified instruction has multiple uses.
4551/// Given this, it may actually increase register pressure to fold it
4552/// into the load. For example, consider this code:
Chandler Carruthc8925912013-01-05 02:09:22 +00004553///
4554/// X = ...
4555/// Y = X+1
4556/// use(Y) -> nonload/store
4557/// Z = Y+1
4558/// load Z
4559///
4560/// In this case, Y has multiple uses, and can be folded into the load of Z
4561/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
4562/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
4563/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
4564/// number of computations either.
4565///
4566/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
4567/// X was live across 'load Z' for other reasons, we actually *would* want to
4568/// fold the addressing mode in the Z case. This would make Y die earlier.
4569bool AddressingModeMatcher::
Sanjay Patelfc580a62015-09-21 23:03:16 +00004570isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
Chandler Carruthc8925912013-01-05 02:09:22 +00004571 ExtAddrMode &AMAfter) {
4572 if (IgnoreProfitability) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004573
Chandler Carruthc8925912013-01-05 02:09:22 +00004574 // AMBefore is the addressing mode before this instruction was folded into it,
4575 // and AMAfter is the addressing mode after the instruction was folded. Get
4576 // the set of registers referenced by AMAfter and subtract out those
4577 // referenced by AMBefore: this is the set of values which folding in this
4578 // address extends the lifetime of.
4579 //
4580 // Note that there are only two potential values being referenced here,
4581 // BaseReg and ScaleReg (global addresses are always available, as are any
4582 // folded immediates).
4583 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
Stephen Lin837bba12013-07-15 17:55:02 +00004584
Chandler Carruthc8925912013-01-05 02:09:22 +00004585 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
4586 // lifetime wasn't extended by adding this instruction.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004587 if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00004588 BaseReg = nullptr;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004589 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00004590 ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00004591
4592 // If folding this instruction (and it's subexprs) didn't extend any live
4593 // ranges, we're ok with it.
Craig Topperc0196b12014-04-14 00:51:57 +00004594 if (!BaseReg && !ScaledReg)
Chandler Carruthc8925912013-01-05 02:09:22 +00004595 return true;
4596
Philip Reamesac115ed2016-03-09 23:13:12 +00004597 // If all uses of this instruction can have the address mode sunk into them,
4598 // we can remove the addressing mode and effectively trade one live register
4599 // for another (at worst.) In this context, folding an addressing mode into
Junmo Park6098cbb2016-03-11 07:05:32 +00004600 // the use is just a particularly nice way of sinking it.
Chandler Carruthc8925912013-01-05 02:09:22 +00004601 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
4602 SmallPtrSet<Instruction*, 16> ConsideredInsts;
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004603 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI, TRI))
Chandler Carruthc8925912013-01-05 02:09:22 +00004604 return false; // Has a non-memory, non-foldable use!
Stephen Lin837bba12013-07-15 17:55:02 +00004605
Chandler Carruthc8925912013-01-05 02:09:22 +00004606 // Now that we know that all uses of this instruction are part of a chain of
4607 // computation involving only operations that could theoretically be folded
Philip Reamesac115ed2016-03-09 23:13:12 +00004608 // into a memory use, loop over each of these memory operation uses and see
4609 // if they could *actually* fold the instruction. The assumption is that
4610 // addressing modes are cheap and that duplicating the computation involved
4611 // many times is worthwhile, even on a fastpath. For sinking candidates
4612 // (i.e. cold call sites), this serves as a way to prevent excessive code
4613 // growth since most architectures have some reasonable small and fast way to
4614 // compute an effective address. (i.e LEA on x86)
Chandler Carruthc8925912013-01-05 02:09:22 +00004615 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
4616 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
4617 Instruction *User = MemoryUses[i].first;
4618 unsigned OpNo = MemoryUses[i].second;
Stephen Lin837bba12013-07-15 17:55:02 +00004619
Chandler Carruthc8925912013-01-05 02:09:22 +00004620 // Get the access type of this use. If the use isn't a pointer, we don't
4621 // know what it accesses.
4622 Value *Address = User->getOperand(OpNo);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004623 PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
4624 if (!AddrTy)
Chandler Carruthc8925912013-01-05 02:09:22 +00004625 return false;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004626 Type *AddressAccessTy = AddrTy->getElementType();
4627 unsigned AS = AddrTy->getAddressSpace();
Stephen Lin837bba12013-07-15 17:55:02 +00004628
Chandler Carruthc8925912013-01-05 02:09:22 +00004629 // Do a match against the root of this address, ignoring profitability. This
4630 // will tell us if the addressing mode for the memory operation will
4631 // *actually* cover the shared instruction.
4632 ExtAddrMode Result;
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00004633 std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr,
4634 0);
Quentin Colombet5a69dda2014-02-11 01:59:02 +00004635 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4636 TPT.getRestorationPoint();
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00004637 AddressingModeMatcher Matcher(
4638 MatchedAddrModeInsts, TLI, TRI, AddressAccessTy, AS, MemoryInst, Result,
4639 InsertedInsts, PromotedInsts, TPT, LargeOffsetGEP);
Chandler Carruthc8925912013-01-05 02:09:22 +00004640 Matcher.IgnoreProfitability = true;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004641 bool Success = Matcher.matchAddr(Address, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00004642 (void)Success; assert(Success && "Couldn't select *anything*?");
4643
Quentin Colombet5a69dda2014-02-11 01:59:02 +00004644 // The match was to check the profitability, the changes made are not
4645 // part of the original matcher. Therefore, they should be dropped
4646 // otherwise the original matcher will not present the right state.
4647 TPT.rollback(LastKnownGood);
4648
Chandler Carruthc8925912013-01-05 02:09:22 +00004649 // If the match didn't cover I, then it won't be shared by it.
David Majnemer0d955d02016-08-11 22:21:41 +00004650 if (!is_contained(MatchedAddrModeInsts, I))
Chandler Carruthc8925912013-01-05 02:09:22 +00004651 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00004652
Chandler Carruthc8925912013-01-05 02:09:22 +00004653 MatchedAddrModeInsts.clear();
4654 }
Stephen Lin837bba12013-07-15 17:55:02 +00004655
Chandler Carruthc8925912013-01-05 02:09:22 +00004656 return true;
4657}
4658
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004659/// Return true if the specified values are defined in a
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004660/// different basic block than BB.
4661static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
4662 if (Instruction *I = dyn_cast<Instruction>(V))
4663 return I->getParent() != BB;
4664 return false;
4665}
4666
Philip Reamesac115ed2016-03-09 23:13:12 +00004667/// Sink addressing mode computation immediate before MemoryInst if doing so
4668/// can be done without increasing register pressure. The need for the
4669/// register pressure constraint means this can end up being an all or nothing
4670/// decision for all uses of the same addressing computation.
4671///
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004672/// Load and Store Instructions often have addressing modes that can do
4673/// significant amounts of computation. As such, instruction selection will try
4674/// to get the load or store to do as much computation as possible for the
4675/// program. The problem is that isel can only see within a single block. As
4676/// such, we sink as much legal addressing mode work into the block as possible.
Chris Lattner728f9022008-11-25 07:09:13 +00004677///
4678/// This method is used to optimize both load/store and inline asms with memory
Philip Reamesac115ed2016-03-09 23:13:12 +00004679/// operands. It's also used to sink addressing computations feeding into cold
4680/// call sites into their (cold) basic block.
4681///
4682/// The motivation for handling sinking into cold blocks is that doing so can
4683/// both enable other address mode sinking (by satisfying the register pressure
4684/// constraint above), and reduce register pressure globally (by removing the
4685/// addressing mode computation from the fast path entirely.).
Sanjay Patelfc580a62015-09-21 23:03:16 +00004686bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004687 Type *AccessTy, unsigned AddrSpace) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00004688 Value *Repl = Addr;
Nadav Rotem465834c2012-07-24 10:51:42 +00004689
4690 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004691 // unprofitable PRE transformations.
Cameron Zwarich43cecb12011-01-03 06:33:01 +00004692 SmallVector<Value*, 8> worklist;
4693 SmallPtrSet<Value*, 16> Visited;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004694 worklist.push_back(Addr);
Nadav Rotem465834c2012-07-24 10:51:42 +00004695
John Brawneb83c752017-10-03 13:04:15 +00004696 // Use a worklist to iteratively look through PHI and select nodes, and
4697 // ensure that the addressing mode obtained from the non-PHI/select roots of
John Brawn736bf002017-10-03 13:08:22 +00004698 // the graph are compatible.
John Brawneb83c752017-10-03 13:04:15 +00004699 bool PhiOrSelectSeen = false;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004700 SmallVector<Instruction*, 16> AddrModeInsts;
Serguei Katkovaee63752017-11-05 07:59:02 +00004701 const SimplifyQuery SQ(*DL, TLInfo);
Serguei Katkov2673f172018-11-29 06:45:18 +00004702 AddressingModeCombiner AddrModes(SQ, Addr);
Jun Bum Limdee55652017-04-03 19:20:07 +00004703 TypePromotionTransaction TPT(RemovedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004704 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4705 TPT.getRestorationPoint();
Owen Anderson8ba5f392010-11-27 08:15:55 +00004706 while (!worklist.empty()) {
4707 Value *V = worklist.back();
4708 worklist.pop_back();
Nadav Rotem465834c2012-07-24 10:51:42 +00004709
Serguei Katkov4ea855e2017-07-19 04:49:17 +00004710 // We allow traversing cyclic Phi nodes.
4711 // In case of success after this loop we ensure that traversing through
4712 // Phi nodes ends up with all cases to compute address of the form
4713 // BaseGV + Base + Scale * Index + Offset
4714 // where Scale and Offset are constans and BaseGV, Base and Index
4715 // are exactly the same Values in all cases.
4716 // It means that BaseGV, Scale and Offset dominate our memory instruction
4717 // and have the same value as they had in address computation represented
4718 // as Phi. So we can safely sink address computation to memory instruction.
4719 if (!Visited.insert(V).second)
4720 continue;
Nadav Rotem465834c2012-07-24 10:51:42 +00004721
Owen Anderson8ba5f392010-11-27 08:15:55 +00004722 // For a PHI node, push all of its incoming values.
4723 if (PHINode *P = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00004724 for (Value *IncValue : P->incoming_values())
4725 worklist.push_back(IncValue);
John Brawneb83c752017-10-03 13:04:15 +00004726 PhiOrSelectSeen = true;
4727 continue;
4728 }
4729 // Similar for select.
4730 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
4731 worklist.push_back(SI->getFalseValue());
4732 worklist.push_back(SI->getTrueValue());
4733 PhiOrSelectSeen = true;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004734 continue;
4735 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004736
Philip Reamesac115ed2016-03-09 23:13:12 +00004737 // For non-PHIs, determine the addressing mode being computed. Note that
4738 // the result may differ depending on what other uses our candidate
4739 // addressing instructions might have.
Serguei Katkova6fba3d2017-07-18 05:16:38 +00004740 AddrModeInsts.clear();
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00004741 std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr,
4742 0);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004743 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
Serguei Katkova6fba3d2017-07-18 05:16:38 +00004744 V, AccessTy, AddrSpace, MemoryInst, AddrModeInsts, *TLI, *TRI,
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00004745 InsertedInsts, PromotedInsts, TPT, LargeOffsetGEP);
Cameron Zwarich13c885d2011-03-05 08:12:26 +00004746
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00004747 GetElementPtrInst *GEP = LargeOffsetGEP.first;
4748 if (GEP && GEP->getParent() != MemoryInst->getParent() &&
4749 !NewGEPBases.count(GEP)) {
4750 // If splitting the underlying data structure can reduce the offset of a
4751 // GEP, collect the GEP. Skip the GEPs that are the new bases of
4752 // previously split data structures.
4753 LargeOffsetGEPMap[GEP->getPointerOperand()].push_back(LargeOffsetGEP);
4754 if (LargeOffsetGEPID.find(GEP) == LargeOffsetGEPID.end())
4755 LargeOffsetGEPID[GEP] = LargeOffsetGEPID.size();
4756 }
4757
4758 NewAddrMode.OriginalValue = V;
John Brawn736bf002017-10-03 13:08:22 +00004759 if (!AddrModes.addNewAddrMode(NewAddrMode))
4760 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004761 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004762
John Brawn736bf002017-10-03 13:08:22 +00004763 // Try to combine the AddrModes we've collected. If we couldn't collect any,
4764 // or we have multiple but either couldn't combine them or combining them
4765 // wouldn't do anything useful, bail out now.
4766 if (!AddrModes.combineAddrModes()) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004767 TPT.rollback(LastKnownGood);
4768 return false;
4769 }
4770 TPT.commit();
Nadav Rotem465834c2012-07-24 10:51:42 +00004771
John Brawn736bf002017-10-03 13:08:22 +00004772 // Get the combined AddrMode (or the only AddrMode, if we only had one).
4773 ExtAddrMode AddrMode = AddrModes.getAddrMode();
4774
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004775 // If all the instructions matched are already in this BB, don't do anything.
John Brawneb83c752017-10-03 13:04:15 +00004776 // If we saw a Phi node then it is not local definitely, and if we saw a select
4777 // then we want to push the address calculation past it even if it's already
4778 // in this BB.
4779 if (!PhiOrSelectSeen && none_of(AddrModeInsts, [&](Value *V) {
Justin Lebar838c7f52016-11-21 22:49:11 +00004780 return IsNonLocalValue(V, MemoryInst->getParent());
Serguei Katkov0b7b59a2017-07-11 06:24:44 +00004781 })) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004782 LLVM_DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode
4783 << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004784 return false;
4785 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004786
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004787 // Insert this computation right after this user. Since our caller is
4788 // scanning from the top of the BB to the bottom, reuse of the expr are
4789 // guaranteed to happen later.
Devang Patelc10e52a2011-09-06 18:49:53 +00004790 IRBuilder<> Builder(MemoryInst);
Eric Christopherc1ea1492008-09-24 05:32:41 +00004791
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004792 // Now that we determined the addressing expression we want to use and know
4793 // that we have to sink it into this block. Check to see if we have already
Simon Dardis230f4532017-11-24 16:45:28 +00004794 // done this for some other load/store instr in this block. If so, reuse
4795 // the computation. Before attempting reuse, check if the address is valid
4796 // as it may have been erased.
4797
4798 WeakTrackingVH SunkAddrVH = SunkAddrs[Addr];
4799
4800 Value * SunkAddr = SunkAddrVH.pointsToAliveValue() ? SunkAddrVH : nullptr;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004801 if (SunkAddr) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004802 LLVM_DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode
4803 << " for " << *MemoryInst << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004804 if (SunkAddr->getType() != Addr->getType())
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004805 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
Eric Christopherfccff372015-01-27 01:01:38 +00004806 } else if (AddrSinkUsingGEPs ||
David Blaikie8ad9a972018-03-28 22:28:50 +00004807 (!AddrSinkUsingGEPs.getNumOccurrences() && TM && TTI->useAA())) {
Hal Finkelc3998302014-04-12 00:59:48 +00004808 // By default, we use the GEP-based method when AA is used later. This
4809 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004810 LLVM_DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode
4811 << " for " << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00004812 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00004813 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00004814
4815 // First, find the pointer.
4816 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
4817 ResultPtr = AddrMode.BaseReg;
Craig Topperc0196b12014-04-14 00:51:57 +00004818 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00004819 }
4820
4821 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
4822 // We can't add more than one pointer together, nor can we scale a
4823 // pointer (both of which seem meaningless).
4824 if (ResultPtr || AddrMode.Scale != 1)
4825 return false;
4826
4827 ResultPtr = AddrMode.ScaledReg;
4828 AddrMode.Scale = 0;
4829 }
4830
Eli Friedman6f7c9ad2017-07-12 23:30:02 +00004831 // It is only safe to sign extend the BaseReg if we know that the math
4832 // required to create it did not overflow before we extend it. Since
4833 // the original IR value was tossed in favor of a constant back when
4834 // the AddrMode was created we need to bail out gracefully if widths
4835 // do not match instead of extending it.
4836 //
4837 // (See below for code to add the scale.)
4838 if (AddrMode.Scale) {
4839 Type *ScaledRegTy = AddrMode.ScaledReg->getType();
4840 if (cast<IntegerType>(IntPtrTy)->getBitWidth() >
4841 cast<IntegerType>(ScaledRegTy)->getBitWidth())
4842 return false;
4843 }
4844
Hal Finkelc3998302014-04-12 00:59:48 +00004845 if (AddrMode.BaseGV) {
4846 if (ResultPtr)
4847 return false;
4848
4849 ResultPtr = AddrMode.BaseGV;
4850 }
4851
4852 // If the real base value actually came from an inttoptr, then the matcher
4853 // will look through it and provide only the integer value. In that case,
4854 // use it here.
Keno Fischer05e4ac22017-06-29 20:28:59 +00004855 if (!DL->isNonIntegralPointerType(Addr->getType())) {
4856 if (!ResultPtr && AddrMode.BaseReg) {
David L. Jonesd81f2302019-01-31 03:28:46 +00004857 ResultPtr = Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(),
4858 "sunkaddr");
Keno Fischer05e4ac22017-06-29 20:28:59 +00004859 AddrMode.BaseReg = nullptr;
4860 } else if (!ResultPtr && AddrMode.Scale == 1) {
David L. Jonesd81f2302019-01-31 03:28:46 +00004861 ResultPtr = Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(),
4862 "sunkaddr");
Keno Fischer05e4ac22017-06-29 20:28:59 +00004863 AddrMode.Scale = 0;
4864 }
Hal Finkelc3998302014-04-12 00:59:48 +00004865 }
4866
4867 if (!ResultPtr &&
4868 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
4869 SunkAddr = Constant::getNullValue(Addr->getType());
4870 } else if (!ResultPtr) {
4871 return false;
4872 } else {
4873 Type *I8PtrTy =
David Blaikie3909da72015-03-30 20:42:56 +00004874 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
4875 Type *I8Ty = Builder.getInt8Ty();
Hal Finkelc3998302014-04-12 00:59:48 +00004876
4877 // Start with the base register. Do this first so that subsequent address
4878 // matching finds it last, which will prevent it from trying to match it
4879 // as the scaled value in case it happens to be a mul. That would be
4880 // problematic if we've sunk a different mul for the scale, because then
4881 // we'd end up sinking both muls.
4882 if (AddrMode.BaseReg) {
4883 Value *V = AddrMode.BaseReg;
4884 if (V->getType() != IntPtrTy)
4885 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
4886
4887 ResultIndex = V;
4888 }
4889
4890 // Add the scale value.
4891 if (AddrMode.Scale) {
4892 Value *V = AddrMode.ScaledReg;
4893 if (V->getType() == IntPtrTy) {
4894 // done.
Hal Finkelc3998302014-04-12 00:59:48 +00004895 } else {
Eli Friedman6f7c9ad2017-07-12 23:30:02 +00004896 assert(cast<IntegerType>(IntPtrTy)->getBitWidth() <
4897 cast<IntegerType>(V->getType())->getBitWidth() &&
4898 "We can't transform if ScaledReg is too narrow");
4899 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004900 }
4901
4902 if (AddrMode.Scale != 1)
4903 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4904 "sunkaddr");
4905 if (ResultIndex)
4906 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
4907 else
4908 ResultIndex = V;
4909 }
4910
4911 // Add in the Base Offset if present.
4912 if (AddrMode.BaseOffs) {
4913 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
4914 if (ResultIndex) {
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00004915 // We need to add this separately from the scale above to help with
4916 // SDAG consecutive load/store merging.
Hal Finkelc3998302014-04-12 00:59:48 +00004917 if (ResultPtr->getType() != I8PtrTy)
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004918 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
Tim Northover8935aca2019-03-12 15:22:23 +00004919 ResultPtr =
4920 AddrMode.InBounds
4921 ? Builder.CreateInBoundsGEP(I8Ty, ResultPtr, ResultIndex,
4922 "sunkaddr")
4923 : Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004924 }
4925
4926 ResultIndex = V;
4927 }
4928
4929 if (!ResultIndex) {
4930 SunkAddr = ResultPtr;
4931 } else {
4932 if (ResultPtr->getType() != I8PtrTy)
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004933 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
Tim Northover8935aca2019-03-12 15:22:23 +00004934 SunkAddr =
4935 AddrMode.InBounds
4936 ? Builder.CreateInBoundsGEP(I8Ty, ResultPtr, ResultIndex,
4937 "sunkaddr")
4938 : Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004939 }
4940
4941 if (SunkAddr->getType() != Addr->getType())
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004942 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
Hal Finkelc3998302014-04-12 00:59:48 +00004943 }
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004944 } else {
Keno Fischer05e4ac22017-06-29 20:28:59 +00004945 // We'd require a ptrtoint/inttoptr down the line, which we can't do for
4946 // non-integral pointers, so in that case bail out now.
4947 Type *BaseTy = AddrMode.BaseReg ? AddrMode.BaseReg->getType() : nullptr;
4948 Type *ScaleTy = AddrMode.Scale ? AddrMode.ScaledReg->getType() : nullptr;
4949 PointerType *BasePtrTy = dyn_cast_or_null<PointerType>(BaseTy);
4950 PointerType *ScalePtrTy = dyn_cast_or_null<PointerType>(ScaleTy);
4951 if (DL->isNonIntegralPointerType(Addr->getType()) ||
4952 (BasePtrTy && DL->isNonIntegralPointerType(BasePtrTy)) ||
4953 (ScalePtrTy && DL->isNonIntegralPointerType(ScalePtrTy)) ||
4954 (AddrMode.BaseGV &&
4955 DL->isNonIntegralPointerType(AddrMode.BaseGV->getType())))
4956 return false;
4957
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004958 LLVM_DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode
4959 << " for " << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00004960 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00004961 Value *Result = nullptr;
Dan Gohmanca194452010-01-19 22:45:06 +00004962
4963 // Start with the base register. Do this first so that subsequent address
4964 // matching finds it last, which will prevent it from trying to match it
4965 // as the scaled value in case it happens to be a mul. That would be
4966 // problematic if we've sunk a different mul for the scale, because then
4967 // we'd end up sinking both muls.
4968 if (AddrMode.BaseReg) {
4969 Value *V = AddrMode.BaseReg;
Duncan Sands19d0b472010-02-16 11:11:14 +00004970 if (V->getType()->isPointerTy())
Devang Patelc10e52a2011-09-06 18:49:53 +00004971 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00004972 if (V->getType() != IntPtrTy)
Devang Patelc10e52a2011-09-06 18:49:53 +00004973 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00004974 Result = V;
4975 }
4976
4977 // Add the scale value.
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004978 if (AddrMode.Scale) {
4979 Value *V = AddrMode.ScaledReg;
4980 if (V->getType() == IntPtrTy) {
4981 // done.
Duncan Sands19d0b472010-02-16 11:11:14 +00004982 } else if (V->getType()->isPointerTy()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004983 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004984 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
4985 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004986 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004987 } else {
Jim Grosbached2cd392014-03-26 17:27:01 +00004988 // It is only safe to sign extend the BaseReg if we know that the math
4989 // required to create it did not overflow before we extend it. Since
4990 // the original IR value was tossed in favor of a constant back when
4991 // the AddrMode was created we need to bail out gracefully if widths
4992 // do not match instead of extending it.
Joey Gouly12a8bf02014-05-13 15:42:45 +00004993 Instruction *I = dyn_cast_or_null<Instruction>(Result);
Jim Grosbach83b44e12014-04-10 00:27:45 +00004994 if (I && (Result != AddrMode.BaseReg))
4995 I->eraseFromParent();
Jim Grosbached2cd392014-03-26 17:27:01 +00004996 return false;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004997 }
4998 if (AddrMode.Scale != 1)
Devang Patelc10e52a2011-09-06 18:49:53 +00004999 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
5000 "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00005001 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00005002 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00005003 else
5004 Result = V;
5005 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00005006
Chris Lattnerfeee64e2007-04-13 20:30:56 +00005007 // Add in the BaseGV if present.
5008 if (AddrMode.BaseGV) {
Devang Patelc10e52a2011-09-06 18:49:53 +00005009 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00005010 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00005011 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00005012 else
5013 Result = V;
5014 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00005015
Chris Lattnerfeee64e2007-04-13 20:30:56 +00005016 // Add in the Base Offset if present.
5017 if (AddrMode.BaseOffs) {
Owen Andersonedb4a702009-07-24 23:12:02 +00005018 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00005019 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00005020 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00005021 else
5022 Result = V;
5023 }
5024
Craig Topperc0196b12014-04-14 00:51:57 +00005025 if (!Result)
Owen Anderson5a1acd92009-07-31 20:28:14 +00005026 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00005027 else
Devang Patelc10e52a2011-09-06 18:49:53 +00005028 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00005029 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00005030
Owen Andersondfb8c3b2010-11-19 22:15:03 +00005031 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Simon Dardis230f4532017-11-24 16:45:28 +00005032 // Store the newly computed address into the cache. In the case we reused a
5033 // value, this should be idempotent.
5034 SunkAddrs[Addr] = WeakTrackingVH(SunkAddr);
Eric Christopherc1ea1492008-09-24 05:32:41 +00005035
Chris Lattneraf1bcce2011-04-09 07:05:44 +00005036 // If we have no uses, recursively delete the value and all dead instructions
5037 // using it.
Owen Andersondfb8c3b2010-11-19 22:15:03 +00005038 if (Repl->use_empty()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00005039 // This can cause recursive deletion, which can invalidate our iterator.
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00005040 // Use a WeakTrackingVH to hold onto it in case this happens.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00005041 Value *CurValue = &*CurInstIterator;
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00005042 WeakTrackingVH IterHandle(CurValue);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00005043 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00005044
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00005045 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00005046
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00005047 if (IterHandle != CurValue) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00005048 // If the iterator instruction was recursively deleted, start over at the
5049 // start of the block.
5050 CurInstIterator = BB->begin();
5051 SunkAddrs.clear();
Nadav Rotem465834c2012-07-24 10:51:42 +00005052 }
Dale Johannesenb67a6e662010-03-31 20:37:15 +00005053 }
Cameron Zwarichced753f2011-01-05 17:27:27 +00005054 ++NumMemoryInsts;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00005055 return true;
5056}
5057
Sanjay Patel4ac6b112015-09-21 22:47:23 +00005058/// If there are any memory operands, use OptimizeMemoryInst to sink their
5059/// address computing into the block when possible / profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005060bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
Evan Cheng1da25002008-02-26 02:42:37 +00005061 bool MadeChange = false;
Evan Cheng1da25002008-02-26 02:42:37 +00005062
Eric Christopher11e4df72015-02-26 22:38:43 +00005063 const TargetRegisterInfo *TRI =
Sanjay Patel4137d512017-06-07 14:29:52 +00005064 TM->getSubtargetImpl(*CS->getFunction())->getRegisterInfo();
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00005065 TargetLowering::AsmOperandInfoVector TargetConstraints =
5066 TLI->ParseConstraints(*DL, TRI, CS);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00005067 unsigned ArgNo = 0;
John Thompson1094c802010-09-13 18:15:37 +00005068 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
5069 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00005070
Evan Cheng1da25002008-02-26 02:42:37 +00005071 // Compute the constraint code and ConstraintType to use.
Dale Johannesence97d552010-06-25 21:55:36 +00005072 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng1da25002008-02-26 02:42:37 +00005073
Eli Friedman666bbe32008-02-26 18:37:49 +00005074 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
5075 OpInfo.isIndirect) {
Chris Lattner7a277142011-01-15 07:14:54 +00005076 Value *OpVal = CS->getArgOperand(ArgNo++);
Sanjay Patelfc580a62015-09-21 23:03:16 +00005077 MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00005078 } else if (OpInfo.Type == InlineAsm::isInput)
5079 ArgNo++;
Evan Cheng1da25002008-02-26 02:42:37 +00005080 }
5081
5082 return MadeChange;
5083}
5084
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00005085/// Check if all the uses of \p Val are equivalent (or free) zero or
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005086/// sign extensions.
Jun Bum Lim42301012017-03-17 19:05:21 +00005087static bool hasSameExtUse(Value *Val, const TargetLowering &TLI) {
5088 assert(!Val->use_empty() && "Input must have at least one use");
5089 const Instruction *FirstUser = cast<Instruction>(*Val->user_begin());
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005090 bool IsSExt = isa<SExtInst>(FirstUser);
5091 Type *ExtTy = FirstUser->getType();
Jun Bum Lim42301012017-03-17 19:05:21 +00005092 for (const User *U : Val->users()) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005093 const Instruction *UI = cast<Instruction>(U);
5094 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
5095 return false;
5096 Type *CurTy = UI->getType();
5097 // Same input and output types: Same instruction after CSE.
5098 if (CurTy == ExtTy)
5099 continue;
5100
5101 // If IsSExt is true, we are in this situation:
Jun Bum Lim42301012017-03-17 19:05:21 +00005102 // a = Val
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005103 // b = sext ty1 a to ty2
5104 // c = sext ty1 a to ty3
5105 // Assuming ty2 is shorter than ty3, this could be turned into:
Jun Bum Lim42301012017-03-17 19:05:21 +00005106 // a = Val
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005107 // b = sext ty1 a to ty2
5108 // c = sext ty2 b to ty3
5109 // However, the last sext is not free.
5110 if (IsSExt)
5111 return false;
5112
5113 // This is a ZExt, maybe this is free to extend from one type to another.
5114 // In that case, we would not account for a different use.
5115 Type *NarrowTy;
5116 Type *LargeTy;
5117 if (ExtTy->getScalarType()->getIntegerBitWidth() >
5118 CurTy->getScalarType()->getIntegerBitWidth()) {
5119 NarrowTy = CurTy;
5120 LargeTy = ExtTy;
5121 } else {
5122 NarrowTy = ExtTy;
5123 LargeTy = CurTy;
5124 }
5125
5126 if (!TLI.isZExtFree(NarrowTy, LargeTy))
5127 return false;
5128 }
5129 // All uses are the same or can be derived from one another for free.
5130 return true;
5131}
5132
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00005133/// Try to speculatively promote extensions in \p Exts and continue
Jun Bum Lim42301012017-03-17 19:05:21 +00005134/// promoting through newly promoted operands recursively as far as doing so is
5135/// profitable. Save extensions profitably moved up, in \p ProfitablyMovedExts.
5136/// When some promotion happened, \p TPT contains the proper state to revert
5137/// them.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005138///
Jun Bum Lim42301012017-03-17 19:05:21 +00005139/// \return true if some promotion happened, false otherwise.
Jun Bum Lim42301012017-03-17 19:05:21 +00005140bool CodeGenPrepare::tryToPromoteExts(
5141 TypePromotionTransaction &TPT, const SmallVectorImpl<Instruction *> &Exts,
5142 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
5143 unsigned CreatedInstsCost) {
5144 bool Promoted = false;
5145
5146 // Iterate over all the extensions to try to promote them.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005147 for (auto I : Exts) {
Jun Bum Lim42301012017-03-17 19:05:21 +00005148 // Early check if we directly have ext(load).
5149 if (isa<LoadInst>(I->getOperand(0))) {
5150 ProfitablyMovedExts.push_back(I);
5151 continue;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005152 }
Jun Bum Lim42301012017-03-17 19:05:21 +00005153
5154 // Check whether or not we want to do any promotion. The reason we have
5155 // this check inside the for loop is to catch the case where an extension
5156 // is directly fed by a load because in such case the extension can be moved
5157 // up without any promotion on its operands.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005158 if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
Jun Bum Lim42301012017-03-17 19:05:21 +00005159 return false;
5160
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005161 // Get the action to perform the promotion.
Jun Bum Lim42301012017-03-17 19:05:21 +00005162 TypePromotionHelper::Action TPH =
5163 TypePromotionHelper::getAction(I, InsertedInsts, *TLI, PromotedInsts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005164 // Check if we can promote.
Jun Bum Lim42301012017-03-17 19:05:21 +00005165 if (!TPH) {
5166 // Save the current extension as we cannot move up through its operand.
5167 ProfitablyMovedExts.push_back(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005168 continue;
Jun Bum Lim42301012017-03-17 19:05:21 +00005169 }
5170
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005171 // Save the current state.
5172 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5173 TPT.getRestorationPoint();
5174 SmallVector<Instruction *, 4> NewExts;
Quentin Colombet1b274f92015-03-10 21:48:15 +00005175 unsigned NewCreatedInstsCost = 0;
5176 unsigned ExtCost = !TLI->isExtFree(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005177 // Promote.
Quentin Colombet1b274f92015-03-10 21:48:15 +00005178 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
5179 &NewExts, nullptr, *TLI);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005180 assert(PromotedVal &&
5181 "TypePromotionHelper should have filtered out those cases");
5182
5183 // We would be able to merge only one extension in a load.
5184 // Therefore, if we have more than 1 new extension we heuristically
5185 // cut this search path, because it means we degrade the code quality.
5186 // With exactly 2, the transformation is neutral, because we will merge
5187 // one extension but leave one. However, we optimistically keep going,
5188 // because the new extension may be removed too.
Quentin Colombet1b274f92015-03-10 21:48:15 +00005189 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
Jun Bum Limb99a06b2017-01-27 17:16:37 +00005190 // FIXME: It would be possible to propagate a negative value instead of
Jun Bum Lim42301012017-03-17 19:05:21 +00005191 // conservatively ceiling it to 0.
Jun Bum Limb99a06b2017-01-27 17:16:37 +00005192 TotalCreatedInstsCost =
5193 std::max((long long)0, (TotalCreatedInstsCost - ExtCost));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005194 if (!StressExtLdPromotion &&
Quentin Colombet1b274f92015-03-10 21:48:15 +00005195 (TotalCreatedInstsCost > 1 ||
Mehdi Amini44ede332015-07-09 02:09:04 +00005196 !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
Jun Bum Lim42301012017-03-17 19:05:21 +00005197 // This promotion is not profitable, rollback to the previous state, and
5198 // save the current extension in ProfitablyMovedExts as the latest
5199 // speculative promotion turned out to be unprofitable.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005200 TPT.rollback(LastKnownGood);
Jun Bum Lim42301012017-03-17 19:05:21 +00005201 ProfitablyMovedExts.push_back(I);
5202 continue;
5203 }
5204 // Continue promoting NewExts as far as doing so is profitable.
5205 SmallVector<Instruction *, 2> NewlyMovedExts;
5206 (void)tryToPromoteExts(TPT, NewExts, NewlyMovedExts, TotalCreatedInstsCost);
5207 bool NewPromoted = false;
5208 for (auto ExtInst : NewlyMovedExts) {
5209 Instruction *MovedExt = cast<Instruction>(ExtInst);
5210 Value *ExtOperand = MovedExt->getOperand(0);
5211 // If we have reached to a load, we need this extra profitability check
5212 // as it could potentially be merged into an ext(load).
5213 if (isa<LoadInst>(ExtOperand) &&
5214 !(StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
5215 (ExtOperand->hasOneUse() || hasSameExtUse(ExtOperand, *TLI))))
5216 continue;
5217
5218 ProfitablyMovedExts.push_back(MovedExt);
5219 NewPromoted = true;
5220 }
5221
5222 // If none of speculative promotions for NewExts is profitable, rollback
5223 // and save the current extension (I) as the last profitable extension.
5224 if (!NewPromoted) {
5225 TPT.rollback(LastKnownGood);
5226 ProfitablyMovedExts.push_back(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005227 continue;
5228 }
5229 // The promotion is profitable.
Jun Bum Lim42301012017-03-17 19:05:21 +00005230 Promoted = true;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005231 }
Jun Bum Lim42301012017-03-17 19:05:21 +00005232 return Promoted;
5233}
5234
Jun Bum Limdee55652017-04-03 19:20:07 +00005235/// Merging redundant sexts when one is dominating the other.
Teresa Johnson3bd4b5a2019-03-25 18:38:48 +00005236bool CodeGenPrepare::mergeSExts(Function &F) {
Jun Bum Limdee55652017-04-03 19:20:07 +00005237 bool Changed = false;
5238 for (auto &Entry : ValToSExtendedUses) {
5239 SExts &Insts = Entry.second;
5240 SExts CurPts;
5241 for (Instruction *Inst : Insts) {
5242 if (RemovedInsts.count(Inst) || !isa<SExtInst>(Inst) ||
5243 Inst->getOperand(0) != Entry.first)
5244 continue;
5245 bool inserted = false;
5246 for (auto &Pt : CurPts) {
Teresa Johnson3bd4b5a2019-03-25 18:38:48 +00005247 if (getDT(F).dominates(Inst, Pt)) {
Jun Bum Limdee55652017-04-03 19:20:07 +00005248 Pt->replaceAllUsesWith(Inst);
5249 RemovedInsts.insert(Pt);
5250 Pt->removeFromParent();
5251 Pt = Inst;
5252 inserted = true;
5253 Changed = true;
5254 break;
5255 }
Teresa Johnson3bd4b5a2019-03-25 18:38:48 +00005256 if (!getDT(F).dominates(Pt, Inst))
Jun Bum Limdee55652017-04-03 19:20:07 +00005257 // Give up if we need to merge in a common dominator as the
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00005258 // experiments show it is not profitable.
Jun Bum Limdee55652017-04-03 19:20:07 +00005259 continue;
5260 Inst->replaceAllUsesWith(Pt);
5261 RemovedInsts.insert(Inst);
5262 Inst->removeFromParent();
5263 inserted = true;
5264 Changed = true;
5265 break;
5266 }
5267 if (!inserted)
5268 CurPts.push_back(Inst);
5269 }
5270 }
5271 return Changed;
5272}
5273
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00005274// Spliting large data structures so that the GEPs accessing them can have
5275// smaller offsets so that they can be sunk to the same blocks as their users.
5276// For example, a large struct starting from %base is splitted into two parts
5277// where the second part starts from %new_base.
5278//
5279// Before:
5280// BB0:
5281// %base =
5282//
5283// BB1:
5284// %gep0 = gep %base, off0
5285// %gep1 = gep %base, off1
5286// %gep2 = gep %base, off2
5287//
5288// BB2:
5289// %load1 = load %gep0
5290// %load2 = load %gep1
5291// %load3 = load %gep2
5292//
5293// After:
5294// BB0:
5295// %base =
5296// %new_base = gep %base, off0
5297//
5298// BB1:
5299// %new_gep0 = %new_base
5300// %new_gep1 = gep %new_base, off1 - off0
5301// %new_gep2 = gep %new_base, off2 - off0
5302//
5303// BB2:
5304// %load1 = load i32, i32* %new_gep0
5305// %load2 = load i32, i32* %new_gep1
5306// %load3 = load i32, i32* %new_gep2
5307//
5308// %new_gep1 and %new_gep2 can be sunk to BB2 now after the splitting because
5309// their offsets are smaller enough to fit into the addressing mode.
5310bool CodeGenPrepare::splitLargeGEPOffsets() {
5311 bool Changed = false;
5312 for (auto &Entry : LargeOffsetGEPMap) {
5313 Value *OldBase = Entry.first;
5314 SmallVectorImpl<std::pair<AssertingVH<GetElementPtrInst>, int64_t>>
5315 &LargeOffsetGEPs = Entry.second;
5316 auto compareGEPOffset =
5317 [&](const std::pair<GetElementPtrInst *, int64_t> &LHS,
5318 const std::pair<GetElementPtrInst *, int64_t> &RHS) {
5319 if (LHS.first == RHS.first)
5320 return false;
5321 if (LHS.second != RHS.second)
5322 return LHS.second < RHS.second;
5323 return LargeOffsetGEPID[LHS.first] < LargeOffsetGEPID[RHS.first];
5324 };
5325 // Sorting all the GEPs of the same data structures based on the offsets.
Fangrui Song0cac7262018-09-27 02:13:45 +00005326 llvm::sort(LargeOffsetGEPs, compareGEPOffset);
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00005327 LargeOffsetGEPs.erase(
5328 std::unique(LargeOffsetGEPs.begin(), LargeOffsetGEPs.end()),
5329 LargeOffsetGEPs.end());
5330 // Skip if all the GEPs have the same offsets.
5331 if (LargeOffsetGEPs.front().second == LargeOffsetGEPs.back().second)
5332 continue;
5333 GetElementPtrInst *BaseGEP = LargeOffsetGEPs.begin()->first;
5334 int64_t BaseOffset = LargeOffsetGEPs.begin()->second;
5335 Value *NewBaseGEP = nullptr;
5336
5337 auto LargeOffsetGEP = LargeOffsetGEPs.begin();
5338 while (LargeOffsetGEP != LargeOffsetGEPs.end()) {
5339 GetElementPtrInst *GEP = LargeOffsetGEP->first;
5340 int64_t Offset = LargeOffsetGEP->second;
5341 if (Offset != BaseOffset) {
5342 TargetLowering::AddrMode AddrMode;
5343 AddrMode.BaseOffs = Offset - BaseOffset;
5344 // The result type of the GEP might not be the type of the memory
5345 // access.
5346 if (!TLI->isLegalAddressingMode(*DL, AddrMode,
5347 GEP->getResultElementType(),
5348 GEP->getAddressSpace())) {
5349 // We need to create a new base if the offset to the current base is
5350 // too large to fit into the addressing mode. So, a very large struct
5351 // may be splitted into several parts.
5352 BaseGEP = GEP;
5353 BaseOffset = Offset;
5354 NewBaseGEP = nullptr;
5355 }
5356 }
5357
5358 // Generate a new GEP to replace the current one.
Eli Friedmana69084f2018-12-19 22:52:04 +00005359 LLVMContext &Ctx = GEP->getContext();
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00005360 Type *IntPtrTy = DL->getIntPtrType(GEP->getType());
5361 Type *I8PtrTy =
Eli Friedmana69084f2018-12-19 22:52:04 +00005362 Type::getInt8PtrTy(Ctx, GEP->getType()->getPointerAddressSpace());
5363 Type *I8Ty = Type::getInt8Ty(Ctx);
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00005364
5365 if (!NewBaseGEP) {
5366 // Create a new base if we don't have one yet. Find the insertion
5367 // pointer for the new base first.
5368 BasicBlock::iterator NewBaseInsertPt;
5369 BasicBlock *NewBaseInsertBB;
5370 if (auto *BaseI = dyn_cast<Instruction>(OldBase)) {
5371 // If the base of the struct is an instruction, the new base will be
5372 // inserted close to it.
5373 NewBaseInsertBB = BaseI->getParent();
5374 if (isa<PHINode>(BaseI))
5375 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
5376 else if (InvokeInst *Invoke = dyn_cast<InvokeInst>(BaseI)) {
5377 NewBaseInsertBB =
5378 SplitEdge(NewBaseInsertBB, Invoke->getNormalDest());
5379 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
5380 } else
5381 NewBaseInsertPt = std::next(BaseI->getIterator());
5382 } else {
5383 // If the current base is an argument or global value, the new base
5384 // will be inserted to the entry block.
5385 NewBaseInsertBB = &BaseGEP->getFunction()->getEntryBlock();
5386 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
5387 }
5388 IRBuilder<> NewBaseBuilder(NewBaseInsertBB, NewBaseInsertPt);
5389 // Create a new base.
5390 Value *BaseIndex = ConstantInt::get(IntPtrTy, BaseOffset);
5391 NewBaseGEP = OldBase;
5392 if (NewBaseGEP->getType() != I8PtrTy)
5393 NewBaseGEP = NewBaseBuilder.CreatePointerCast(NewBaseGEP, I8PtrTy);
5394 NewBaseGEP =
5395 NewBaseBuilder.CreateGEP(I8Ty, NewBaseGEP, BaseIndex, "splitgep");
5396 NewGEPBases.insert(NewBaseGEP);
5397 }
5398
Eli Friedmana69084f2018-12-19 22:52:04 +00005399 IRBuilder<> Builder(GEP);
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00005400 Value *NewGEP = NewBaseGEP;
5401 if (Offset == BaseOffset) {
5402 if (GEP->getType() != I8PtrTy)
5403 NewGEP = Builder.CreatePointerCast(NewGEP, GEP->getType());
5404 } else {
5405 // Calculate the new offset for the new GEP.
5406 Value *Index = ConstantInt::get(IntPtrTy, Offset - BaseOffset);
5407 NewGEP = Builder.CreateGEP(I8Ty, NewBaseGEP, Index);
5408
5409 if (GEP->getType() != I8PtrTy)
5410 NewGEP = Builder.CreatePointerCast(NewGEP, GEP->getType());
5411 }
5412 GEP->replaceAllUsesWith(NewGEP);
5413 LargeOffsetGEPID.erase(GEP);
5414 LargeOffsetGEP = LargeOffsetGEPs.erase(LargeOffsetGEP);
5415 GEP->eraseFromParent();
5416 Changed = true;
5417 }
5418 }
5419 return Changed;
5420}
5421
Jun Bum Lim42301012017-03-17 19:05:21 +00005422/// Return true, if an ext(load) can be formed from an extension in
5423/// \p MovedExts.
5424bool CodeGenPrepare::canFormExtLd(
5425 const SmallVectorImpl<Instruction *> &MovedExts, LoadInst *&LI,
5426 Instruction *&Inst, bool HasPromoted) {
5427 for (auto *MovedExtInst : MovedExts) {
5428 if (isa<LoadInst>(MovedExtInst->getOperand(0))) {
5429 LI = cast<LoadInst>(MovedExtInst->getOperand(0));
5430 Inst = MovedExtInst;
5431 break;
5432 }
5433 }
5434 if (!LI)
5435 return false;
5436
5437 // If they're already in the same block, there's nothing to do.
5438 // Make the cheap checks first if we did not promote.
5439 // If we promoted, we need to check if it is indeed profitable.
5440 if (!HasPromoted && LI->getParent() == Inst->getParent())
5441 return false;
5442
Haicheng Wuabdef9e2017-07-15 02:12:16 +00005443 return TLI->isExtLoad(LI, Inst, *DL);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005444}
5445
Sanjay Patel4ac6b112015-09-21 22:47:23 +00005446/// Move a zext or sext fed by a load into the same basic block as the load,
5447/// unless conditions are unfavorable. This allows SelectionDAG to fold the
5448/// extend into the load.
Dan Gohman99429a02009-10-16 20:59:35 +00005449///
Jun Bum Limdee55652017-04-03 19:20:07 +00005450/// E.g.,
5451/// \code
5452/// %ld = load i32* %addr
5453/// %add = add nuw i32 %ld, 4
5454/// %zext = zext i32 %add to i64
5455// \endcode
5456/// =>
5457/// \code
5458/// %ld = load i32* %addr
5459/// %zext = zext i32 %ld to i64
5460/// %add = add nuw i64 %zext, 4
5461/// \encode
5462/// Note that the promotion in %add to i64 is done in tryToPromoteExts(), which
5463/// allow us to match zext(load i32*) to i64.
5464///
5465/// Also, try to promote the computations used to obtain a sign extended
5466/// value used into memory accesses.
5467/// E.g.,
5468/// \code
5469/// a = add nsw i32 b, 3
5470/// d = sext i32 a to i64
5471/// e = getelementptr ..., i64 d
5472/// \endcode
5473/// =>
5474/// \code
5475/// f = sext i32 b to i64
5476/// a = add nsw i64 f, 3
5477/// e = getelementptr ..., i64 a
5478/// \endcode
5479///
5480/// \p Inst[in/out] the extension may be modified during the process if some
5481/// promotions apply.
5482bool CodeGenPrepare::optimizeExt(Instruction *&Inst) {
5483 // ExtLoad formation and address type promotion infrastructure requires TLI to
5484 // be effective.
Chandler Carruth0f139b42016-11-04 06:54:00 +00005485 if (!TLI)
5486 return false;
5487
Jun Bum Limdee55652017-04-03 19:20:07 +00005488 bool AllowPromotionWithoutCommonHeader = false;
5489 /// See if it is an interesting sext operations for the address type
5490 /// promotion before trying to promote it, e.g., the ones with the right
5491 /// type and used in memory accesses.
5492 bool ATPConsiderable = TTI->shouldConsiderAddressTypePromotion(
5493 *Inst, AllowPromotionWithoutCommonHeader);
5494 TypePromotionTransaction TPT(RemovedInsts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005495 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
Jun Bum Lim42301012017-03-17 19:05:21 +00005496 TPT.getRestorationPoint();
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005497 SmallVector<Instruction *, 1> Exts;
Jun Bum Limdee55652017-04-03 19:20:07 +00005498 SmallVector<Instruction *, 2> SpeculativelyMovedExts;
5499 Exts.push_back(Inst);
Jun Bum Lim42301012017-03-17 19:05:21 +00005500
Jun Bum Limdee55652017-04-03 19:20:07 +00005501 bool HasPromoted = tryToPromoteExts(TPT, Exts, SpeculativelyMovedExts);
Jun Bum Lim42301012017-03-17 19:05:21 +00005502
Dan Gohman99429a02009-10-16 20:59:35 +00005503 // Look for a load being extended.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005504 LoadInst *LI = nullptr;
Jun Bum Limdee55652017-04-03 19:20:07 +00005505 Instruction *ExtFedByLoad;
5506
5507 // Try to promote a chain of computation if it allows to form an extended
5508 // load.
5509 if (canFormExtLd(SpeculativelyMovedExts, LI, ExtFedByLoad, HasPromoted)) {
5510 assert(LI && ExtFedByLoad && "Expect a valid load and extension");
5511 TPT.commit();
5512 // Move the extend into the same block as the load
Sanjay Patel674d2c22017-08-29 14:07:48 +00005513 ExtFedByLoad->moveAfter(LI);
Jun Bum Limdee55652017-04-03 19:20:07 +00005514 // CGP does not check if the zext would be speculatively executed when moved
5515 // to the same basic block as the load. Preserving its original location
5516 // would pessimize the debugging experience, as well as negatively impact
5517 // the quality of sample pgo. We don't want to use "line 0" as that has a
5518 // size cost in the line-table section and logically the zext can be seen as
5519 // part of the load. Therefore we conservatively reuse the same debug
5520 // location for the load and the zext.
5521 ExtFedByLoad->setDebugLoc(LI->getDebugLoc());
5522 ++NumExtsMoved;
5523 Inst = ExtFedByLoad;
5524 return true;
5525 }
5526
5527 // Continue promoting SExts if known as considerable depending on targets.
5528 if (ATPConsiderable &&
5529 performAddressTypePromotion(Inst, AllowPromotionWithoutCommonHeader,
5530 HasPromoted, TPT, SpeculativelyMovedExts))
5531 return true;
5532
5533 TPT.rollback(LastKnownGood);
5534 return false;
5535}
5536
5537// Perform address type promotion if doing so is profitable.
5538// If AllowPromotionWithoutCommonHeader == false, we should find other sext
5539// instructions that sign extended the same initial value. However, if
5540// AllowPromotionWithoutCommonHeader == true, we expect promoting the
5541// extension is just profitable.
5542bool CodeGenPrepare::performAddressTypePromotion(
5543 Instruction *&Inst, bool AllowPromotionWithoutCommonHeader,
5544 bool HasPromoted, TypePromotionTransaction &TPT,
5545 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts) {
5546 bool Promoted = false;
5547 SmallPtrSet<Instruction *, 1> UnhandledExts;
5548 bool AllSeenFirst = true;
5549 for (auto I : SpeculativelyMovedExts) {
5550 Value *HeadOfChain = I->getOperand(0);
5551 DenseMap<Value *, Instruction *>::iterator AlreadySeen =
5552 SeenChainsForSExt.find(HeadOfChain);
5553 // If there is an unhandled SExt which has the same header, try to promote
5554 // it as well.
5555 if (AlreadySeen != SeenChainsForSExt.end()) {
5556 if (AlreadySeen->second != nullptr)
5557 UnhandledExts.insert(AlreadySeen->second);
5558 AllSeenFirst = false;
5559 }
5560 }
5561
5562 if (!AllSeenFirst || (AllowPromotionWithoutCommonHeader &&
5563 SpeculativelyMovedExts.size() == 1)) {
5564 TPT.commit();
5565 if (HasPromoted)
5566 Promoted = true;
5567 for (auto I : SpeculativelyMovedExts) {
5568 Value *HeadOfChain = I->getOperand(0);
5569 SeenChainsForSExt[HeadOfChain] = nullptr;
5570 ValToSExtendedUses[HeadOfChain].push_back(I);
5571 }
5572 // Update Inst as promotion happen.
5573 Inst = SpeculativelyMovedExts.pop_back_val();
5574 } else {
5575 // This is the first chain visited from the header, keep the current chain
5576 // as unhandled. Defer to promote this until we encounter another SExt
5577 // chain derived from the same header.
5578 for (auto I : SpeculativelyMovedExts) {
5579 Value *HeadOfChain = I->getOperand(0);
5580 SeenChainsForSExt[HeadOfChain] = Inst;
5581 }
Dan Gohman99429a02009-10-16 20:59:35 +00005582 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005583 }
Dan Gohman99429a02009-10-16 20:59:35 +00005584
Jun Bum Limdee55652017-04-03 19:20:07 +00005585 if (!AllSeenFirst && !UnhandledExts.empty())
5586 for (auto VisitedSExt : UnhandledExts) {
5587 if (RemovedInsts.count(VisitedSExt))
5588 continue;
5589 TypePromotionTransaction TPT(RemovedInsts);
5590 SmallVector<Instruction *, 1> Exts;
5591 SmallVector<Instruction *, 2> Chains;
5592 Exts.push_back(VisitedSExt);
5593 bool HasPromoted = tryToPromoteExts(TPT, Exts, Chains);
5594 TPT.commit();
5595 if (HasPromoted)
5596 Promoted = true;
5597 for (auto I : Chains) {
5598 Value *HeadOfChain = I->getOperand(0);
5599 // Mark this as handled.
5600 SeenChainsForSExt[HeadOfChain] = nullptr;
5601 ValToSExtendedUses[HeadOfChain].push_back(I);
5602 }
5603 }
5604 return Promoted;
Dan Gohman99429a02009-10-16 20:59:35 +00005605}
5606
Sanjay Patelfc580a62015-09-21 23:03:16 +00005607bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
Evan Chengd3d80172007-12-05 23:58:20 +00005608 BasicBlock *DefBB = I->getParent();
5609
Bob Wilsonff714f92010-09-21 21:44:14 +00005610 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengd3d80172007-12-05 23:58:20 +00005611 // other uses of the source with result of extension.
5612 Value *Src = I->getOperand(0);
5613 if (Src->hasOneUse())
5614 return false;
5615
Evan Cheng2011df42007-12-13 07:50:36 +00005616 // Only do this xform if truncating is free.
Gabor Greifaa261722008-02-26 19:13:21 +00005617 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Cheng37c36ed2007-12-13 03:32:53 +00005618 return false;
5619
Evan Cheng7bc89422007-12-12 00:51:06 +00005620 // Only safe to perform the optimization if the source is also defined in
Evan Cheng63d33cf2007-12-12 02:53:41 +00005621 // this block.
5622 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng7bc89422007-12-12 00:51:06 +00005623 return false;
5624
Evan Chengd3d80172007-12-05 23:58:20 +00005625 bool DefIsLiveOut = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00005626 for (User *U : I->users()) {
5627 Instruction *UI = cast<Instruction>(U);
Evan Chengd3d80172007-12-05 23:58:20 +00005628
5629 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005630 BasicBlock *UserBB = UI->getParent();
Evan Chengd3d80172007-12-05 23:58:20 +00005631 if (UserBB == DefBB) continue;
5632 DefIsLiveOut = true;
5633 break;
5634 }
5635 if (!DefIsLiveOut)
5636 return false;
5637
Jim Grosbach0f38c1e2013-04-15 17:40:48 +00005638 // Make sure none of the uses are PHI nodes.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005639 for (User *U : Src->users()) {
5640 Instruction *UI = cast<Instruction>(U);
5641 BasicBlock *UserBB = UI->getParent();
Evan Cheng37c36ed2007-12-13 03:32:53 +00005642 if (UserBB == DefBB) continue;
5643 // Be conservative. We don't want this xform to end up introducing
5644 // reloads just before load / store instructions.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005645 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
Evan Cheng63d33cf2007-12-12 02:53:41 +00005646 return false;
5647 }
5648
Evan Chengd3d80172007-12-05 23:58:20 +00005649 // InsertedTruncs - Only insert one trunc in each block once.
5650 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
5651
5652 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00005653 for (Use &U : Src->uses()) {
5654 Instruction *User = cast<Instruction>(U.getUser());
Evan Chengd3d80172007-12-05 23:58:20 +00005655
5656 // Figure out which BB this ext is used in.
5657 BasicBlock *UserBB = User->getParent();
5658 if (UserBB == DefBB) continue;
5659
5660 // Both src and def are live in this block. Rewrite the use.
5661 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
5662
5663 if (!InsertedTrunc) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00005664 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005665 assert(InsertPt != UserBB->end());
5666 InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00005667 InsertedInsts.insert(InsertedTrunc);
Evan Chengd3d80172007-12-05 23:58:20 +00005668 }
5669
5670 // Replace a use of the {s|z}ext source with a use of the result.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005671 U = InsertedTrunc;
Cameron Zwarichced753f2011-01-05 17:27:27 +00005672 ++NumExtUses;
Evan Chengd3d80172007-12-05 23:58:20 +00005673 MadeChange = true;
5674 }
5675
5676 return MadeChange;
5677}
5678
Geoff Berry5256fca2015-11-20 22:34:39 +00005679// Find loads whose uses only use some of the loaded value's bits. Add an "and"
5680// just after the load if the target can fold this into one extload instruction,
5681// with the hope of eliminating some of the other later "and" instructions using
5682// the loaded value. "and"s that are made trivially redundant by the insertion
5683// of the new "and" are removed by this function, while others (e.g. those whose
5684// path from the load goes through a phi) are left for isel to potentially
5685// remove.
5686//
5687// For example:
5688//
5689// b0:
5690// x = load i32
5691// ...
5692// b1:
5693// y = and x, 0xff
5694// z = use y
5695//
5696// becomes:
5697//
5698// b0:
5699// x = load i32
5700// x' = and x, 0xff
5701// ...
5702// b1:
5703// z = use x'
5704//
5705// whereas:
5706//
5707// b0:
5708// x1 = load i32
5709// ...
5710// b1:
5711// x2 = load i32
5712// ...
5713// b2:
5714// x = phi x1, x2
5715// y = and x, 0xff
5716//
5717// becomes (after a call to optimizeLoadExt for each load):
5718//
5719// b0:
5720// x1 = load i32
5721// x1' = and x1, 0xff
5722// ...
5723// b1:
5724// x2 = load i32
5725// x2' = and x2, 0xff
5726// ...
5727// b2:
5728// x = phi x1', x2'
5729// y = and x, 0xff
Geoff Berry5256fca2015-11-20 22:34:39 +00005730bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
Vedant Kumarb3091da2018-07-06 20:17:42 +00005731 if (!Load->isSimple() || !Load->getType()->isIntOrPtrTy())
Geoff Berry5256fca2015-11-20 22:34:39 +00005732 return false;
5733
Geoff Berry5d534b62017-02-21 18:53:14 +00005734 // Skip loads we've already transformed.
5735 if (Load->hasOneUse() &&
5736 InsertedInsts.count(cast<Instruction>(*Load->user_begin())))
5737 return false;
Geoff Berry5256fca2015-11-20 22:34:39 +00005738
5739 // Look at all uses of Load, looking through phis, to determine how many bits
5740 // of the loaded value are needed.
5741 SmallVector<Instruction *, 8> WorkList;
5742 SmallPtrSet<Instruction *, 16> Visited;
5743 SmallVector<Instruction *, 8> AndsToMaybeRemove;
5744 for (auto *U : Load->users())
5745 WorkList.push_back(cast<Instruction>(U));
5746
5747 EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
5748 unsigned BitWidth = LoadResultVT.getSizeInBits();
5749 APInt DemandBits(BitWidth, 0);
5750 APInt WidestAndBits(BitWidth, 0);
5751
5752 while (!WorkList.empty()) {
5753 Instruction *I = WorkList.back();
5754 WorkList.pop_back();
5755
5756 // Break use-def graph loops.
5757 if (!Visited.insert(I).second)
5758 continue;
5759
5760 // For a PHI node, push all of its users.
5761 if (auto *Phi = dyn_cast<PHINode>(I)) {
5762 for (auto *U : Phi->users())
5763 WorkList.push_back(cast<Instruction>(U));
5764 continue;
5765 }
5766
5767 switch (I->getOpcode()) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00005768 case Instruction::And: {
Geoff Berry5256fca2015-11-20 22:34:39 +00005769 auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
5770 if (!AndC)
5771 return false;
5772 APInt AndBits = AndC->getValue();
5773 DemandBits |= AndBits;
5774 // Keep track of the widest and mask we see.
5775 if (AndBits.ugt(WidestAndBits))
5776 WidestAndBits = AndBits;
5777 if (AndBits == WidestAndBits && I->getOperand(0) == Load)
5778 AndsToMaybeRemove.push_back(I);
5779 break;
5780 }
5781
Eugene Zelenko900b6332017-08-29 22:32:07 +00005782 case Instruction::Shl: {
Geoff Berry5256fca2015-11-20 22:34:39 +00005783 auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
5784 if (!ShlC)
5785 return false;
5786 uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
Craig Topperfc947bc2017-04-18 17:14:21 +00005787 DemandBits.setLowBits(BitWidth - ShiftAmt);
Geoff Berry5256fca2015-11-20 22:34:39 +00005788 break;
5789 }
5790
Eugene Zelenko900b6332017-08-29 22:32:07 +00005791 case Instruction::Trunc: {
Geoff Berry5256fca2015-11-20 22:34:39 +00005792 EVT TruncVT = TLI->getValueType(*DL, I->getType());
5793 unsigned TruncBitWidth = TruncVT.getSizeInBits();
Craig Topperfc947bc2017-04-18 17:14:21 +00005794 DemandBits.setLowBits(TruncBitWidth);
Geoff Berry5256fca2015-11-20 22:34:39 +00005795 break;
5796 }
5797
5798 default:
5799 return false;
5800 }
5801 }
5802
5803 uint32_t ActiveBits = DemandBits.getActiveBits();
5804 // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
5805 // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example,
5806 // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but
5807 // (and (load x) 1) is not matched as a single instruction, rather as a LDR
5808 // followed by an AND.
5809 // TODO: Look into removing this restriction by fixing backends to either
5810 // return false for isLoadExtLegal for i1 or have them select this pattern to
5811 // a single instruction.
5812 //
5813 // Also avoid hoisting if we didn't see any ands with the exact DemandBits
5814 // mask, since these are the only ands that will be removed by isel.
Craig Topperd33ee1b2017-04-03 16:34:59 +00005815 if (ActiveBits <= 1 || !DemandBits.isMask(ActiveBits) ||
Geoff Berry5256fca2015-11-20 22:34:39 +00005816 WidestAndBits != DemandBits)
5817 return false;
5818
5819 LLVMContext &Ctx = Load->getType()->getContext();
5820 Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
5821 EVT TruncVT = TLI->getValueType(*DL, TruncTy);
5822
5823 // Reject cases that won't be matched as extloads.
5824 if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
5825 !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT))
5826 return false;
5827
5828 IRBuilder<> Builder(Load->getNextNode());
5829 auto *NewAnd = dyn_cast<Instruction>(
5830 Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
Geoff Berry5d534b62017-02-21 18:53:14 +00005831 // Mark this instruction as "inserted by CGP", so that other
5832 // optimizations don't touch it.
5833 InsertedInsts.insert(NewAnd);
Geoff Berry5256fca2015-11-20 22:34:39 +00005834
5835 // Replace all uses of load with new and (except for the use of load in the
5836 // new and itself).
5837 Load->replaceAllUsesWith(NewAnd);
5838 NewAnd->setOperand(0, Load);
5839
5840 // Remove any and instructions that are now redundant.
5841 for (auto *And : AndsToMaybeRemove)
5842 // Check that the and mask is the same as the one we decided to put on the
5843 // new and.
5844 if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
5845 And->replaceAllUsesWith(NewAnd);
5846 if (&*CurInstIterator == And)
5847 CurInstIterator = std::next(And->getIterator());
5848 And->eraseFromParent();
5849 ++NumAndUses;
5850 }
5851
5852 ++NumAndsAdded;
5853 return true;
5854}
5855
Sanjay Patel69a50a12015-10-19 21:59:12 +00005856/// Check if V (an operand of a select instruction) is an expensive instruction
5857/// that is only used once.
5858static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
5859 auto *I = dyn_cast<Instruction>(V);
5860 // If it's safe to speculatively execute, then it should not have side
5861 // effects; therefore, it's safe to sink and possibly *not* execute.
Rafael Espindola84921b92015-10-24 23:11:13 +00005862 return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
5863 TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005864}
5865
Sanjay Patel4ac6b112015-09-21 22:47:23 +00005866/// Returns true if a SelectInst should be turned into an explicit branch.
Sanjay Patel69a50a12015-10-19 21:59:12 +00005867static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
Sanjay Pateld66607b2016-04-26 17:11:17 +00005868 const TargetLowering *TLI,
Sanjay Patel69a50a12015-10-19 21:59:12 +00005869 SelectInst *SI) {
Sanjay Pateld66607b2016-04-26 17:11:17 +00005870 // If even a predictable select is cheap, then a branch can't be cheaper.
5871 if (!TLI->isPredictableSelectExpensive())
5872 return false;
5873
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005874 // FIXME: This should use the same heuristics as IfConversion to determine
Sanjay Pateld66607b2016-04-26 17:11:17 +00005875 // whether a select is better represented as a branch.
5876
5877 // If metadata tells us that the select condition is obviously predictable,
5878 // then we want to replace the select with a branch.
5879 uint64_t TrueWeight, FalseWeight;
5880 if (SI->extractProfMetadata(TrueWeight, FalseWeight)) {
5881 uint64_t Max = std::max(TrueWeight, FalseWeight);
5882 uint64_t Sum = TrueWeight + FalseWeight;
Sanjay Patelc7b91e62016-05-09 17:31:55 +00005883 if (Sum != 0) {
5884 auto Probability = BranchProbability::getBranchProbability(Max, Sum);
5885 if (Probability > TLI->getPredictableBranchThreshold())
5886 return true;
5887 }
Sanjay Pateld66607b2016-04-26 17:11:17 +00005888 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005889
5890 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
5891
Sanjay Patel4e652762015-09-28 22:14:51 +00005892 // If a branch is predictable, an out-of-order CPU can avoid blocking on its
5893 // comparison condition. If the compare has more than one use, there's
5894 // probably another cmov or setcc around, so it's not worth emitting a branch.
Sanjay Patel5e5f0e92015-09-28 21:44:46 +00005895 if (!Cmp || !Cmp->hasOneUse())
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005896 return false;
5897
Sanjay Patel69a50a12015-10-19 21:59:12 +00005898 // If either operand of the select is expensive and only needed on one side
5899 // of the select, we should form a branch.
5900 if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
5901 sinkSelectOperand(TTI, SI->getFalseValue()))
5902 return true;
5903
5904 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005905}
5906
Dehao Chen9bbb9412016-09-12 20:23:28 +00005907/// If \p isTrue is true, return the true value of \p SI, otherwise return
5908/// false value of \p SI. If the true/false value of \p SI is defined by any
5909/// select instructions in \p Selects, look through the defining select
5910/// instruction until the true/false value is not defined in \p Selects.
5911static Value *getTrueOrFalseValue(
5912 SelectInst *SI, bool isTrue,
5913 const SmallPtrSet<const Instruction *, 2> &Selects) {
5914 Value *V;
5915
5916 for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI);
5917 DefSI = dyn_cast<SelectInst>(V)) {
Dehao Chenc32d7122016-09-12 20:29:54 +00005918 assert(DefSI->getCondition() == SI->getCondition() &&
Dehao Chen9bbb9412016-09-12 20:23:28 +00005919 "The condition of DefSI does not match with SI");
5920 V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
5921 }
5922 return V;
5923}
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005924
Nadav Rotem9d832022012-09-02 12:10:19 +00005925/// If we have a SelectInst that will likely profit from branch prediction,
5926/// turn it into a branch.
Teresa Johnsonb7e21382019-03-27 18:44:25 +00005927bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
Vedant Kumarfbc38732018-08-21 23:42:23 +00005928 // If branch conversion isn't desirable, exit early.
5929 if (DisableSelectToBranch || OptSize || !TLI)
5930 return false;
5931
Dehao Chen9bbb9412016-09-12 20:23:28 +00005932 // Find all consecutive select instructions that share the same condition.
5933 SmallVector<SelectInst *, 2> ASI;
5934 ASI.push_back(SI);
David Blaikie7d306532018-08-28 00:55:19 +00005935 for (BasicBlock::iterator It = ++BasicBlock::iterator(SI);
5936 It != SI->getParent()->end(); ++It) {
5937 SelectInst *I = dyn_cast<SelectInst>(&*It);
Dehao Chen9bbb9412016-09-12 20:23:28 +00005938 if (I && SI->getCondition() == I->getCondition()) {
5939 ASI.push_back(I);
5940 } else {
5941 break;
5942 }
5943 }
5944
5945 SelectInst *LastSI = ASI.back();
5946 // Increment the current iterator to skip all the rest of select instructions
5947 // because they will be either "not lowered" or "all lowered" to branch.
5948 CurInstIterator = std::next(LastSI->getIterator());
5949
Nadav Rotem9d832022012-09-02 12:10:19 +00005950 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
5951
5952 // Can we convert the 'select' to CF ?
Vedant Kumarfbc38732018-08-21 23:42:23 +00005953 if (VectorCond || SI->getMetadata(LLVMContext::MD_unpredictable))
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005954 return false;
5955
Nadav Rotem9d832022012-09-02 12:10:19 +00005956 TargetLowering::SelectSupportKind SelectKind;
5957 if (VectorCond)
5958 SelectKind = TargetLowering::VectorMaskSelect;
5959 else if (SI->getType()->isVectorTy())
5960 SelectKind = TargetLowering::ScalarCondVectorVal;
5961 else
5962 SelectKind = TargetLowering::ScalarValSelect;
5963
Sanjay Pateld66607b2016-04-26 17:11:17 +00005964 if (TLI->isSelectSupported(SelectKind) &&
5965 !isFormingBranchFromSelectProfitable(TTI, TLI, SI))
5966 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005967
Teresa Johnsonb7e21382019-03-27 18:44:25 +00005968 // The DominatorTree needs to be rebuilt by any consumers after this
5969 // transformation. We simply reset here rather than setting the ModifiedDT
5970 // flag to avoid restarting the function walk in runOnFunction for each
5971 // select optimized.
5972 DT.reset();
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005973
Sanjay Patel69a50a12015-10-19 21:59:12 +00005974 // Transform a sequence like this:
5975 // start:
5976 // %cmp = cmp uge i32 %a, %b
5977 // %sel = select i1 %cmp, i32 %c, i32 %d
5978 //
5979 // Into:
5980 // start:
5981 // %cmp = cmp uge i32 %a, %b
5982 // br i1 %cmp, label %select.true, label %select.false
5983 // select.true:
5984 // br label %select.end
5985 // select.false:
5986 // br label %select.end
5987 // select.end:
5988 // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
5989 //
5990 // In addition, we may sink instructions that produce %c or %d from
5991 // the entry block into the destination(s) of the new branch.
5992 // If the true or false blocks do not contain a sunken instruction, that
5993 // block and its branch may be optimized away. In that case, one side of the
5994 // first branch will point directly to select.end, and the corresponding PHI
5995 // predecessor block will be the start block.
5996
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005997 // First, we split the block containing the select into 2 blocks.
5998 BasicBlock *StartBlock = SI->getParent();
Dehao Chen9bbb9412016-09-12 20:23:28 +00005999 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI));
Sanjay Patel69a50a12015-10-19 21:59:12 +00006000 BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00006001
Sanjay Patel69a50a12015-10-19 21:59:12 +00006002 // Delete the unconditional branch that was just created by the split.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00006003 StartBlock->getTerminator()->eraseFromParent();
Sanjay Patel69a50a12015-10-19 21:59:12 +00006004
6005 // These are the new basic blocks for the conditional branch.
6006 // At least one will become an actual new basic block.
6007 BasicBlock *TrueBlock = nullptr;
6008 BasicBlock *FalseBlock = nullptr;
Dehao Chen9bbb9412016-09-12 20:23:28 +00006009 BranchInst *TrueBranch = nullptr;
6010 BranchInst *FalseBranch = nullptr;
Sanjay Patel69a50a12015-10-19 21:59:12 +00006011
6012 // Sink expensive instructions into the conditional blocks to avoid executing
6013 // them speculatively.
Dehao Chen9bbb9412016-09-12 20:23:28 +00006014 for (SelectInst *SI : ASI) {
6015 if (sinkSelectOperand(TTI, SI->getTrueValue())) {
6016 if (TrueBlock == nullptr) {
6017 TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink",
6018 EndBlock->getParent(), EndBlock);
6019 TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
Vedant Kumar1e8a2c92018-08-22 00:10:37 +00006020 TrueBranch->setDebugLoc(SI->getDebugLoc());
Dehao Chen9bbb9412016-09-12 20:23:28 +00006021 }
6022 auto *TrueInst = cast<Instruction>(SI->getTrueValue());
6023 TrueInst->moveBefore(TrueBranch);
6024 }
6025 if (sinkSelectOperand(TTI, SI->getFalseValue())) {
6026 if (FalseBlock == nullptr) {
6027 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink",
6028 EndBlock->getParent(), EndBlock);
6029 FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
Vedant Kumar1e8a2c92018-08-22 00:10:37 +00006030 FalseBranch->setDebugLoc(SI->getDebugLoc());
Dehao Chen9bbb9412016-09-12 20:23:28 +00006031 }
6032 auto *FalseInst = cast<Instruction>(SI->getFalseValue());
6033 FalseInst->moveBefore(FalseBranch);
6034 }
Sanjay Patel69a50a12015-10-19 21:59:12 +00006035 }
6036
6037 // If there was nothing to sink, then arbitrarily choose the 'false' side
6038 // for a new input value to the PHI.
6039 if (TrueBlock == FalseBlock) {
6040 assert(TrueBlock == nullptr &&
6041 "Unexpected basic block transform while optimizing select");
6042
6043 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
6044 EndBlock->getParent(), EndBlock);
Vedant Kumar1e8a2c92018-08-22 00:10:37 +00006045 auto *FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
6046 FalseBranch->setDebugLoc(SI->getDebugLoc());
Sanjay Patel69a50a12015-10-19 21:59:12 +00006047 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00006048
6049 // Insert the real conditional branch based on the original condition.
Sanjay Patel69a50a12015-10-19 21:59:12 +00006050 // If we did not create a new block for one of the 'true' or 'false' paths
6051 // of the condition, it means that side of the branch goes to the end block
6052 // directly and the path originates from the start block from the point of
6053 // view of the new PHI.
Xinliang David Li241e6c72016-09-03 21:26:36 +00006054 BasicBlock *TT, *FT;
Sanjay Patel69a50a12015-10-19 21:59:12 +00006055 if (TrueBlock == nullptr) {
Xinliang David Li241e6c72016-09-03 21:26:36 +00006056 TT = EndBlock;
6057 FT = FalseBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00006058 TrueBlock = StartBlock;
6059 } else if (FalseBlock == nullptr) {
Xinliang David Li241e6c72016-09-03 21:26:36 +00006060 TT = TrueBlock;
6061 FT = EndBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00006062 FalseBlock = StartBlock;
6063 } else {
Xinliang David Li241e6c72016-09-03 21:26:36 +00006064 TT = TrueBlock;
6065 FT = FalseBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00006066 }
Xinliang David Li241e6c72016-09-03 21:26:36 +00006067 IRBuilder<>(SI).CreateCondBr(SI->getCondition(), TT, FT, SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00006068
Dehao Chen9bbb9412016-09-12 20:23:28 +00006069 SmallPtrSet<const Instruction *, 2> INS;
6070 INS.insert(ASI.begin(), ASI.end());
6071 // Use reverse iterator because later select may use the value of the
6072 // earlier select, and we need to propagate value through earlier select
6073 // to get the PHI operand.
6074 for (auto It = ASI.rbegin(); It != ASI.rend(); ++It) {
6075 SelectInst *SI = *It;
6076 // The select itself is replaced with a PHI Node.
6077 PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
6078 PN->takeName(SI);
6079 PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock);
6080 PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock);
Vedant Kumar1e8a2c92018-08-22 00:10:37 +00006081 PN->setDebugLoc(SI->getDebugLoc());
Sanjay Patel69a50a12015-10-19 21:59:12 +00006082
Dehao Chen9bbb9412016-09-12 20:23:28 +00006083 SI->replaceAllUsesWith(PN);
6084 SI->eraseFromParent();
6085 INS.erase(SI);
6086 ++NumSelectsExpanded;
6087 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00006088
6089 // Instruct OptimizeBlock to skip to the next block.
6090 CurInstIterator = StartBlock->end();
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00006091 return true;
6092}
6093
Benjamin Kramer573ff362014-03-01 17:24:40 +00006094static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00006095 SmallVector<int, 16> Mask(SVI->getShuffleMask());
6096 int SplatElem = -1;
6097 for (unsigned i = 0; i < Mask.size(); ++i) {
6098 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
6099 return false;
6100 SplatElem = Mask[i];
6101 }
6102
6103 return true;
6104}
6105
6106/// Some targets have expensive vector shifts if the lanes aren't all the same
6107/// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
6108/// it's often worth sinking a shufflevector splat down to its use so that
6109/// codegen can spot all lanes are identical.
Sanjay Patelfc580a62015-09-21 23:03:16 +00006110bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00006111 BasicBlock *DefBB = SVI->getParent();
6112
6113 // Only do this xform if variable vector shifts are particularly expensive.
6114 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
6115 return false;
6116
6117 // We only expect better codegen by sinking a shuffle if we can recognise a
6118 // constant splat.
6119 if (!isBroadcastShuffle(SVI))
6120 return false;
6121
6122 // InsertedShuffles - Only insert a shuffle in each block once.
6123 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
6124
6125 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00006126 for (User *U : SVI->users()) {
6127 Instruction *UI = cast<Instruction>(U);
Tim Northoveraeb8e062014-02-19 10:02:43 +00006128
6129 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00006130 BasicBlock *UserBB = UI->getParent();
Tim Northoveraeb8e062014-02-19 10:02:43 +00006131 if (UserBB == DefBB) continue;
6132
6133 // For now only apply this when the splat is used by a shift instruction.
Chandler Carruthcdf47882014-03-09 03:16:01 +00006134 if (!UI->isShift()) continue;
Tim Northoveraeb8e062014-02-19 10:02:43 +00006135
6136 // Everything checks out, sink the shuffle if the user's block doesn't
6137 // already have a copy.
6138 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
6139
6140 if (!InsertedShuffle) {
6141 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00006142 assert(InsertPt != UserBB->end());
6143 InsertedShuffle =
6144 new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
6145 SVI->getOperand(2), "", &*InsertPt);
Tim Northoveraeb8e062014-02-19 10:02:43 +00006146 }
6147
Chandler Carruthcdf47882014-03-09 03:16:01 +00006148 UI->replaceUsesOfWith(SVI, InsertedShuffle);
Tim Northoveraeb8e062014-02-19 10:02:43 +00006149 MadeChange = true;
6150 }
6151
6152 // If we removed all uses, nuke the shuffle.
6153 if (SVI->use_empty()) {
6154 SVI->eraseFromParent();
6155 MadeChange = true;
6156 }
6157
6158 return MadeChange;
6159}
6160
Florian Hahn3b251962019-02-05 10:27:40 +00006161bool CodeGenPrepare::tryToSinkFreeOperands(Instruction *I) {
6162 // If the operands of I can be folded into a target instruction together with
6163 // I, duplicate and sink them.
6164 SmallVector<Use *, 4> OpsToSink;
6165 if (!TLI || !TLI->shouldSinkOperands(I, OpsToSink))
6166 return false;
6167
6168 // OpsToSink can contain multiple uses in a use chain (e.g.
6169 // (%u1 with %u1 = shufflevector), (%u2 with %u2 = zext %u1)). The dominating
6170 // uses must come first, which means they are sunk first, temporarily creating
6171 // invalid IR. This will be fixed once their dominated users are sunk and
6172 // updated.
6173 BasicBlock *TargetBB = I->getParent();
6174 bool Changed = false;
6175 SmallVector<Use *, 4> ToReplace;
6176 for (Use *U : OpsToSink) {
6177 auto *UI = cast<Instruction>(U->get());
6178 if (UI->getParent() == TargetBB || isa<PHINode>(UI))
6179 continue;
6180 ToReplace.push_back(U);
6181 }
6182
6183 SmallPtrSet<Instruction *, 4> MaybeDead;
6184 for (Use *U : ToReplace) {
6185 auto *UI = cast<Instruction>(U->get());
6186 Instruction *NI = UI->clone();
6187 MaybeDead.insert(UI);
6188 LLVM_DEBUG(dbgs() << "Sinking " << *UI << " to user " << *I << "\n");
6189 NI->insertBefore(I);
6190 InsertedInsts.insert(NI);
6191 U->set(NI);
6192 Changed = true;
6193 }
6194
6195 // Remove instructions that are dead after sinking.
6196 for (auto *I : MaybeDead)
6197 if (!I->hasNUsesOrMore(1))
6198 I->eraseFromParent();
6199
6200 return Changed;
6201}
6202
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00006203bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
6204 if (!TLI || !DL)
6205 return false;
6206
6207 Value *Cond = SI->getCondition();
6208 Type *OldType = Cond->getType();
6209 LLVMContext &Context = Cond->getContext();
6210 MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType));
6211 unsigned RegWidth = RegType.getSizeInBits();
6212
6213 if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
6214 return false;
6215
6216 // If the register width is greater than the type width, expand the condition
6217 // of the switch instruction and each case constant to the width of the
6218 // register. By widening the type of the switch condition, subsequent
6219 // comparisons (for case comparisons) will not need to be extended to the
6220 // preferred register width, so we will potentially eliminate N-1 extends,
6221 // where N is the number of cases in the switch.
6222 auto *NewType = Type::getIntNTy(Context, RegWidth);
6223
6224 // Zero-extend the switch condition and case constants unless the switch
6225 // condition is a function argument that is already being sign-extended.
6226 // In that case, we can avoid an unnecessary mask/extension by sign-extending
6227 // everything instead.
6228 Instruction::CastOps ExtType = Instruction::ZExt;
6229 if (auto *Arg = dyn_cast<Argument>(Cond))
6230 if (Arg->hasSExtAttr())
6231 ExtType = Instruction::SExt;
6232
6233 auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
6234 ExtInst->insertBefore(SI);
Vedant Kumar47606862018-08-22 01:23:31 +00006235 ExtInst->setDebugLoc(SI->getDebugLoc());
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00006236 SI->setCondition(ExtInst);
Chandler Carruth927d8e62017-04-12 07:27:28 +00006237 for (auto Case : SI->cases()) {
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00006238 APInt NarrowConst = Case.getCaseValue()->getValue();
6239 APInt WideConst = (ExtType == Instruction::ZExt) ?
6240 NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth);
6241 Case.setValue(ConstantInt::get(Context, WideConst));
6242 }
6243
6244 return true;
6245}
6246
Zaara Syeda3a7578c2017-05-31 17:12:38 +00006247
Quentin Colombetc32615d2014-10-31 17:52:53 +00006248namespace {
Eugene Zelenko900b6332017-08-29 22:32:07 +00006249
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006250/// Helper class to promote a scalar operation to a vector one.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006251/// This class is used to move downward extractelement transition.
6252/// E.g.,
6253/// a = vector_op <2 x i32>
6254/// b = extractelement <2 x i32> a, i32 0
6255/// c = scalar_op b
6256/// store c
6257///
6258/// =>
6259/// a = vector_op <2 x i32>
6260/// c = vector_op a (equivalent to scalar_op on the related lane)
6261/// * d = extractelement <2 x i32> c, i32 0
6262/// * store d
6263/// Assuming both extractelement and store can be combine, we get rid of the
6264/// transition.
6265class VectorPromoteHelper {
Mehdi Amini44ede332015-07-09 02:09:04 +00006266 /// DataLayout associated with the current module.
6267 const DataLayout &DL;
6268
Quentin Colombetc32615d2014-10-31 17:52:53 +00006269 /// Used to perform some checks on the legality of vector operations.
6270 const TargetLowering &TLI;
6271
6272 /// Used to estimated the cost of the promoted chain.
6273 const TargetTransformInfo &TTI;
6274
6275 /// The transition being moved downwards.
6276 Instruction *Transition;
Eugene Zelenko900b6332017-08-29 22:32:07 +00006277
Quentin Colombetc32615d2014-10-31 17:52:53 +00006278 /// The sequence of instructions to be promoted.
6279 SmallVector<Instruction *, 4> InstsToBePromoted;
Eugene Zelenko900b6332017-08-29 22:32:07 +00006280
Quentin Colombetc32615d2014-10-31 17:52:53 +00006281 /// Cost of combining a store and an extract.
6282 unsigned StoreExtractCombineCost;
Eugene Zelenko900b6332017-08-29 22:32:07 +00006283
Quentin Colombetc32615d2014-10-31 17:52:53 +00006284 /// Instruction that will be combined with the transition.
Eugene Zelenko900b6332017-08-29 22:32:07 +00006285 Instruction *CombineInst = nullptr;
Quentin Colombetc32615d2014-10-31 17:52:53 +00006286
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006287 /// The instruction that represents the current end of the transition.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006288 /// Since we are faking the promotion until we reach the end of the chain
6289 /// of computation, we need a way to get the current end of the transition.
6290 Instruction *getEndOfTransition() const {
6291 if (InstsToBePromoted.empty())
6292 return Transition;
6293 return InstsToBePromoted.back();
6294 }
6295
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006296 /// Return the index of the original value in the transition.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006297 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
6298 /// c, is at index 0.
6299 unsigned getTransitionOriginalValueIdx() const {
6300 assert(isa<ExtractElementInst>(Transition) &&
6301 "Other kind of transitions are not supported yet");
6302 return 0;
6303 }
6304
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006305 /// Return the index of the index in the transition.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006306 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
6307 /// is at index 1.
6308 unsigned getTransitionIdx() const {
6309 assert(isa<ExtractElementInst>(Transition) &&
6310 "Other kind of transitions are not supported yet");
6311 return 1;
6312 }
6313
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006314 /// Get the type of the transition.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006315 /// This is the type of the original value.
6316 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
6317 /// transition is <2 x i32>.
6318 Type *getTransitionType() const {
6319 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
6320 }
6321
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006322 /// Promote \p ToBePromoted by moving \p Def downward through.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006323 /// I.e., we have the following sequence:
6324 /// Def = Transition <ty1> a to <ty2>
6325 /// b = ToBePromoted <ty2> Def, ...
6326 /// =>
6327 /// b = ToBePromoted <ty1> a, ...
6328 /// Def = Transition <ty1> ToBePromoted to <ty2>
6329 void promoteImpl(Instruction *ToBePromoted);
6330
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006331 /// Check whether or not it is profitable to promote all the
Quentin Colombetc32615d2014-10-31 17:52:53 +00006332 /// instructions enqueued to be promoted.
6333 bool isProfitableToPromote() {
6334 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
6335 unsigned Index = isa<ConstantInt>(ValIdx)
6336 ? cast<ConstantInt>(ValIdx)->getZExtValue()
6337 : -1;
6338 Type *PromotedType = getTransitionType();
6339
6340 StoreInst *ST = cast<StoreInst>(CombineInst);
6341 unsigned AS = ST->getPointerAddressSpace();
6342 unsigned Align = ST->getAlignment();
6343 // Check if this store is supported.
6344 if (!TLI.allowsMisalignedMemoryAccesses(
Mehdi Amini44ede332015-07-09 02:09:04 +00006345 TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
6346 Align)) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00006347 // If this is not supported, there is no way we can combine
6348 // the extract with the store.
6349 return false;
6350 }
6351
6352 // The scalar chain of computation has to pay for the transition
6353 // scalar to vector.
6354 // The vector chain has to account for the combining cost.
6355 uint64_t ScalarCost =
6356 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
6357 uint64_t VectorCost = StoreExtractCombineCost;
6358 for (const auto &Inst : InstsToBePromoted) {
6359 // Compute the cost.
6360 // By construction, all instructions being promoted are arithmetic ones.
6361 // Moreover, one argument is a constant that can be viewed as a splat
6362 // constant.
6363 Value *Arg0 = Inst->getOperand(0);
6364 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
6365 isa<ConstantFP>(Arg0);
6366 TargetTransformInfo::OperandValueKind Arg0OVK =
6367 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
6368 : TargetTransformInfo::OK_AnyValue;
6369 TargetTransformInfo::OperandValueKind Arg1OVK =
6370 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
6371 : TargetTransformInfo::OK_AnyValue;
6372 ScalarCost += TTI.getArithmeticInstrCost(
6373 Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
6374 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
6375 Arg0OVK, Arg1OVK);
6376 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006377 LLVM_DEBUG(
6378 dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
6379 << ScalarCost << "\nVector: " << VectorCost << '\n');
Quentin Colombetc32615d2014-10-31 17:52:53 +00006380 return ScalarCost > VectorCost;
6381 }
6382
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006383 /// Generate a constant vector with \p Val with the same
Quentin Colombetc32615d2014-10-31 17:52:53 +00006384 /// number of elements as the transition.
6385 /// \p UseSplat defines whether or not \p Val should be replicated
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00006386 /// across the whole vector.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006387 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
6388 /// otherwise we generate a vector with as many undef as possible:
6389 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
6390 /// used at the index of the extract.
6391 Value *getConstantVector(Constant *Val, bool UseSplat) const {
Eugene Zelenko900b6332017-08-29 22:32:07 +00006392 unsigned ExtractIdx = std::numeric_limits<unsigned>::max();
Quentin Colombetc32615d2014-10-31 17:52:53 +00006393 if (!UseSplat) {
6394 // If we cannot determine where the constant must be, we have to
6395 // use a splat constant.
6396 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
6397 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
6398 ExtractIdx = CstVal->getSExtValue();
6399 else
6400 UseSplat = true;
6401 }
6402
6403 unsigned End = getTransitionType()->getVectorNumElements();
6404 if (UseSplat)
6405 return ConstantVector::getSplat(End, Val);
6406
6407 SmallVector<Constant *, 4> ConstVec;
6408 UndefValue *UndefVal = UndefValue::get(Val->getType());
6409 for (unsigned Idx = 0; Idx != End; ++Idx) {
6410 if (Idx == ExtractIdx)
6411 ConstVec.push_back(Val);
6412 else
6413 ConstVec.push_back(UndefVal);
6414 }
6415 return ConstantVector::get(ConstVec);
6416 }
6417
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006418 /// Check if promoting to a vector type an operand at \p OperandIdx
Quentin Colombetc32615d2014-10-31 17:52:53 +00006419 /// in \p Use can trigger undefined behavior.
6420 static bool canCauseUndefinedBehavior(const Instruction *Use,
6421 unsigned OperandIdx) {
6422 // This is not safe to introduce undef when the operand is on
6423 // the right hand side of a division-like instruction.
6424 if (OperandIdx != 1)
6425 return false;
6426 switch (Use->getOpcode()) {
6427 default:
6428 return false;
6429 case Instruction::SDiv:
6430 case Instruction::UDiv:
6431 case Instruction::SRem:
6432 case Instruction::URem:
6433 return true;
6434 case Instruction::FDiv:
6435 case Instruction::FRem:
6436 return !Use->hasNoNaNs();
6437 }
6438 llvm_unreachable(nullptr);
6439 }
6440
6441public:
Mehdi Amini44ede332015-07-09 02:09:04 +00006442 VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
6443 const TargetTransformInfo &TTI, Instruction *Transition,
6444 unsigned CombineCost)
6445 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
Eugene Zelenko900b6332017-08-29 22:32:07 +00006446 StoreExtractCombineCost(CombineCost) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00006447 assert(Transition && "Do not know how to promote null");
6448 }
6449
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006450 /// Check if we can promote \p ToBePromoted to \p Type.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006451 bool canPromote(const Instruction *ToBePromoted) const {
6452 // We could support CastInst too.
6453 return isa<BinaryOperator>(ToBePromoted);
6454 }
6455
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006456 /// Check if it is profitable to promote \p ToBePromoted
Quentin Colombetc32615d2014-10-31 17:52:53 +00006457 /// by moving downward the transition through.
6458 bool shouldPromote(const Instruction *ToBePromoted) const {
6459 // Promote only if all the operands can be statically expanded.
6460 // Indeed, we do not want to introduce any new kind of transitions.
6461 for (const Use &U : ToBePromoted->operands()) {
6462 const Value *Val = U.get();
6463 if (Val == getEndOfTransition()) {
6464 // If the use is a division and the transition is on the rhs,
6465 // we cannot promote the operation, otherwise we may create a
6466 // division by zero.
6467 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
6468 return false;
6469 continue;
6470 }
6471 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
6472 !isa<ConstantFP>(Val))
6473 return false;
6474 }
6475 // Check that the resulting operation is legal.
6476 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
6477 if (!ISDOpcode)
6478 return false;
6479 return StressStoreExtract ||
Ahmed Bougacha026600d2014-11-12 23:05:03 +00006480 TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00006481 ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
Quentin Colombetc32615d2014-10-31 17:52:53 +00006482 }
6483
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006484 /// Check whether or not \p Use can be combined
Quentin Colombetc32615d2014-10-31 17:52:53 +00006485 /// with the transition.
6486 /// I.e., is it possible to do Use(Transition) => AnotherUse?
6487 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
6488
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006489 /// Record \p ToBePromoted as part of the chain to be promoted.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006490 void enqueueForPromotion(Instruction *ToBePromoted) {
6491 InstsToBePromoted.push_back(ToBePromoted);
6492 }
6493
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006494 /// Set the instruction that will be combined with the transition.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006495 void recordCombineInstruction(Instruction *ToBeCombined) {
6496 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
6497 CombineInst = ToBeCombined;
6498 }
6499
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006500 /// Promote all the instructions enqueued for promotion if it is
Quentin Colombetc32615d2014-10-31 17:52:53 +00006501 /// is profitable.
6502 /// \return True if the promotion happened, false otherwise.
6503 bool promote() {
6504 // Check if there is something to promote.
6505 // Right now, if we do not have anything to combine with,
6506 // we assume the promotion is not profitable.
6507 if (InstsToBePromoted.empty() || !CombineInst)
6508 return false;
6509
6510 // Check cost.
6511 if (!StressStoreExtract && !isProfitableToPromote())
6512 return false;
6513
6514 // Promote.
6515 for (auto &ToBePromoted : InstsToBePromoted)
6516 promoteImpl(ToBePromoted);
6517 InstsToBePromoted.clear();
6518 return true;
6519 }
6520};
Eugene Zelenko900b6332017-08-29 22:32:07 +00006521
6522} // end anonymous namespace
Quentin Colombetc32615d2014-10-31 17:52:53 +00006523
6524void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
6525 // At this point, we know that all the operands of ToBePromoted but Def
6526 // can be statically promoted.
6527 // For Def, we need to use its parameter in ToBePromoted:
6528 // b = ToBePromoted ty1 a
6529 // Def = Transition ty1 b to ty2
6530 // Move the transition down.
6531 // 1. Replace all uses of the promoted operation by the transition.
6532 // = ... b => = ... Def.
6533 assert(ToBePromoted->getType() == Transition->getType() &&
6534 "The type of the result of the transition does not match "
6535 "the final type");
6536 ToBePromoted->replaceAllUsesWith(Transition);
6537 // 2. Update the type of the uses.
6538 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
6539 Type *TransitionTy = getTransitionType();
6540 ToBePromoted->mutateType(TransitionTy);
6541 // 3. Update all the operands of the promoted operation with promoted
6542 // operands.
6543 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
6544 for (Use &U : ToBePromoted->operands()) {
6545 Value *Val = U.get();
6546 Value *NewVal = nullptr;
6547 if (Val == Transition)
6548 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
6549 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
6550 isa<ConstantFP>(Val)) {
6551 // Use a splat constant if it is not safe to use undef.
6552 NewVal = getConstantVector(
6553 cast<Constant>(Val),
6554 isa<UndefValue>(Val) ||
6555 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
6556 } else
Craig Topperd3c02f12015-01-05 10:15:49 +00006557 llvm_unreachable("Did you modified shouldPromote and forgot to update "
6558 "this?");
Quentin Colombetc32615d2014-10-31 17:52:53 +00006559 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
6560 }
Sanjay Patel674d2c22017-08-29 14:07:48 +00006561 Transition->moveAfter(ToBePromoted);
Quentin Colombetc32615d2014-10-31 17:52:53 +00006562 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
6563}
6564
6565/// Some targets can do store(extractelement) with one instruction.
6566/// Try to push the extractelement towards the stores when the target
6567/// has this feature and this is profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00006568bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00006569 unsigned CombineCost = std::numeric_limits<unsigned>::max();
Quentin Colombetc32615d2014-10-31 17:52:53 +00006570 if (DisableStoreExtract || !TLI ||
6571 (!StressStoreExtract &&
6572 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
6573 Inst->getOperand(1), CombineCost)))
6574 return false;
6575
6576 // At this point we know that Inst is a vector to scalar transition.
6577 // Try to move it down the def-use chain, until:
6578 // - We can combine the transition with its single use
6579 // => we got rid of the transition.
6580 // - We escape the current basic block
6581 // => we would need to check that we are moving it at a cheaper place and
6582 // we do not do that for now.
6583 BasicBlock *Parent = Inst->getParent();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006584 LLVM_DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
Mehdi Amini44ede332015-07-09 02:09:04 +00006585 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
Quentin Colombetc32615d2014-10-31 17:52:53 +00006586 // If the transition has more than one use, assume this is not going to be
6587 // beneficial.
6588 while (Inst->hasOneUse()) {
6589 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006590 LLVM_DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
Quentin Colombetc32615d2014-10-31 17:52:53 +00006591
6592 if (ToBePromoted->getParent() != Parent) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006593 LLVM_DEBUG(dbgs() << "Instruction to promote is in a different block ("
6594 << ToBePromoted->getParent()->getName()
6595 << ") than the transition (" << Parent->getName()
6596 << ").\n");
Quentin Colombetc32615d2014-10-31 17:52:53 +00006597 return false;
6598 }
6599
6600 if (VPH.canCombine(ToBePromoted)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006601 LLVM_DEBUG(dbgs() << "Assume " << *Inst << '\n'
6602 << "will be combined with: " << *ToBePromoted << '\n');
Quentin Colombetc32615d2014-10-31 17:52:53 +00006603 VPH.recordCombineInstruction(ToBePromoted);
6604 bool Changed = VPH.promote();
6605 NumStoreExtractExposed += Changed;
6606 return Changed;
6607 }
6608
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006609 LLVM_DEBUG(dbgs() << "Try promoting.\n");
Quentin Colombetc32615d2014-10-31 17:52:53 +00006610 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
6611 return false;
6612
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006613 LLVM_DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
Quentin Colombetc32615d2014-10-31 17:52:53 +00006614
6615 VPH.enqueueForPromotion(ToBePromoted);
6616 Inst = ToBePromoted;
6617 }
6618 return false;
6619}
6620
Wei Mia2f0b592016-12-22 19:44:45 +00006621/// For the instruction sequence of store below, F and I values
6622/// are bundled together as an i64 value before being stored into memory.
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00006623/// Sometimes it is more efficient to generate separate stores for F and I,
Wei Mia2f0b592016-12-22 19:44:45 +00006624/// which can remove the bitwise instructions or sink them to colder places.
6625///
6626/// (store (or (zext (bitcast F to i32) to i64),
6627/// (shl (zext I to i64), 32)), addr) -->
6628/// (store F, addr) and (store I, addr+4)
6629///
6630/// Similarly, splitting for other merged store can also be beneficial, like:
6631/// For pair of {i32, i32}, i64 store --> two i32 stores.
6632/// For pair of {i32, i16}, i64 store --> two i32 stores.
6633/// For pair of {i16, i16}, i32 store --> two i16 stores.
6634/// For pair of {i16, i8}, i32 store --> two i16 stores.
6635/// For pair of {i8, i8}, i16 store --> two i8 stores.
6636///
6637/// We allow each target to determine specifically which kind of splitting is
6638/// supported.
6639///
6640/// The store patterns are commonly seen from the simple code snippet below
6641/// if only std::make_pair(...) is sroa transformed before inlined into hoo.
6642/// void goo(const std::pair<int, float> &);
6643/// hoo() {
6644/// ...
6645/// goo(std::make_pair(tmp, ftmp));
6646/// ...
6647/// }
6648///
6649/// Although we already have similar splitting in DAG Combine, we duplicate
6650/// it in CodeGenPrepare to catch the case in which pattern is across
6651/// multiple BBs. The logic in DAG Combine is kept to catch case generated
6652/// during code expansion.
6653static bool splitMergedValStore(StoreInst &SI, const DataLayout &DL,
6654 const TargetLowering &TLI) {
6655 // Handle simple but common cases only.
6656 Type *StoreType = SI.getValueOperand()->getType();
6657 if (DL.getTypeStoreSizeInBits(StoreType) != DL.getTypeSizeInBits(StoreType) ||
6658 DL.getTypeSizeInBits(StoreType) == 0)
6659 return false;
6660
6661 unsigned HalfValBitSize = DL.getTypeSizeInBits(StoreType) / 2;
6662 Type *SplitStoreType = Type::getIntNTy(SI.getContext(), HalfValBitSize);
6663 if (DL.getTypeStoreSizeInBits(SplitStoreType) !=
6664 DL.getTypeSizeInBits(SplitStoreType))
6665 return false;
6666
6667 // Match the following patterns:
6668 // (store (or (zext LValue to i64),
6669 // (shl (zext HValue to i64), 32)), HalfValBitSize)
6670 // or
6671 // (store (or (shl (zext HValue to i64), 32)), HalfValBitSize)
6672 // (zext LValue to i64),
6673 // Expect both operands of OR and the first operand of SHL have only
6674 // one use.
6675 Value *LValue, *HValue;
6676 if (!match(SI.getValueOperand(),
6677 m_c_Or(m_OneUse(m_ZExt(m_Value(LValue))),
6678 m_OneUse(m_Shl(m_OneUse(m_ZExt(m_Value(HValue))),
6679 m_SpecificInt(HalfValBitSize))))))
6680 return false;
6681
6682 // Check LValue and HValue are int with size less or equal than 32.
6683 if (!LValue->getType()->isIntegerTy() ||
6684 DL.getTypeSizeInBits(LValue->getType()) > HalfValBitSize ||
6685 !HValue->getType()->isIntegerTy() ||
6686 DL.getTypeSizeInBits(HValue->getType()) > HalfValBitSize)
6687 return false;
6688
6689 // If LValue/HValue is a bitcast instruction, use the EVT before bitcast
6690 // as the input of target query.
6691 auto *LBC = dyn_cast<BitCastInst>(LValue);
6692 auto *HBC = dyn_cast<BitCastInst>(HValue);
6693 EVT LowTy = LBC ? EVT::getEVT(LBC->getOperand(0)->getType())
6694 : EVT::getEVT(LValue->getType());
6695 EVT HighTy = HBC ? EVT::getEVT(HBC->getOperand(0)->getType())
6696 : EVT::getEVT(HValue->getType());
6697 if (!ForceSplitStore && !TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
6698 return false;
6699
6700 // Start to split store.
6701 IRBuilder<> Builder(SI.getContext());
6702 Builder.SetInsertPoint(&SI);
6703
6704 // If LValue/HValue is a bitcast in another BB, create a new one in current
6705 // BB so it may be merged with the splitted stores by dag combiner.
6706 if (LBC && LBC->getParent() != SI.getParent())
6707 LValue = Builder.CreateBitCast(LBC->getOperand(0), LBC->getType());
6708 if (HBC && HBC->getParent() != SI.getParent())
6709 HValue = Builder.CreateBitCast(HBC->getOperand(0), HBC->getType());
6710
Jonas Paulsson5612bb22018-03-13 08:36:20 +00006711 bool IsLE = SI.getModule()->getDataLayout().isLittleEndian();
Wei Mia2f0b592016-12-22 19:44:45 +00006712 auto CreateSplitStore = [&](Value *V, bool Upper) {
6713 V = Builder.CreateZExtOrBitCast(V, SplitStoreType);
6714 Value *Addr = Builder.CreateBitCast(
6715 SI.getOperand(1),
6716 SplitStoreType->getPointerTo(SI.getPointerAddressSpace()));
Jonas Paulsson5612bb22018-03-13 08:36:20 +00006717 if ((IsLE && Upper) || (!IsLE && !Upper))
Wei Mia2f0b592016-12-22 19:44:45 +00006718 Addr = Builder.CreateGEP(
6719 SplitStoreType, Addr,
6720 ConstantInt::get(Type::getInt32Ty(SI.getContext()), 1));
6721 Builder.CreateAlignedStore(
6722 V, Addr, Upper ? SI.getAlignment() / 2 : SI.getAlignment());
6723 };
6724
6725 CreateSplitStore(LValue, false);
6726 CreateSplitStore(HValue, true);
6727
6728 // Delete the old store.
6729 SI.eraseFromParent();
6730 return true;
6731}
6732
Hiroshi Yamauchi93644322017-09-11 17:52:08 +00006733// Return true if the GEP has two operands, the first operand is of a sequential
6734// type, and the second operand is a constant.
6735static bool GEPSequentialConstIndexed(GetElementPtrInst *GEP) {
6736 gep_type_iterator I = gep_type_begin(*GEP);
6737 return GEP->getNumOperands() == 2 &&
6738 I.isSequential() &&
6739 isa<ConstantInt>(GEP->getOperand(1));
6740}
6741
6742// Try unmerging GEPs to reduce liveness interference (register pressure) across
6743// IndirectBr edges. Since IndirectBr edges tend to touch on many blocks,
6744// reducing liveness interference across those edges benefits global register
6745// allocation. Currently handles only certain cases.
6746//
6747// For example, unmerge %GEPI and %UGEPI as below.
6748//
6749// ---------- BEFORE ----------
6750// SrcBlock:
6751// ...
6752// %GEPIOp = ...
6753// ...
6754// %GEPI = gep %GEPIOp, Idx
6755// ...
6756// indirectbr ... [ label %DstB0, label %DstB1, ... label %DstBi ... ]
6757// (* %GEPI is alive on the indirectbr edges due to other uses ahead)
6758// (* %GEPIOp is alive on the indirectbr edges only because of it's used by
6759// %UGEPI)
6760//
6761// DstB0: ... (there may be a gep similar to %UGEPI to be unmerged)
6762// DstB1: ... (there may be a gep similar to %UGEPI to be unmerged)
6763// ...
6764//
6765// DstBi:
6766// ...
6767// %UGEPI = gep %GEPIOp, UIdx
6768// ...
6769// ---------------------------
6770//
6771// ---------- AFTER ----------
6772// SrcBlock:
6773// ... (same as above)
6774// (* %GEPI is still alive on the indirectbr edges)
6775// (* %GEPIOp is no longer alive on the indirectbr edges as a result of the
6776// unmerging)
6777// ...
6778//
6779// DstBi:
6780// ...
6781// %UGEPI = gep %GEPI, (UIdx-Idx)
6782// ...
6783// ---------------------------
6784//
6785// The register pressure on the IndirectBr edges is reduced because %GEPIOp is
6786// no longer alive on them.
6787//
6788// We try to unmerge GEPs here in CodGenPrepare, as opposed to limiting merging
6789// of GEPs in the first place in InstCombiner::visitGetElementPtrInst() so as
6790// not to disable further simplications and optimizations as a result of GEP
6791// merging.
6792//
6793// Note this unmerging may increase the length of the data flow critical path
6794// (the path from %GEPIOp to %UGEPI would go through %GEPI), which is a tradeoff
6795// between the register pressure and the length of data-flow critical
6796// path. Restricting this to the uncommon IndirectBr case would minimize the
6797// impact of potentially longer critical path, if any, and the impact on compile
6798// time.
6799static bool tryUnmergingGEPsAcrossIndirectBr(GetElementPtrInst *GEPI,
6800 const TargetTransformInfo *TTI) {
6801 BasicBlock *SrcBlock = GEPI->getParent();
6802 // Check that SrcBlock ends with an IndirectBr. If not, give up. The common
6803 // (non-IndirectBr) cases exit early here.
6804 if (!isa<IndirectBrInst>(SrcBlock->getTerminator()))
6805 return false;
6806 // Check that GEPI is a simple gep with a single constant index.
6807 if (!GEPSequentialConstIndexed(GEPI))
6808 return false;
6809 ConstantInt *GEPIIdx = cast<ConstantInt>(GEPI->getOperand(1));
6810 // Check that GEPI is a cheap one.
6811 if (TTI->getIntImmCost(GEPIIdx->getValue(), GEPIIdx->getType())
6812 > TargetTransformInfo::TCC_Basic)
6813 return false;
6814 Value *GEPIOp = GEPI->getOperand(0);
6815 // Check that GEPIOp is an instruction that's also defined in SrcBlock.
6816 if (!isa<Instruction>(GEPIOp))
6817 return false;
6818 auto *GEPIOpI = cast<Instruction>(GEPIOp);
6819 if (GEPIOpI->getParent() != SrcBlock)
6820 return false;
6821 // Check that GEP is used outside the block, meaning it's alive on the
6822 // IndirectBr edge(s).
6823 if (find_if(GEPI->users(), [&](User *Usr) {
6824 if (auto *I = dyn_cast<Instruction>(Usr)) {
6825 if (I->getParent() != SrcBlock) {
6826 return true;
6827 }
6828 }
6829 return false;
6830 }) == GEPI->users().end())
6831 return false;
6832 // The second elements of the GEP chains to be unmerged.
6833 std::vector<GetElementPtrInst *> UGEPIs;
6834 // Check each user of GEPIOp to check if unmerging would make GEPIOp not alive
6835 // on IndirectBr edges.
6836 for (User *Usr : GEPIOp->users()) {
6837 if (Usr == GEPI) continue;
6838 // Check if Usr is an Instruction. If not, give up.
6839 if (!isa<Instruction>(Usr))
6840 return false;
6841 auto *UI = cast<Instruction>(Usr);
6842 // Check if Usr in the same block as GEPIOp, which is fine, skip.
6843 if (UI->getParent() == SrcBlock)
6844 continue;
6845 // Check if Usr is a GEP. If not, give up.
6846 if (!isa<GetElementPtrInst>(Usr))
6847 return false;
6848 auto *UGEPI = cast<GetElementPtrInst>(Usr);
6849 // Check if UGEPI is a simple gep with a single constant index and GEPIOp is
6850 // the pointer operand to it. If so, record it in the vector. If not, give
6851 // up.
6852 if (!GEPSequentialConstIndexed(UGEPI))
6853 return false;
6854 if (UGEPI->getOperand(0) != GEPIOp)
6855 return false;
6856 if (GEPIIdx->getType() !=
6857 cast<ConstantInt>(UGEPI->getOperand(1))->getType())
6858 return false;
6859 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
6860 if (TTI->getIntImmCost(UGEPIIdx->getValue(), UGEPIIdx->getType())
6861 > TargetTransformInfo::TCC_Basic)
6862 return false;
6863 UGEPIs.push_back(UGEPI);
6864 }
6865 if (UGEPIs.size() == 0)
6866 return false;
6867 // Check the materializing cost of (Uidx-Idx).
6868 for (GetElementPtrInst *UGEPI : UGEPIs) {
6869 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
6870 APInt NewIdx = UGEPIIdx->getValue() - GEPIIdx->getValue();
6871 unsigned ImmCost = TTI->getIntImmCost(NewIdx, GEPIIdx->getType());
6872 if (ImmCost > TargetTransformInfo::TCC_Basic)
6873 return false;
6874 }
6875 // Now unmerge between GEPI and UGEPIs.
6876 for (GetElementPtrInst *UGEPI : UGEPIs) {
6877 UGEPI->setOperand(0, GEPI);
6878 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
6879 Constant *NewUGEPIIdx =
6880 ConstantInt::get(GEPIIdx->getType(),
6881 UGEPIIdx->getValue() - GEPIIdx->getValue());
6882 UGEPI->setOperand(1, NewUGEPIIdx);
6883 // If GEPI is not inbounds but UGEPI is inbounds, change UGEPI to not
6884 // inbounds to avoid UB.
6885 if (!GEPI->isInBounds()) {
6886 UGEPI->setIsInBounds(false);
6887 }
6888 }
6889 // After unmerging, verify that GEPIOp is actually only used in SrcBlock (not
6890 // alive on IndirectBr edges).
6891 assert(find_if(GEPIOp->users(), [&](User *Usr) {
6892 return cast<Instruction>(Usr)->getParent() != SrcBlock;
6893 }) == GEPIOp->users().end() && "GEPIOp is used outside SrcBlock");
6894 return true;
6895}
6896
Teresa Johnson3bd4b5a2019-03-25 18:38:48 +00006897bool CodeGenPrepare::optimizeInst(Instruction *I, bool &ModifiedDT) {
Ahmed Bougachaf3299142015-06-17 20:44:32 +00006898 // Bail out if we inserted the instruction to prevent optimizations from
6899 // stepping on each other's toes.
6900 if (InsertedInsts.count(I))
6901 return false;
6902
Sanjay Pateld1ce4552019-03-20 15:53:06 +00006903 // TODO: Move into the switch on opcode below here.
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006904 if (PHINode *P = dyn_cast<PHINode>(I)) {
6905 // It is possible for very late stage optimizations (such as SimplifyCFG)
6906 // to introduce PHI nodes too late to be cleaned up. If we detect such a
6907 // trivial PHI, go ahead and zap it here.
Daniel Berlin4d0fe642017-04-28 19:55:38 +00006908 if (Value *V = SimplifyInstruction(P, {*DL, TLInfo})) {
Eugene Leviant1e249ca2019-03-12 10:10:29 +00006909 LargeOffsetGEPMap.erase(P);
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006910 P->replaceAllUsesWith(V);
6911 P->eraseFromParent();
6912 ++NumPHIsElim;
Chris Lattneree588de2011-01-15 07:29:01 +00006913 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006914 }
Chris Lattneree588de2011-01-15 07:29:01 +00006915 return false;
6916 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006917
Chris Lattneree588de2011-01-15 07:29:01 +00006918 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006919 // If the source of the cast is a constant, then this should have
6920 // already been constant folded. The only reason NOT to constant fold
6921 // it is if something (e.g. LSR) was careful to place the constant
6922 // evaluation in a block other than then one that uses it (e.g. to hoist
6923 // the address of globals out of a loop). If this is the case, we don't
6924 // want to forward-subst the cast.
6925 if (isa<Constant>(CI->getOperand(0)))
6926 return false;
6927
Mehdi Amini44ede332015-07-09 02:09:04 +00006928 if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
Chris Lattneree588de2011-01-15 07:29:01 +00006929 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006930
Chris Lattneree588de2011-01-15 07:29:01 +00006931 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00006932 /// Sink a zext or sext into its user blocks if the target type doesn't
6933 /// fit in one register
Mehdi Amini44ede332015-07-09 02:09:04 +00006934 if (TLI &&
6935 TLI->getTypeAction(CI->getContext(),
6936 TLI->getValueType(*DL, CI->getType())) ==
6937 TargetLowering::TypeExpandInteger) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00006938 return SinkCast(CI);
6939 } else {
Jun Bum Limdee55652017-04-03 19:20:07 +00006940 bool MadeChange = optimizeExt(I);
Sanjay Patelfc580a62015-09-21 23:03:16 +00006941 return MadeChange | optimizeExtUses(I);
Manuel Jacoba7c48f92014-03-13 13:36:25 +00006942 }
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006943 }
Chris Lattneree588de2011-01-15 07:29:01 +00006944 return false;
6945 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006946
Sanjay Pateld8b4efc2019-02-18 23:33:05 +00006947 if (auto *Cmp = dyn_cast<CmpInst>(I))
Teresa Johnson3bd4b5a2019-03-25 18:38:48 +00006948 if (TLI && optimizeCmp(Cmp, ModifiedDT))
Sanjay Patel00fcc742019-02-03 13:48:03 +00006949 return true;
Nadav Rotem465834c2012-07-24 10:51:42 +00006950
Chris Lattneree588de2011-01-15 07:29:01 +00006951 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Sanjoy Das00757272016-12-16 20:29:39 +00006952 LI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006953 if (TLI) {
Geoff Berry5256fca2015-11-20 22:34:39 +00006954 bool Modified = optimizeLoadExt(LI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006955 unsigned AS = LI->getPointerAddressSpace();
Geoff Berry5256fca2015-11-20 22:34:39 +00006956 Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
6957 return Modified;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006958 }
Hans Wennborgf3254832012-10-30 11:23:25 +00006959 return false;
Chris Lattneree588de2011-01-15 07:29:01 +00006960 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006961
Chris Lattneree588de2011-01-15 07:29:01 +00006962 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Wei Mia2f0b592016-12-22 19:44:45 +00006963 if (TLI && splitMergedValStore(*SI, *DL, *TLI))
6964 return true;
Sanjoy Das00757272016-12-16 20:29:39 +00006965 SI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006966 if (TLI) {
6967 unsigned AS = SI->getPointerAddressSpace();
Sanjay Patelfc580a62015-09-21 23:03:16 +00006968 return optimizeMemoryInst(I, SI->getOperand(1),
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006969 SI->getOperand(0)->getType(), AS);
6970 }
Chris Lattneree588de2011-01-15 07:29:01 +00006971 return false;
6972 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006973
Matt Arsenault02d915b2017-03-15 22:35:20 +00006974 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
6975 unsigned AS = RMW->getPointerAddressSpace();
6976 return optimizeMemoryInst(I, RMW->getPointerOperand(),
6977 RMW->getType(), AS);
6978 }
6979
6980 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(I)) {
6981 unsigned AS = CmpX->getPointerAddressSpace();
6982 return optimizeMemoryInst(I, CmpX->getPointerOperand(),
6983 CmpX->getCompareOperand()->getType(), AS);
6984 }
6985
Yi Jiangd069f632014-04-21 19:34:27 +00006986 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
6987
Geoff Berry5d534b62017-02-21 18:53:14 +00006988 if (BinOp && (BinOp->getOpcode() == Instruction::And) &&
6989 EnableAndCmpSinking && TLI)
6990 return sinkAndCmp0Expression(BinOp, *TLI, InsertedInsts);
6991
Yi Jiangd069f632014-04-21 19:34:27 +00006992 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
6993 BinOp->getOpcode() == Instruction::LShr)) {
6994 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
6995 if (TLI && CI && TLI->hasExtractBitsInsn())
Mehdi Amini44ede332015-07-09 02:09:04 +00006996 return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
Yi Jiangd069f632014-04-21 19:34:27 +00006997
6998 return false;
6999 }
7000
Chris Lattneree588de2011-01-15 07:29:01 +00007001 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00007002 if (GEPI->hasAllZeroIndices()) {
7003 /// The GEP operand must be a pointer, so must its result -> BitCast
7004 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
7005 GEPI->getName(), GEPI);
Vedant Kumar40399a22018-05-24 23:00:21 +00007006 NC->setDebugLoc(GEPI->getDebugLoc());
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00007007 GEPI->replaceAllUsesWith(NC);
7008 GEPI->eraseFromParent();
7009 ++NumGEPsElim;
Teresa Johnson3bd4b5a2019-03-25 18:38:48 +00007010 optimizeInst(NC, ModifiedDT);
Chris Lattneree588de2011-01-15 07:29:01 +00007011 return true;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00007012 }
Hiroshi Yamauchi93644322017-09-11 17:52:08 +00007013 if (tryUnmergingGEPsAcrossIndirectBr(GEPI, TTI)) {
7014 return true;
7015 }
Chris Lattneree588de2011-01-15 07:29:01 +00007016 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00007017 }
Nadav Rotem465834c2012-07-24 10:51:42 +00007018
Florian Hahn3b251962019-02-05 10:27:40 +00007019 if (tryToSinkFreeOperands(I))
7020 return true;
7021
Sanjay Pateld1ce4552019-03-20 15:53:06 +00007022 switch (I->getOpcode()) {
7023 case Instruction::Call:
7024 return optimizeCallInst(cast<CallInst>(I), ModifiedDT);
7025 case Instruction::Select:
Teresa Johnsonb7e21382019-03-27 18:44:25 +00007026 return optimizeSelectInst(cast<SelectInst>(I));
Sanjay Pateld1ce4552019-03-20 15:53:06 +00007027 case Instruction::ShuffleVector:
7028 return optimizeShuffleVectorInst(cast<ShuffleVectorInst>(I));
7029 case Instruction::Switch:
7030 return optimizeSwitchInst(cast<SwitchInst>(I));
7031 case Instruction::ExtractElement:
7032 return optimizeExtractElementInst(cast<ExtractElementInst>(I));
7033 }
Quentin Colombetc32615d2014-10-31 17:52:53 +00007034
Chris Lattneree588de2011-01-15 07:29:01 +00007035 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00007036}
7037
James Molloyf01488e2016-01-15 09:20:19 +00007038/// Given an OR instruction, check to see if this is a bitreverse
7039/// idiom. If so, insert the new intrinsic and return true.
7040static bool makeBitReverse(Instruction &I, const DataLayout &DL,
7041 const TargetLowering &TLI) {
7042 if (!I.getType()->isIntegerTy() ||
7043 !TLI.isOperationLegalOrCustom(ISD::BITREVERSE,
7044 TLI.getValueType(DL, I.getType(), true)))
7045 return false;
7046
7047 SmallVector<Instruction*, 4> Insts;
Chad Rosiera00df492016-05-25 16:22:14 +00007048 if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts))
James Molloyf01488e2016-01-15 09:20:19 +00007049 return false;
7050 Instruction *LastInst = Insts.back();
7051 I.replaceAllUsesWith(LastInst);
7052 RecursivelyDeleteTriviallyDeadInstructions(&I);
7053 return true;
7054}
7055
Chris Lattnerf2836d12007-03-31 04:06:36 +00007056// In this pass we look for GEP and cast instructions that are used
7057// across basic blocks and rewrite them to improve basic-block-at-a-time
7058// selection.
Teresa Johnson3bd4b5a2019-03-25 18:38:48 +00007059bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool &ModifiedDT) {
Cameron Zwarichce3b9302011-01-06 00:42:50 +00007060 SunkAddrs.clear();
Cameron Zwarich5dd2aa22011-03-02 03:31:46 +00007061 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00007062
Chris Lattner7a277142011-01-15 07:14:54 +00007063 CurInstIterator = BB.begin();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00007064 while (CurInstIterator != BB.end()) {
Teresa Johnson3bd4b5a2019-03-25 18:38:48 +00007065 MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00007066 if (ModifiedDT)
7067 return true;
7068 }
Benjamin Kramer455fa352012-11-23 19:17:06 +00007069
James Molloyf01488e2016-01-15 09:20:19 +00007070 bool MadeBitReverse = true;
7071 while (TLI && MadeBitReverse) {
7072 MadeBitReverse = false;
7073 for (auto &I : reverse(BB)) {
7074 if (makeBitReverse(I, *DL, *TLI)) {
7075 MadeBitReverse = MadeChange = true;
George Burgess IVd4febd12016-03-22 21:25:08 +00007076 ModifiedDT = true;
James Molloyf01488e2016-01-15 09:20:19 +00007077 break;
7078 }
7079 }
7080 }
Rong Xuce3be452019-03-08 22:46:18 +00007081 MadeChange |= dupRetToEnableTailCallOpts(&BB, ModifiedDT);
Junmo Park7d6c5f12016-01-28 09:42:39 +00007082
Chris Lattnerf2836d12007-03-31 04:06:36 +00007083 return MadeChange;
7084}
Devang Patel53771ba2011-08-18 00:50:51 +00007085
7086// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +00007087// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +00007088// find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +00007089bool CodeGenPrepare::placeDbgValues(Function &F) {
Devang Patel53771ba2011-08-18 00:50:51 +00007090 bool MadeChange = false;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00007091 for (BasicBlock &BB : F) {
Craig Topperc0196b12014-04-14 00:51:57 +00007092 Instruction *PrevNonDbgInst = nullptr;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00007093 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00007094 Instruction *Insn = &*BI++;
Devang Patel53771ba2011-08-18 00:50:51 +00007095 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
Adrian Prantl32da8892014-04-25 20:49:25 +00007096 // Leave dbg.values that refer to an alloca alone. These
Craig Topper87e715f2017-11-07 20:56:17 +00007097 // intrinsics describe the address of a variable (= the alloca)
Adrian Prantl32da8892014-04-25 20:49:25 +00007098 // being taken. They should not be moved next to the alloca
7099 // (and to the beginning of the scope), but rather stay close to
7100 // where said address is used.
7101 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
Devang Patel53771ba2011-08-18 00:50:51 +00007102 PrevNonDbgInst = Insn;
7103 continue;
7104 }
7105
7106 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
7107 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
Reid Kleckner8de1fe22015-12-08 23:00:03 +00007108 // If VI is a phi in a block with an EHPad terminator, we can't insert
7109 // after it.
7110 if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
7111 continue;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007112 LLVM_DEBUG(dbgs() << "Moving Debug Value before :\n"
7113 << *DVI << ' ' << *VI);
Devang Patel53771ba2011-08-18 00:50:51 +00007114 DVI->removeFromParent();
Reid Klecknere18f92b2015-12-08 22:33:23 +00007115 if (isa<PHINode>(VI))
7116 DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
7117 else
7118 DVI->insertAfter(VI);
Devang Patel53771ba2011-08-18 00:50:51 +00007119 MadeChange = true;
7120 ++NumDbgValueMoved;
7121 }
7122 }
7123 }
7124 return MadeChange;
7125}
Tim Northovercea0abb2014-03-29 08:22:29 +00007126
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00007127/// Scale down both weights to fit into uint32_t.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007128static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
7129 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
Eugene Zelenko900b6332017-08-29 22:32:07 +00007130 uint32_t Scale = (NewMax / std::numeric_limits<uint32_t>::max()) + 1;
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007131 NewTrue = NewTrue / Scale;
7132 NewFalse = NewFalse / Scale;
7133}
7134
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00007135/// Some targets prefer to split a conditional branch like:
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007136/// \code
7137/// %0 = icmp ne i32 %a, 0
7138/// %1 = icmp ne i32 %b, 0
7139/// %or.cond = or i1 %0, %1
7140/// br i1 %or.cond, label %TrueBB, label %FalseBB
7141/// \endcode
7142/// into multiple branch instructions like:
7143/// \code
7144/// bb1:
7145/// %0 = icmp ne i32 %a, 0
7146/// br i1 %0, label %TrueBB, label %bb2
7147/// bb2:
7148/// %1 = icmp ne i32 %b, 0
7149/// br i1 %1, label %TrueBB, label %FalseBB
7150/// \endcode
7151/// This usually allows instruction selection to do even further optimizations
7152/// and combine the compare with the branch instruction. Currently this is
7153/// applied for targets which have "cheap" jump instructions.
7154///
7155/// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
7156///
Rong Xuce3be452019-03-08 22:46:18 +00007157bool CodeGenPrepare::splitBranchCondition(Function &F, bool &ModifiedDT) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00007158 if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007159 return false;
7160
7161 bool MadeChange = false;
7162 for (auto &BB : F) {
7163 // Does this BB end with the following?
7164 // %cond1 = icmp|fcmp|binary instruction ...
7165 // %cond2 = icmp|fcmp|binary instruction ...
7166 // %cond.or = or|and i1 %cond1, cond2
7167 // br i1 %cond.or label %dest1, label %dest2"
7168 BinaryOperator *LogicOp;
7169 BasicBlock *TBB, *FBB;
7170 if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
7171 continue;
7172
Sanjay Patel42574202015-09-02 19:23:23 +00007173 auto *Br1 = cast<BranchInst>(BB.getTerminator());
7174 if (Br1->getMetadata(LLVMContext::MD_unpredictable))
7175 continue;
7176
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007177 unsigned Opc;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00007178 Value *Cond1, *Cond2;
7179 if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
7180 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007181 Opc = Instruction::And;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00007182 else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
7183 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007184 Opc = Instruction::Or;
7185 else
7186 continue;
7187
7188 if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
7189 !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
7190 continue;
7191
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007192 LLVM_DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007193
7194 // Create a new BB.
Duncan P. N. Exon Smitha848c472016-02-21 19:52:15 +00007195 auto TmpBB =
7196 BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split",
7197 BB.getParent(), BB.getNextNode());
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007198
7199 // Update original basic block by using the first condition directly by the
7200 // branch instruction and removing the no longer needed and/or instruction.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007201 Br1->setCondition(Cond1);
7202 LogicOp->eraseFromParent();
Juergen Ributzka8bda7382014-12-09 17:50:10 +00007203
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00007204 // Depending on the condition we have to either replace the true or the
7205 // false successor of the original branch instruction.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007206 if (Opc == Instruction::And)
7207 Br1->setSuccessor(0, TmpBB);
7208 else
7209 Br1->setSuccessor(1, TmpBB);
7210
7211 // Fill in the new basic block.
7212 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
Juergen Ributzka8bda7382014-12-09 17:50:10 +00007213 if (auto *I = dyn_cast<Instruction>(Cond2)) {
7214 I->removeFromParent();
7215 I->insertBefore(Br2);
7216 }
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007217
7218 // Update PHI nodes in both successors. The original BB needs to be
Hiroshi Inoue6a391bb2017-06-27 10:35:37 +00007219 // replaced in one successor's PHI nodes, because the branch comes now from
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007220 // the newly generated BB (NewBB). In the other successor we need to add one
7221 // incoming edge to the PHI nodes, because both branch instructions target
7222 // now the same successor. Depending on the original branch condition
7223 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
Simon Pilgrimf2fbf432016-11-20 13:47:59 +00007224 // we perform the correct update for the PHI nodes.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007225 // This doesn't change the successor order of the just created branch
7226 // instruction (or any other instruction).
7227 if (Opc == Instruction::Or)
7228 std::swap(TBB, FBB);
7229
7230 // Replace the old BB with the new BB.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00007231 for (PHINode &PN : TBB->phis()) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007232 int i;
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00007233 while ((i = PN.getBasicBlockIndex(&BB)) >= 0)
7234 PN.setIncomingBlock(i, TmpBB);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007235 }
7236
7237 // Add another incoming edge form the new BB.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00007238 for (PHINode &PN : FBB->phis()) {
7239 auto *Val = PN.getIncomingValueForBlock(&BB);
7240 PN.addIncoming(Val, TmpBB);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007241 }
7242
7243 // Update the branch weights (from SelectionDAGBuilder::
7244 // FindMergedConditions).
7245 if (Opc == Instruction::Or) {
7246 // Codegen X | Y as:
7247 // BB1:
7248 // jmp_if_X TBB
7249 // jmp TmpBB
7250 // TmpBB:
7251 // jmp_if_Y TBB
7252 // jmp FBB
7253 //
7254
7255 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
7256 // The requirement is that
7257 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00007258 // = TrueProb for original BB.
7259 // Assuming the original weights are A and B, one choice is to set BB1's
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007260 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
7261 // assumes that
7262 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
7263 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
7264 // TmpBB, but the math is more complicated.
7265 uint64_t TrueWeight, FalseWeight;
Sanjay Pateldc88bd62016-04-23 20:01:22 +00007266 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007267 uint64_t NewTrueWeight = TrueWeight;
7268 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
7269 scaleWeights(NewTrueWeight, NewFalseWeight);
7270 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
7271 .createBranchWeights(TrueWeight, FalseWeight));
7272
7273 NewTrueWeight = TrueWeight;
7274 NewFalseWeight = 2 * FalseWeight;
7275 scaleWeights(NewTrueWeight, NewFalseWeight);
7276 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
7277 .createBranchWeights(TrueWeight, FalseWeight));
7278 }
7279 } else {
7280 // Codegen X & Y as:
7281 // BB1:
7282 // jmp_if_X TmpBB
7283 // jmp FBB
7284 // TmpBB:
7285 // jmp_if_Y TBB
7286 // jmp FBB
7287 //
7288 // This requires creation of TmpBB after CurBB.
7289
7290 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
7291 // The requirement is that
7292 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00007293 // = FalseProb for original BB.
7294 // Assuming the original weights are A and B, one choice is to set BB1's
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007295 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
7296 // assumes that
7297 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
7298 uint64_t TrueWeight, FalseWeight;
Sanjay Pateldc88bd62016-04-23 20:01:22 +00007299 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007300 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
7301 uint64_t NewFalseWeight = FalseWeight;
7302 scaleWeights(NewTrueWeight, NewFalseWeight);
7303 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
7304 .createBranchWeights(TrueWeight, FalseWeight));
7305
7306 NewTrueWeight = 2 * TrueWeight;
7307 NewFalseWeight = FalseWeight;
7308 scaleWeights(NewTrueWeight, NewFalseWeight);
7309 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
7310 .createBranchWeights(TrueWeight, FalseWeight));
7311 }
7312 }
7313
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007314 ModifiedDT = true;
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007315 MadeChange = true;
7316
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007317 LLVM_DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
7318 TmpBB->dump());
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007319 }
7320 return MadeChange;
7321}