Bug Summary

File:build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/llvm/lib/CodeGen/CodeGenPrepare.cpp
Warning:line 1237, column 37
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name CodeGenPrepare.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm -resource-dir /usr/lib/llvm-16/lib/clang/16.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I lib/CodeGen -I /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/llvm/lib/CodeGen -I include -I /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-16/lib/clang/16.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-10-03-140002-15933-1 -x c++ /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/llvm/lib/CodeGen/CodeGenPrepare.cpp
1//===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
2//
3// 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
6//
7//===----------------------------------------------------------------------===//
8//
9// This pass munges the code in the input function to better prepare it for
10// SelectionDAG-based code generation. This works around limitations in it's
11// basic-block-at-a-time approach. It should eventually be removed.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/MapVector.h"
19#include "llvm/ADT/PointerIntPair.h"
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/SmallPtrSet.h"
22#include "llvm/ADT/SmallVector.h"
23#include "llvm/ADT/Statistic.h"
24#include "llvm/Analysis/BlockFrequencyInfo.h"
25#include "llvm/Analysis/BranchProbabilityInfo.h"
26#include "llvm/Analysis/InstructionSimplify.h"
27#include "llvm/Analysis/LoopInfo.h"
28#include "llvm/Analysis/ProfileSummaryInfo.h"
29#include "llvm/Analysis/TargetLibraryInfo.h"
30#include "llvm/Analysis/TargetTransformInfo.h"
31#include "llvm/Analysis/ValueTracking.h"
32#include "llvm/Analysis/VectorUtils.h"
33#include "llvm/CodeGen/Analysis.h"
34#include "llvm/CodeGen/BasicBlockSectionsProfileReader.h"
35#include "llvm/CodeGen/ISDOpcodes.h"
36#include "llvm/CodeGen/SelectionDAGNodes.h"
37#include "llvm/CodeGen/TargetLowering.h"
38#include "llvm/CodeGen/TargetPassConfig.h"
39#include "llvm/CodeGen/TargetSubtargetInfo.h"
40#include "llvm/CodeGen/ValueTypes.h"
41#include "llvm/Config/llvm-config.h"
42#include "llvm/IR/Argument.h"
43#include "llvm/IR/Attributes.h"
44#include "llvm/IR/BasicBlock.h"
45#include "llvm/IR/Constant.h"
46#include "llvm/IR/Constants.h"
47#include "llvm/IR/DataLayout.h"
48#include "llvm/IR/DebugInfo.h"
49#include "llvm/IR/DerivedTypes.h"
50#include "llvm/IR/Dominators.h"
51#include "llvm/IR/Function.h"
52#include "llvm/IR/GetElementPtrTypeIterator.h"
53#include "llvm/IR/GlobalValue.h"
54#include "llvm/IR/GlobalVariable.h"
55#include "llvm/IR/IRBuilder.h"
56#include "llvm/IR/InlineAsm.h"
57#include "llvm/IR/InstrTypes.h"
58#include "llvm/IR/Instruction.h"
59#include "llvm/IR/Instructions.h"
60#include "llvm/IR/IntrinsicInst.h"
61#include "llvm/IR/Intrinsics.h"
62#include "llvm/IR/IntrinsicsAArch64.h"
63#include "llvm/IR/LLVMContext.h"
64#include "llvm/IR/MDBuilder.h"
65#include "llvm/IR/Module.h"
66#include "llvm/IR/Operator.h"
67#include "llvm/IR/PatternMatch.h"
68#include "llvm/IR/ProfDataUtils.h"
69#include "llvm/IR/Statepoint.h"
70#include "llvm/IR/Type.h"
71#include "llvm/IR/Use.h"
72#include "llvm/IR/User.h"
73#include "llvm/IR/Value.h"
74#include "llvm/IR/ValueHandle.h"
75#include "llvm/IR/ValueMap.h"
76#include "llvm/InitializePasses.h"
77#include "llvm/Pass.h"
78#include "llvm/Support/BlockFrequency.h"
79#include "llvm/Support/BranchProbability.h"
80#include "llvm/Support/Casting.h"
81#include "llvm/Support/CommandLine.h"
82#include "llvm/Support/Compiler.h"
83#include "llvm/Support/Debug.h"
84#include "llvm/Support/ErrorHandling.h"
85#include "llvm/Support/MachineValueType.h"
86#include "llvm/Support/MathExtras.h"
87#include "llvm/Support/raw_ostream.h"
88#include "llvm/Target/TargetMachine.h"
89#include "llvm/Target/TargetOptions.h"
90#include "llvm/Transforms/Utils/BasicBlockUtils.h"
91#include "llvm/Transforms/Utils/BypassSlowDivision.h"
92#include "llvm/Transforms/Utils/Local.h"
93#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
94#include "llvm/Transforms/Utils/SizeOpts.h"
95#include <algorithm>
96#include <cassert>
97#include <cstdint>
98#include <iterator>
99#include <limits>
100#include <memory>
101#include <utility>
102#include <vector>
103
104using namespace llvm;
105using namespace llvm::PatternMatch;
106
107#define DEBUG_TYPE"codegenprepare" "codegenprepare"
108
109STATISTIC(NumBlocksElim, "Number of blocks eliminated")static llvm::Statistic NumBlocksElim = {"codegenprepare", "NumBlocksElim"
, "Number of blocks eliminated"}
;
110STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated")static llvm::Statistic NumPHIsElim = {"codegenprepare", "NumPHIsElim"
, "Number of trivial PHIs eliminated"}
;
111STATISTIC(NumGEPsElim, "Number of GEPs converted to casts")static llvm::Statistic NumGEPsElim = {"codegenprepare", "NumGEPsElim"
, "Number of GEPs converted to casts"}
;
112STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "static llvm::Statistic NumCmpUses = {"codegenprepare", "NumCmpUses"
, "Number of uses of Cmp expressions replaced with uses of " "sunken Cmps"
}
113 "sunken Cmps")static llvm::Statistic NumCmpUses = {"codegenprepare", "NumCmpUses"
, "Number of uses of Cmp expressions replaced with uses of " "sunken Cmps"
}
;
114STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "static llvm::Statistic NumCastUses = {"codegenprepare", "NumCastUses"
, "Number of uses of Cast expressions replaced with uses " "of sunken Casts"
}
115 "of sunken Casts")static llvm::Statistic NumCastUses = {"codegenprepare", "NumCastUses"
, "Number of uses of Cast expressions replaced with uses " "of sunken Casts"
}
;
116STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "static llvm::Statistic NumMemoryInsts = {"codegenprepare", "NumMemoryInsts"
, "Number of memory instructions whose address " "computations were sunk"
}
117 "computations were sunk")static llvm::Statistic NumMemoryInsts = {"codegenprepare", "NumMemoryInsts"
, "Number of memory instructions whose address " "computations were sunk"
}
;
118STATISTIC(NumMemoryInstsPhiCreated,static llvm::Statistic NumMemoryInstsPhiCreated = {"codegenprepare"
, "NumMemoryInstsPhiCreated", "Number of phis created when address "
"computations were sunk to memory instructions"}
119 "Number of phis created when address "static llvm::Statistic NumMemoryInstsPhiCreated = {"codegenprepare"
, "NumMemoryInstsPhiCreated", "Number of phis created when address "
"computations were sunk to memory instructions"}
120 "computations were sunk to memory instructions")static llvm::Statistic NumMemoryInstsPhiCreated = {"codegenprepare"
, "NumMemoryInstsPhiCreated", "Number of phis created when address "
"computations were sunk to memory instructions"}
;
121STATISTIC(NumMemoryInstsSelectCreated,static llvm::Statistic NumMemoryInstsSelectCreated = {"codegenprepare"
, "NumMemoryInstsSelectCreated", "Number of select created when address "
"computations were sunk to memory instructions"}
122 "Number of select created when address "static llvm::Statistic NumMemoryInstsSelectCreated = {"codegenprepare"
, "NumMemoryInstsSelectCreated", "Number of select created when address "
"computations were sunk to memory instructions"}
123 "computations were sunk to memory instructions")static llvm::Statistic NumMemoryInstsSelectCreated = {"codegenprepare"
, "NumMemoryInstsSelectCreated", "Number of select created when address "
"computations were sunk to memory instructions"}
;
124STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads")static llvm::Statistic NumExtsMoved = {"codegenprepare", "NumExtsMoved"
, "Number of [s|z]ext instructions combined with loads"}
;
125STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized")static llvm::Statistic NumExtUses = {"codegenprepare", "NumExtUses"
, "Number of uses of [s|z]ext instructions optimized"}
;
126STATISTIC(NumAndsAdded,static llvm::Statistic NumAndsAdded = {"codegenprepare", "NumAndsAdded"
, "Number of and mask instructions added to form ext loads"}
127 "Number of and mask instructions added to form ext loads")static llvm::Statistic NumAndsAdded = {"codegenprepare", "NumAndsAdded"
, "Number of and mask instructions added to form ext loads"}
;
128STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized")static llvm::Statistic NumAndUses = {"codegenprepare", "NumAndUses"
, "Number of uses of and mask instructions optimized"}
;
129STATISTIC(NumRetsDup, "Number of return instructions duplicated")static llvm::Statistic NumRetsDup = {"codegenprepare", "NumRetsDup"
, "Number of return instructions duplicated"}
;
130STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved")static llvm::Statistic NumDbgValueMoved = {"codegenprepare", "NumDbgValueMoved"
, "Number of debug value instructions moved"}
;
131STATISTIC(NumSelectsExpanded, "Number of selects turned into branches")static llvm::Statistic NumSelectsExpanded = {"codegenprepare"
, "NumSelectsExpanded", "Number of selects turned into branches"
}
;
132STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed")static llvm::Statistic NumStoreExtractExposed = {"codegenprepare"
, "NumStoreExtractExposed", "Number of store(extractelement) exposed"
}
;
133
134static cl::opt<bool> DisableBranchOpts(
135 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
136 cl::desc("Disable branch optimizations in CodeGenPrepare"));
137
138static cl::opt<bool>
139 DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
140 cl::desc("Disable GC optimizations in CodeGenPrepare"));
141
142static cl::opt<bool>
143 DisableSelectToBranch("disable-cgp-select2branch", cl::Hidden,
144 cl::init(false),
145 cl::desc("Disable select to branch conversion."));
146
147static cl::opt<bool>
148 AddrSinkUsingGEPs("addr-sink-using-gep", cl::Hidden, cl::init(true),
149 cl::desc("Address sinking in CGP using GEPs."));
150
151static cl::opt<bool>
152 EnableAndCmpSinking("enable-andcmp-sinking", cl::Hidden, cl::init(true),
153 cl::desc("Enable sinkinig and/cmp into branches."));
154
155static cl::opt<bool> DisableStoreExtract(
156 "disable-cgp-store-extract", cl::Hidden, cl::init(false),
157 cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
158
159static cl::opt<bool> StressStoreExtract(
160 "stress-cgp-store-extract", cl::Hidden, cl::init(false),
161 cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
162
163static cl::opt<bool> DisableExtLdPromotion(
164 "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
165 cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
166 "CodeGenPrepare"));
167
168static cl::opt<bool> StressExtLdPromotion(
169 "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
170 cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
171 "optimization in CodeGenPrepare"));
172
173static cl::opt<bool> DisablePreheaderProtect(
174 "disable-preheader-prot", cl::Hidden, cl::init(false),
175 cl::desc("Disable protection against removing loop preheaders"));
176
177static cl::opt<bool> ProfileGuidedSectionPrefix(
178 "profile-guided-section-prefix", cl::Hidden, cl::init(true),
179 cl::desc("Use profile info to add section prefix for hot/cold functions"));
180
181static cl::opt<bool> ProfileUnknownInSpecialSection(
182 "profile-unknown-in-special-section", cl::Hidden,
183 cl::desc("In profiling mode like sampleFDO, if a function doesn't have "
184 "profile, we cannot tell the function is cold for sure because "
185 "it may be a function newly added without ever being sampled. "
186 "With the flag enabled, compiler can put such profile unknown "
187 "functions into a special section, so runtime system can choose "
188 "to handle it in a different way than .text section, to save "
189 "RAM for example. "));
190
191static cl::opt<bool> BBSectionsGuidedSectionPrefix(
192 "bbsections-guided-section-prefix", cl::Hidden, cl::init(true),
193 cl::desc("Use the basic-block-sections profile to determine the text "
194 "section prefix for hot functions. Functions with "
195 "basic-block-sections profile will be placed in `.text.hot` "
196 "regardless of their FDO profile info. Other functions won't be "
197 "impacted, i.e., their prefixes will be decided by FDO/sampleFDO "
198 "profiles."));
199
200static cl::opt<unsigned> FreqRatioToSkipMerge(
201 "cgp-freq-ratio-to-skip-merge", cl::Hidden, cl::init(2),
202 cl::desc("Skip merging empty blocks if (frequency of empty block) / "
203 "(frequency of destination block) is greater than this ratio"));
204
205static cl::opt<bool> ForceSplitStore(
206 "force-split-store", cl::Hidden, cl::init(false),
207 cl::desc("Force store splitting no matter what the target query says."));
208
209static cl::opt<bool> EnableTypePromotionMerge(
210 "cgp-type-promotion-merge", cl::Hidden,
211 cl::desc("Enable merging of redundant sexts when one is dominating"
212 " the other."),
213 cl::init(true));
214
215static cl::opt<bool> DisableComplexAddrModes(
216 "disable-complex-addr-modes", cl::Hidden, cl::init(false),
217 cl::desc("Disables combining addressing modes with different parts "
218 "in optimizeMemoryInst."));
219
220static cl::opt<bool>
221 AddrSinkNewPhis("addr-sink-new-phis", cl::Hidden, cl::init(false),
222 cl::desc("Allow creation of Phis in Address sinking."));
223
224static cl::opt<bool> AddrSinkNewSelects(
225 "addr-sink-new-select", cl::Hidden, cl::init(true),
226 cl::desc("Allow creation of selects in Address sinking."));
227
228static cl::opt<bool> AddrSinkCombineBaseReg(
229 "addr-sink-combine-base-reg", cl::Hidden, cl::init(true),
230 cl::desc("Allow combining of BaseReg field in Address sinking."));
231
232static cl::opt<bool> AddrSinkCombineBaseGV(
233 "addr-sink-combine-base-gv", cl::Hidden, cl::init(true),
234 cl::desc("Allow combining of BaseGV field in Address sinking."));
235
236static cl::opt<bool> AddrSinkCombineBaseOffs(
237 "addr-sink-combine-base-offs", cl::Hidden, cl::init(true),
238 cl::desc("Allow combining of BaseOffs field in Address sinking."));
239
240static cl::opt<bool> AddrSinkCombineScaledReg(
241 "addr-sink-combine-scaled-reg", cl::Hidden, cl::init(true),
242 cl::desc("Allow combining of ScaledReg field in Address sinking."));
243
244static cl::opt<bool>
245 EnableGEPOffsetSplit("cgp-split-large-offset-gep", cl::Hidden,
246 cl::init(true),
247 cl::desc("Enable splitting large offset of GEP."));
248
249static cl::opt<bool> EnableICMP_EQToICMP_ST(
250 "cgp-icmp-eq2icmp-st", cl::Hidden, cl::init(false),
251 cl::desc("Enable ICMP_EQ to ICMP_S(L|G)T conversion."));
252
253static cl::opt<bool>
254 VerifyBFIUpdates("cgp-verify-bfi-updates", cl::Hidden, cl::init(false),
255 cl::desc("Enable BFI update verification for "
256 "CodeGenPrepare."));
257
258static cl::opt<bool>
259 OptimizePhiTypes("cgp-optimize-phi-types", cl::Hidden, cl::init(false),
260 cl::desc("Enable converting phi types in CodeGenPrepare"));
261
262static cl::opt<unsigned>
263 HugeFuncThresholdInCGPP("cgpp-huge-func", cl::init(10000), cl::Hidden,
264 cl::desc("Least BB number of huge function."));
265
266namespace {
267
268enum ExtType {
269 ZeroExtension, // Zero extension has been seen.
270 SignExtension, // Sign extension has been seen.
271 BothExtension // This extension type is used if we saw sext after
272 // ZeroExtension had been set, or if we saw zext after
273 // SignExtension had been set. It makes the type
274 // information of a promoted instruction invalid.
275};
276
277enum ModifyDT {
278 NotModifyDT, // Not Modify any DT.
279 ModifyBBDT, // Modify the Basic Block Dominator Tree.
280 ModifyInstDT // Modify the Instruction Dominator in a Basic Block,
281 // This usually means we move/delete/insert instruction
282 // in a Basic Block. So we should re-iterate instructions
283 // in such Basic Block.
284};
285
286using SetOfInstrs = SmallPtrSet<Instruction *, 16>;
287using TypeIsSExt = PointerIntPair<Type *, 2, ExtType>;
288using InstrToOrigTy = DenseMap<Instruction *, TypeIsSExt>;
289using SExts = SmallVector<Instruction *, 16>;
290using ValueToSExts = DenseMap<Value *, SExts>;
291
292class TypePromotionTransaction;
293
294class CodeGenPrepare : public FunctionPass {
295 const TargetMachine *TM = nullptr;
296 const TargetSubtargetInfo *SubtargetInfo;
297 const TargetLowering *TLI = nullptr;
298 const TargetRegisterInfo *TRI;
299 const TargetTransformInfo *TTI = nullptr;
300 const BasicBlockSectionsProfileReader *BBSectionsProfileReader = nullptr;
301 const TargetLibraryInfo *TLInfo;
302 const LoopInfo *LI;
303 std::unique_ptr<BlockFrequencyInfo> BFI;
304 std::unique_ptr<BranchProbabilityInfo> BPI;
305 ProfileSummaryInfo *PSI;
306
307 /// As we scan instructions optimizing them, this is the next instruction
308 /// to optimize. Transforms that can invalidate this should update it.
309 BasicBlock::iterator CurInstIterator;
310
311 /// Keeps track of non-local addresses that have been sunk into a block.
312 /// This allows us to avoid inserting duplicate code for blocks with
313 /// multiple load/stores of the same address. The usage of WeakTrackingVH
314 /// enables SunkAddrs to be treated as a cache whose entries can be
315 /// invalidated if a sunken address computation has been erased.
316 ValueMap<Value *, WeakTrackingVH> SunkAddrs;
317
318 /// Keeps track of all instructions inserted for the current function.
319 SetOfInstrs InsertedInsts;
320
321 /// Keeps track of the type of the related instruction before their
322 /// promotion for the current function.
323 InstrToOrigTy PromotedInsts;
324
325 /// Keep track of instructions removed during promotion.
326 SetOfInstrs RemovedInsts;
327
328 /// Keep track of sext chains based on their initial value.
329 DenseMap<Value *, Instruction *> SeenChainsForSExt;
330
331 /// Keep track of GEPs accessing the same data structures such as structs or
332 /// arrays that are candidates to be split later because of their large
333 /// size.
334 MapVector<AssertingVH<Value>,
335 SmallVector<std::pair<AssertingVH<GetElementPtrInst>, int64_t>, 32>>
336 LargeOffsetGEPMap;
337
338 /// Keep track of new GEP base after splitting the GEPs having large offset.
339 SmallSet<AssertingVH<Value>, 2> NewGEPBases;
340
341 /// Map serial numbers to Large offset GEPs.
342 DenseMap<AssertingVH<GetElementPtrInst>, int> LargeOffsetGEPID;
343
344 /// Keep track of SExt promoted.
345 ValueToSExts ValToSExtendedUses;
346
347 /// True if the function has the OptSize attribute.
348 bool OptSize;
349
350 /// DataLayout for the Function being processed.
351 const DataLayout *DL = nullptr;
352
353 /// Building the dominator tree can be expensive, so we only build it
354 /// lazily and update it when required.
355 std::unique_ptr<DominatorTree> DT;
356
357public:
358 /// If encounter huge function, we need to limit the build time.
359 bool IsHugeFunc = false;
360
361 /// FreshBBs is like worklist, it collected the updated BBs which need
362 /// to be optimized again.
363 /// Note: Consider building time in this pass, when a BB updated, we need
364 /// to insert such BB into FreshBBs for huge function.
365 SmallSet<BasicBlock *, 32> FreshBBs;
366
367 static char ID; // Pass identification, replacement for typeid
368
369 CodeGenPrepare() : FunctionPass(ID) {
370 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
371 }
372
373 bool runOnFunction(Function &F) override;
374
375 StringRef getPassName() const override { return "CodeGen Prepare"; }
376
377 void getAnalysisUsage(AnalysisUsage &AU) const override {
378 // FIXME: When we can selectively preserve passes, preserve the domtree.
379 AU.addRequired<ProfileSummaryInfoWrapperPass>();
380 AU.addRequired<TargetLibraryInfoWrapperPass>();
381 AU.addRequired<TargetPassConfig>();
382 AU.addRequired<TargetTransformInfoWrapperPass>();
383 AU.addRequired<LoopInfoWrapperPass>();
384 AU.addUsedIfAvailable<BasicBlockSectionsProfileReader>();
385 }
386
387private:
388 template <typename F>
389 void resetIteratorIfInvalidatedWhileCalling(BasicBlock *BB, F f) {
390 // Substituting can cause recursive simplifications, which can invalidate
391 // our iterator. Use a WeakTrackingVH to hold onto it in case this
392 // happens.
393 Value *CurValue = &*CurInstIterator;
394 WeakTrackingVH IterHandle(CurValue);
395
396 f();
397
398 // If the iterator instruction was recursively deleted, start over at the
399 // start of the block.
400 if (IterHandle != CurValue) {
401 CurInstIterator = BB->begin();
402 SunkAddrs.clear();
403 }
404 }
405
406 // Get the DominatorTree, building if necessary.
407 DominatorTree &getDT(Function &F) {
408 if (!DT)
409 DT = std::make_unique<DominatorTree>(F);
410 return *DT;
411 }
412
413 void removeAllAssertingVHReferences(Value *V);
414 bool eliminateAssumptions(Function &F);
415 bool eliminateFallThrough(Function &F);
416 bool eliminateMostlyEmptyBlocks(Function &F);
417 BasicBlock *findDestBlockOfMergeableEmptyBlock(BasicBlock *BB);
418 bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
419 void eliminateMostlyEmptyBlock(BasicBlock *BB);
420 bool isMergingEmptyBlockProfitable(BasicBlock *BB, BasicBlock *DestBB,
421 bool isPreheader);
422 bool makeBitReverse(Instruction &I);
423 bool optimizeBlock(BasicBlock &BB, ModifyDT &ModifiedDT);
424 bool optimizeInst(Instruction *I, ModifyDT &ModifiedDT);
425 bool optimizeMemoryInst(Instruction *MemoryInst, Value *Addr, Type *AccessTy,
426 unsigned AddrSpace);
427 bool optimizeGatherScatterInst(Instruction *MemoryInst, Value *Ptr);
428 bool optimizeInlineAsmInst(CallInst *CS);
429 bool optimizeCallInst(CallInst *CI, ModifyDT &ModifiedDT);
430 bool optimizeExt(Instruction *&I);
431 bool optimizeExtUses(Instruction *I);
432 bool optimizeLoadExt(LoadInst *Load);
433 bool optimizeShiftInst(BinaryOperator *BO);
434 bool optimizeFunnelShift(IntrinsicInst *Fsh);
435 bool optimizeSelectInst(SelectInst *SI);
436 bool optimizeShuffleVectorInst(ShuffleVectorInst *SVI);
437 bool optimizeSwitchType(SwitchInst *SI);
438 bool optimizeSwitchPhiConstants(SwitchInst *SI);
439 bool optimizeSwitchInst(SwitchInst *SI);
440 bool optimizeExtractElementInst(Instruction *Inst);
441 bool dupRetToEnableTailCallOpts(BasicBlock *BB, ModifyDT &ModifiedDT);
442 bool fixupDbgValue(Instruction *I);
443 bool placeDbgValues(Function &F);
444 bool placePseudoProbes(Function &F);
445 bool canFormExtLd(const SmallVectorImpl<Instruction *> &MovedExts,
446 LoadInst *&LI, Instruction *&Inst, bool HasPromoted);
447 bool tryToPromoteExts(TypePromotionTransaction &TPT,
448 const SmallVectorImpl<Instruction *> &Exts,
449 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
450 unsigned CreatedInstsCost = 0);
451 bool mergeSExts(Function &F);
452 bool splitLargeGEPOffsets();
453 bool optimizePhiType(PHINode *Inst, SmallPtrSetImpl<PHINode *> &Visited,
454 SmallPtrSetImpl<Instruction *> &DeletedInstrs);
455 bool optimizePhiTypes(Function &F);
456 bool performAddressTypePromotion(
457 Instruction *&Inst, bool AllowPromotionWithoutCommonHeader,
458 bool HasPromoted, TypePromotionTransaction &TPT,
459 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts);
460 bool splitBranchCondition(Function &F, ModifyDT &ModifiedDT);
461 bool simplifyOffsetableRelocate(GCStatepointInst &I);
462
463 bool tryToSinkFreeOperands(Instruction *I);
464 bool replaceMathCmpWithIntrinsic(BinaryOperator *BO, Value *Arg0, Value *Arg1,
465 CmpInst *Cmp, Intrinsic::ID IID);
466 bool optimizeCmp(CmpInst *Cmp, ModifyDT &ModifiedDT);
467 bool combineToUSubWithOverflow(CmpInst *Cmp, ModifyDT &ModifiedDT);
468 bool combineToUAddWithOverflow(CmpInst *Cmp, ModifyDT &ModifiedDT);
469 void verifyBFIUpdates(Function &F);
470};
471
472} // end anonymous namespace
473
474char CodeGenPrepare::ID = 0;
475
476INITIALIZE_PASS_BEGIN(CodeGenPrepare, DEBUG_TYPE,static void *initializeCodeGenPreparePassOnce(PassRegistry &
Registry) {
477 "Optimize for code generation", false, false)static void *initializeCodeGenPreparePassOnce(PassRegistry &
Registry) {
478INITIALIZE_PASS_DEPENDENCY(BasicBlockSectionsProfileReader)initializeBasicBlockSectionsProfileReaderPass(Registry);
479INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)initializeLoopInfoWrapperPassPass(Registry);
480INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)initializeProfileSummaryInfoWrapperPassPass(Registry);
481INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)initializeTargetLibraryInfoWrapperPassPass(Registry);
482INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)initializeTargetPassConfigPass(Registry);
483INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)initializeTargetTransformInfoWrapperPassPass(Registry);
484INITIALIZE_PASS_END(CodeGenPrepare, DEBUG_TYPE, "Optimize for code generation",PassInfo *PI = new PassInfo( "Optimize for code generation", "codegenprepare"
, &CodeGenPrepare::ID, PassInfo::NormalCtor_t(callDefaultCtor
<CodeGenPrepare>), false, false); Registry.registerPass
(*PI, true); return PI; } static llvm::once_flag InitializeCodeGenPreparePassFlag
; void llvm::initializeCodeGenPreparePass(PassRegistry &Registry
) { llvm::call_once(InitializeCodeGenPreparePassFlag, initializeCodeGenPreparePassOnce
, std::ref(Registry)); }
485 false, false)PassInfo *PI = new PassInfo( "Optimize for code generation", "codegenprepare"
, &CodeGenPrepare::ID, PassInfo::NormalCtor_t(callDefaultCtor
<CodeGenPrepare>), false, false); Registry.registerPass
(*PI, true); return PI; } static llvm::once_flag InitializeCodeGenPreparePassFlag
; void llvm::initializeCodeGenPreparePass(PassRegistry &Registry
) { llvm::call_once(InitializeCodeGenPreparePassFlag, initializeCodeGenPreparePassOnce
, std::ref(Registry)); }
486
487FunctionPass *llvm::createCodeGenPreparePass() { return new CodeGenPrepare(); }
488
489bool CodeGenPrepare::runOnFunction(Function &F) {
490 if (skipFunction(F))
491 return false;
492
493 DL = &F.getParent()->getDataLayout();
494
495 bool EverMadeChange = false;
496 // Clear per function information.
497 InsertedInsts.clear();
498 PromotedInsts.clear();
499 FreshBBs.clear();
500
501 TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
502 SubtargetInfo = TM->getSubtargetImpl(F);
503 TLI = SubtargetInfo->getTargetLowering();
504 TRI = SubtargetInfo->getRegisterInfo();
505 TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
506 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
507 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
508 BPI.reset(new BranchProbabilityInfo(F, *LI));
509 BFI.reset(new BlockFrequencyInfo(F, *BPI, *LI));
510 PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
511 BBSectionsProfileReader =
512 getAnalysisIfAvailable<BasicBlockSectionsProfileReader>();
513 OptSize = F.hasOptSize();
514 // Use the basic-block-sections profile to promote hot functions to .text.hot
515 // if requested.
516 if (BBSectionsGuidedSectionPrefix && BBSectionsProfileReader &&
517 BBSectionsProfileReader->isFunctionHot(F.getName())) {
518 F.setSectionPrefix("hot");
519 } else if (ProfileGuidedSectionPrefix) {
520 // The hot attribute overwrites profile count based hotness while profile
521 // counts based hotness overwrite the cold attribute.
522 // This is a conservative behabvior.
523 if (F.hasFnAttribute(Attribute::Hot) ||
524 PSI->isFunctionHotInCallGraph(&F, *BFI))
525 F.setSectionPrefix("hot");
526 // If PSI shows this function is not hot, we will placed the function
527 // into unlikely section if (1) PSI shows this is a cold function, or
528 // (2) the function has a attribute of cold.
529 else if (PSI->isFunctionColdInCallGraph(&F, *BFI) ||
530 F.hasFnAttribute(Attribute::Cold))
531 F.setSectionPrefix("unlikely");
532 else if (ProfileUnknownInSpecialSection && PSI->hasPartialSampleProfile() &&
533 PSI->isFunctionHotnessUnknown(F))
534 F.setSectionPrefix("unknown");
535 }
536
537 /// This optimization identifies DIV instructions that can be
538 /// profitably bypassed and carried out with a shorter, faster divide.
539 if (!OptSize && !PSI->hasHugeWorkingSetSize() && TLI->isSlowDivBypassed()) {
540 const DenseMap<unsigned int, unsigned int> &BypassWidths =
541 TLI->getBypassSlowDivWidths();
542 BasicBlock *BB = &*F.begin();
543 while (BB != nullptr) {
544 // bypassSlowDivision may create new BBs, but we don't want to reapply the
545 // optimization to those blocks.
546 BasicBlock *Next = BB->getNextNode();
547 // F.hasOptSize is already checked in the outer if statement.
548 if (!llvm::shouldOptimizeForSize(BB, PSI, BFI.get()))
549 EverMadeChange |= bypassSlowDivision(BB, BypassWidths);
550 BB = Next;
551 }
552 }
553
554 // Get rid of @llvm.assume builtins before attempting to eliminate empty
555 // blocks, since there might be blocks that only contain @llvm.assume calls
556 // (plus arguments that we can get rid of).
557 EverMadeChange |= eliminateAssumptions(F);
558
559 // Eliminate blocks that contain only PHI nodes and an
560 // unconditional branch.
561 EverMadeChange |= eliminateMostlyEmptyBlocks(F);
562
563 ModifyDT ModifiedDT = ModifyDT::NotModifyDT;
564 if (!DisableBranchOpts)
565 EverMadeChange |= splitBranchCondition(F, ModifiedDT);
566
567 // Split some critical edges where one of the sources is an indirect branch,
568 // to help generate sane code for PHIs involving such edges.
569 EverMadeChange |=
570 SplitIndirectBrCriticalEdges(F, /*IgnoreBlocksWithoutPHI=*/true);
571
572 // If we are optimzing huge function, we need to consider the build time.
573 // Because the basic algorithm's complex is near O(N!).
574 IsHugeFunc = F.size() > HugeFuncThresholdInCGPP;
575
576 bool MadeChange = true;
577 bool FuncIterated = false;
578 while (MadeChange) {
579 MadeChange = false;
580 DT.reset();
581
582 for (BasicBlock &BB : llvm::make_early_inc_range(F)) {
583 if (FuncIterated && !FreshBBs.contains(&BB))
584 continue;
585
586 ModifyDT ModifiedDTOnIteration = ModifyDT::NotModifyDT;
587 bool Changed = optimizeBlock(BB, ModifiedDTOnIteration);
588
589 MadeChange |= Changed;
590 if (IsHugeFunc) {
591 // If the BB is updated, it may still has chance to be optimized.
592 // This usually happen at sink optimization.
593 // For example:
594 //
595 // bb0:
596 // %and = and i32 %a, 4
597 // %cmp = icmp eq i32 %and, 0
598 //
599 // If the %cmp sink to other BB, the %and will has chance to sink.
600 if (Changed)
601 FreshBBs.insert(&BB);
602 else if (FuncIterated)
603 FreshBBs.erase(&BB);
604
605 if (ModifiedDTOnIteration == ModifyDT::ModifyBBDT)
606 DT.reset();
607 } else {
608 // For small/normal functions, we restart BB iteration if the dominator
609 // tree of the Function was changed.
610 if (ModifiedDTOnIteration != ModifyDT::NotModifyDT)
611 break;
612 }
613 }
614 // We have iterated all the BB in the (only work for huge) function.
615 FuncIterated = IsHugeFunc;
616
617 if (EnableTypePromotionMerge && !ValToSExtendedUses.empty())
618 MadeChange |= mergeSExts(F);
619 if (!LargeOffsetGEPMap.empty())
620 MadeChange |= splitLargeGEPOffsets();
621 MadeChange |= optimizePhiTypes(F);
622
623 if (MadeChange)
624 eliminateFallThrough(F);
625
626 // Really free removed instructions during promotion.
627 for (Instruction *I : RemovedInsts)
628 I->deleteValue();
629
630 EverMadeChange |= MadeChange;
631 SeenChainsForSExt.clear();
632 ValToSExtendedUses.clear();
633 RemovedInsts.clear();
634 LargeOffsetGEPMap.clear();
635 LargeOffsetGEPID.clear();
636 }
637
638 NewGEPBases.clear();
639 SunkAddrs.clear();
640
641 if (!DisableBranchOpts) {
642 MadeChange = false;
643 // Use a set vector to get deterministic iteration order. The order the
644 // blocks are removed may affect whether or not PHI nodes in successors
645 // are removed.
646 SmallSetVector<BasicBlock *, 8> WorkList;
647 for (BasicBlock &BB : F) {
648 SmallVector<BasicBlock *, 2> Successors(successors(&BB));
649 MadeChange |= ConstantFoldTerminator(&BB, true);
650 if (!MadeChange)
651 continue;
652
653 for (BasicBlock *Succ : Successors)
654 if (pred_empty(Succ))
655 WorkList.insert(Succ);
656 }
657
658 // Delete the dead blocks and any of their dead successors.
659 MadeChange |= !WorkList.empty();
660 while (!WorkList.empty()) {
661 BasicBlock *BB = WorkList.pop_back_val();
662 SmallVector<BasicBlock *, 2> Successors(successors(BB));
663
664 DeleteDeadBlock(BB);
665
666 for (BasicBlock *Succ : Successors)
667 if (pred_empty(Succ))
668 WorkList.insert(Succ);
669 }
670
671 // Merge pairs of basic blocks with unconditional branches, connected by
672 // a single edge.
673 if (EverMadeChange || MadeChange)
674 MadeChange |= eliminateFallThrough(F);
675
676 EverMadeChange |= MadeChange;
677 }
678
679 if (!DisableGCOpts) {
680 SmallVector<GCStatepointInst *, 2> Statepoints;
681 for (BasicBlock &BB : F)
682 for (Instruction &I : BB)
683 if (auto *SP = dyn_cast<GCStatepointInst>(&I))
684 Statepoints.push_back(SP);
685 for (auto &I : Statepoints)
686 EverMadeChange |= simplifyOffsetableRelocate(*I);
687 }
688
689 // Do this last to clean up use-before-def scenarios introduced by other
690 // preparatory transforms.
691 EverMadeChange |= placeDbgValues(F);
692 EverMadeChange |= placePseudoProbes(F);
693
694#ifndef NDEBUG
695 if (VerifyBFIUpdates)
696 verifyBFIUpdates(F);
697#endif
698
699 return EverMadeChange;
700}
701
702bool CodeGenPrepare::eliminateAssumptions(Function &F) {
703 bool MadeChange = false;
704 for (BasicBlock &BB : F) {
705 CurInstIterator = BB.begin();
706 while (CurInstIterator != BB.end()) {
707 Instruction *I = &*(CurInstIterator++);
708 if (auto *Assume = dyn_cast<AssumeInst>(I)) {
709 MadeChange = true;
710 Value *Operand = Assume->getOperand(0);
711 Assume->eraseFromParent();
712
713 resetIteratorIfInvalidatedWhileCalling(&BB, [&]() {
714 RecursivelyDeleteTriviallyDeadInstructions(Operand, TLInfo, nullptr);
715 });
716 }
717 }
718 }
719 return MadeChange;
720}
721
722/// An instruction is about to be deleted, so remove all references to it in our
723/// GEP-tracking data strcutures.
724void CodeGenPrepare::removeAllAssertingVHReferences(Value *V) {
725 LargeOffsetGEPMap.erase(V);
726 NewGEPBases.erase(V);
727
728 auto GEP = dyn_cast<GetElementPtrInst>(V);
729 if (!GEP)
730 return;
731
732 LargeOffsetGEPID.erase(GEP);
733
734 auto VecI = LargeOffsetGEPMap.find(GEP->getPointerOperand());
735 if (VecI == LargeOffsetGEPMap.end())
736 return;
737
738 auto &GEPVector = VecI->second;
739 llvm::erase_if(GEPVector, [=](auto &Elt) { return Elt.first == GEP; });
740
741 if (GEPVector.empty())
742 LargeOffsetGEPMap.erase(VecI);
743}
744
745// Verify BFI has been updated correctly by recomputing BFI and comparing them.
746void LLVM_ATTRIBUTE_UNUSED__attribute__((__unused__)) CodeGenPrepare::verifyBFIUpdates(Function &F) {
747 DominatorTree NewDT(F);
748 LoopInfo NewLI(NewDT);
749 BranchProbabilityInfo NewBPI(F, NewLI, TLInfo);
750 BlockFrequencyInfo NewBFI(F, NewBPI, NewLI);
751 NewBFI.verifyMatch(*BFI);
752}
753
754/// Merge basic blocks which are connected by a single edge, where one of the
755/// basic blocks has a single successor pointing to the other basic block,
756/// which has a single predecessor.
757bool CodeGenPrepare::eliminateFallThrough(Function &F) {
758 bool Changed = false;
759 // Scan all of the blocks in the function, except for the entry block.
760 // Use a temporary array to avoid iterator being invalidated when
761 // deleting blocks.
762 SmallVector<WeakTrackingVH, 16> Blocks;
763 for (auto &Block : llvm::drop_begin(F))
764 Blocks.push_back(&Block);
765
766 SmallSet<WeakTrackingVH, 16> Preds;
767 for (auto &Block : Blocks) {
768 auto *BB = cast_or_null<BasicBlock>(Block);
769 if (!BB)
770 continue;
771 // If the destination block has a single pred, then this is a trivial
772 // edge, just collapse it.
773 BasicBlock *SinglePred = BB->getSinglePredecessor();
774
775 // Don't merge if BB's address is taken.
776 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken())
777 continue;
778
779 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
780 if (Term && !Term->isConditional()) {
781 Changed = true;
782 LLVM_DEBUG(dbgs() << "To merge:\n" << *BB << "\n\n\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "To merge:\n" << *
BB << "\n\n\n"; } } while (false)
;
783
784 // Merge BB into SinglePred and delete it.
785 MergeBlockIntoPredecessor(BB);
786 Preds.insert(SinglePred);
787
788 if (IsHugeFunc) {
789 // Update FreshBBs to optimize the merged BB.
790 FreshBBs.insert(SinglePred);
791 FreshBBs.erase(BB);
792 }
793 }
794 }
795
796 // (Repeatedly) merging blocks into their predecessors can create redundant
797 // debug intrinsics.
798 for (const auto &Pred : Preds)
799 if (auto *BB = cast_or_null<BasicBlock>(Pred))
800 RemoveRedundantDbgInstrs(BB);
801
802 return Changed;
803}
804
805/// Find a destination block from BB if BB is mergeable empty block.
806BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) {
807 // If this block doesn't end with an uncond branch, ignore it.
808 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
809 if (!BI || !BI->isUnconditional())
810 return nullptr;
811
812 // If the instruction before the branch (skipping debug info) isn't a phi
813 // node, then other stuff is happening here.
814 BasicBlock::iterator BBI = BI->getIterator();
815 if (BBI != BB->begin()) {
816 --BBI;
817 while (isa<DbgInfoIntrinsic>(BBI)) {
818 if (BBI == BB->begin())
819 break;
820 --BBI;
821 }
822 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
823 return nullptr;
824 }
825
826 // Do not break infinite loops.
827 BasicBlock *DestBB = BI->getSuccessor(0);
828 if (DestBB == BB)
829 return nullptr;
830
831 if (!canMergeBlocks(BB, DestBB))
832 DestBB = nullptr;
833
834 return DestBB;
835}
836
837/// Eliminate blocks that contain only PHI nodes, debug info directives, and an
838/// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
839/// edges in ways that are non-optimal for isel. Start by eliminating these
840/// blocks so we can split them the way we want them.
841bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
842 SmallPtrSet<BasicBlock *, 16> Preheaders;
843 SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end());
844 while (!LoopList.empty()) {
845 Loop *L = LoopList.pop_back_val();
846 llvm::append_range(LoopList, *L);
847 if (BasicBlock *Preheader = L->getLoopPreheader())
848 Preheaders.insert(Preheader);
849 }
850
851 bool MadeChange = false;
852 // Copy blocks into a temporary array to avoid iterator invalidation issues
853 // as we remove them.
854 // Note that this intentionally skips the entry block.
855 SmallVector<WeakTrackingVH, 16> Blocks;
856 for (auto &Block : llvm::drop_begin(F))
857 Blocks.push_back(&Block);
858
859 for (auto &Block : Blocks) {
860 BasicBlock *BB = cast_or_null<BasicBlock>(Block);
861 if (!BB)
862 continue;
863 BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB);
864 if (!DestBB ||
865 !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.count(BB)))
866 continue;
867
868 eliminateMostlyEmptyBlock(BB);
869 MadeChange = true;
870 }
871 return MadeChange;
872}
873
874bool CodeGenPrepare::isMergingEmptyBlockProfitable(BasicBlock *BB,
875 BasicBlock *DestBB,
876 bool isPreheader) {
877 // Do not delete loop preheaders if doing so would create a critical edge.
878 // Loop preheaders can be good locations to spill registers. If the
879 // preheader is deleted and we create a critical edge, registers may be
880 // spilled in the loop body instead.
881 if (!DisablePreheaderProtect && isPreheader &&
882 !(BB->getSinglePredecessor() &&
883 BB->getSinglePredecessor()->getSingleSuccessor()))
884 return false;
885
886 // Skip merging if the block's successor is also a successor to any callbr
887 // that leads to this block.
888 // FIXME: Is this really needed? Is this a correctness issue?
889 for (BasicBlock *Pred : predecessors(BB)) {
890 if (auto *CBI = dyn_cast<CallBrInst>((Pred)->getTerminator()))
891 for (unsigned i = 0, e = CBI->getNumSuccessors(); i != e; ++i)
892 if (DestBB == CBI->getSuccessor(i))
893 return false;
894 }
895
896 // Try to skip merging if the unique predecessor of BB is terminated by a
897 // switch or indirect branch instruction, and BB is used as an incoming block
898 // of PHIs in DestBB. In such case, merging BB and DestBB would cause ISel to
899 // add COPY instructions in the predecessor of BB instead of BB (if it is not
900 // merged). Note that the critical edge created by merging such blocks wont be
901 // split in MachineSink because the jump table is not analyzable. By keeping
902 // such empty block (BB), ISel will place COPY instructions in BB, not in the
903 // predecessor of BB.
904 BasicBlock *Pred = BB->getUniquePredecessor();
905 if (!Pred || !(isa<SwitchInst>(Pred->getTerminator()) ||
906 isa<IndirectBrInst>(Pred->getTerminator())))
907 return true;
908
909 if (BB->getTerminator() != BB->getFirstNonPHIOrDbg())
910 return true;
911
912 // We use a simple cost heuristic which determine skipping merging is
913 // profitable if the cost of skipping merging is less than the cost of
914 // merging : Cost(skipping merging) < Cost(merging BB), where the
915 // Cost(skipping merging) is Freq(BB) * (Cost(Copy) + Cost(Branch)), and
916 // the Cost(merging BB) is Freq(Pred) * Cost(Copy).
917 // Assuming Cost(Copy) == Cost(Branch), we could simplify it to :
918 // Freq(Pred) / Freq(BB) > 2.
919 // Note that if there are multiple empty blocks sharing the same incoming
920 // value for the PHIs in the DestBB, we consider them together. In such
921 // case, Cost(merging BB) will be the sum of their frequencies.
922
923 if (!isa<PHINode>(DestBB->begin()))
924 return true;
925
926 SmallPtrSet<BasicBlock *, 16> SameIncomingValueBBs;
927
928 // Find all other incoming blocks from which incoming values of all PHIs in
929 // DestBB are the same as the ones from BB.
930 for (BasicBlock *DestBBPred : predecessors(DestBB)) {
931 if (DestBBPred == BB)
932 continue;
933
934 if (llvm::all_of(DestBB->phis(), [&](const PHINode &DestPN) {
935 return DestPN.getIncomingValueForBlock(BB) ==
936 DestPN.getIncomingValueForBlock(DestBBPred);
937 }))
938 SameIncomingValueBBs.insert(DestBBPred);
939 }
940
941 // See if all BB's incoming values are same as the value from Pred. In this
942 // case, no reason to skip merging because COPYs are expected to be place in
943 // Pred already.
944 if (SameIncomingValueBBs.count(Pred))
945 return true;
946
947 BlockFrequency PredFreq = BFI->getBlockFreq(Pred);
948 BlockFrequency BBFreq = BFI->getBlockFreq(BB);
949
950 for (auto *SameValueBB : SameIncomingValueBBs)
951 if (SameValueBB->getUniquePredecessor() == Pred &&
952 DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB))
953 BBFreq += BFI->getBlockFreq(SameValueBB);
954
955 return PredFreq.getFrequency() <=
956 BBFreq.getFrequency() * FreqRatioToSkipMerge;
957}
958
959/// Return true if we can merge BB into DestBB if there is a single
960/// unconditional branch between them, and BB contains no other non-phi
961/// instructions.
962bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
963 const BasicBlock *DestBB) const {
964 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
965 // the successor. If there are more complex condition (e.g. preheaders),
966 // don't mess around with them.
967 for (const PHINode &PN : BB->phis()) {
968 for (const User *U : PN.users()) {
969 const Instruction *UI = cast<Instruction>(U);
970 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
971 return false;
972 // If User is inside DestBB block and it is a PHINode then check
973 // incoming value. If incoming value is not from BB then this is
974 // a complex condition (e.g. preheaders) we want to avoid here.
975 if (UI->getParent() == DestBB) {
976 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
977 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
978 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
979 if (Insn && Insn->getParent() == BB &&
980 Insn->getParent() != UPN->getIncomingBlock(I))
981 return false;
982 }
983 }
984 }
985 }
986
987 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
988 // and DestBB may have conflicting incoming values for the block. If so, we
989 // can't merge the block.
990 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
991 if (!DestBBPN)
992 return true; // no conflict.
993
994 // Collect the preds of BB.
995 SmallPtrSet<const BasicBlock *, 16> BBPreds;
996 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
997 // It is faster to get preds from a PHI than with pred_iterator.
998 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
999 BBPreds.insert(BBPN->getIncomingBlock(i));
1000 } else {
1001 BBPreds.insert(pred_begin(BB), pred_end(BB));
1002 }
1003
1004 // Walk the preds of DestBB.
1005 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
1006 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
1007 if (BBPreds.count(Pred)) { // Common predecessor?
1008 for (const PHINode &PN : DestBB->phis()) {
1009 const Value *V1 = PN.getIncomingValueForBlock(Pred);
1010 const Value *V2 = PN.getIncomingValueForBlock(BB);
1011
1012 // If V2 is a phi node in BB, look up what the mapped value will be.
1013 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
1014 if (V2PN->getParent() == BB)
1015 V2 = V2PN->getIncomingValueForBlock(Pred);
1016
1017 // If there is a conflict, bail out.
1018 if (V1 != V2)
1019 return false;
1020 }
1021 }
1022 }
1023
1024 return true;
1025}
1026
1027/// Replace all old uses with new ones, and push the updated BBs into FreshBBs.
1028static void replaceAllUsesWith(Value *Old, Value *New,
1029 SmallSet<BasicBlock *, 32> &FreshBBs,
1030 bool IsHuge) {
1031 auto *OldI = dyn_cast<Instruction>(Old);
1032 if (OldI) {
1033 for (Value::user_iterator UI = OldI->user_begin(), E = OldI->user_end();
1034 UI != E; ++UI) {
1035 Instruction *User = cast<Instruction>(*UI);
1036 if (IsHuge)
1037 FreshBBs.insert(User->getParent());
1038 }
1039 }
1040 Old->replaceAllUsesWith(New);
1041}
1042
1043/// Eliminate a basic block that has only phi's and an unconditional branch in
1044/// it.
1045void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
1046 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
1047 BasicBlock *DestBB = BI->getSuccessor(0);
1048
1049 LLVM_DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n"
<< *BB << *DestBB; } } while (false)
1050 << *BB << *DestBB)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n"
<< *BB << *DestBB; } } while (false)
;
1051
1052 // If the destination block has a single pred, then this is a trivial edge,
1053 // just collapse it.
1054 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
1055 if (SinglePred != DestBB) {
1056 assert(SinglePred == BB &&(static_cast <bool> (SinglePred == BB && "Single predecessor not the same as predecessor"
) ? void (0) : __assert_fail ("SinglePred == BB && \"Single predecessor not the same as predecessor\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 1057, __extension__ __PRETTY_FUNCTION__
))
1057 "Single predecessor not the same as predecessor")(static_cast <bool> (SinglePred == BB && "Single predecessor not the same as predecessor"
) ? void (0) : __assert_fail ("SinglePred == BB && \"Single predecessor not the same as predecessor\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 1057, __extension__ __PRETTY_FUNCTION__
))
;
1058 // Merge DestBB into SinglePred/BB and delete it.
1059 MergeBlockIntoPredecessor(DestBB);
1060 // Note: BB(=SinglePred) will not be deleted on this path.
1061 // DestBB(=its single successor) is the one that was deleted.
1062 LLVM_DEBUG(dbgs() << "AFTER:\n" << *SinglePred << "\n\n\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "AFTER:\n" << *SinglePred
<< "\n\n\n"; } } while (false)
;
1063
1064 if (IsHugeFunc) {
1065 // Update FreshBBs to optimize the merged BB.
1066 FreshBBs.insert(SinglePred);
1067 FreshBBs.erase(DestBB);
1068 }
1069 return;
1070 }
1071 }
1072
1073 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
1074 // to handle the new incoming edges it is about to have.
1075 for (PHINode &PN : DestBB->phis()) {
1076 // Remove the incoming value for BB, and remember it.
1077 Value *InVal = PN.removeIncomingValue(BB, false);
1078
1079 // Two options: either the InVal is a phi node defined in BB or it is some
1080 // value that dominates BB.
1081 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
1082 if (InValPhi && InValPhi->getParent() == BB) {
1083 // Add all of the input values of the input PHI as inputs of this phi.
1084 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
1085 PN.addIncoming(InValPhi->getIncomingValue(i),
1086 InValPhi->getIncomingBlock(i));
1087 } else {
1088 // Otherwise, add one instance of the dominating value for each edge that
1089 // we will be adding.
1090 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
1091 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
1092 PN.addIncoming(InVal, BBPN->getIncomingBlock(i));
1093 } else {
1094 for (BasicBlock *Pred : predecessors(BB))
1095 PN.addIncoming(InVal, Pred);
1096 }
1097 }
1098 }
1099
1100 // The PHIs are now updated, change everything that refers to BB to use
1101 // DestBB and remove BB.
1102 BB->replaceAllUsesWith(DestBB);
1103 BB->eraseFromParent();
1104 ++NumBlocksElim;
1105
1106 LLVM_DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "AFTER:\n" << *DestBB
<< "\n\n\n"; } } while (false)
;
1107}
1108
1109// Computes a map of base pointer relocation instructions to corresponding
1110// derived pointer relocation instructions given a vector of all relocate calls
1111static void computeBaseDerivedRelocateMap(
1112 const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
1113 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>>
1114 &RelocateInstMap) {
1115 // Collect information in two maps: one primarily for locating the base object
1116 // while filling the second map; the second map is the final structure holding
1117 // a mapping between Base and corresponding Derived relocate calls
1118 DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap;
1119 for (auto *ThisRelocate : AllRelocateCalls) {
1120 auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
1121 ThisRelocate->getDerivedPtrIndex());
1122 RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
1123 }
1124 for (auto &Item : RelocateIdxMap) {
1125 std::pair<unsigned, unsigned> Key = Item.first;
1126 if (Key.first == Key.second)
1127 // Base relocation: nothing to insert
1128 continue;
1129
1130 GCRelocateInst *I = Item.second;
1131 auto BaseKey = std::make_pair(Key.first, Key.first);
1132
1133 // We're iterating over RelocateIdxMap so we cannot modify it.
1134 auto MaybeBase = RelocateIdxMap.find(BaseKey);
1135 if (MaybeBase == RelocateIdxMap.end())
1136 // TODO: We might want to insert a new base object relocate and gep off
1137 // that, if there are enough derived object relocates.
1138 continue;
1139
1140 RelocateInstMap[MaybeBase->second].push_back(I);
1141 }
1142}
1143
1144// Accepts a GEP and extracts the operands into a vector provided they're all
1145// small integer constants
1146static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
1147 SmallVectorImpl<Value *> &OffsetV) {
1148 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
1149 // Only accept small constant integer operands
1150 auto *Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
1151 if (!Op || Op->getZExtValue() > 20)
1152 return false;
1153 }
1154
1155 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
1156 OffsetV.push_back(GEP->getOperand(i));
1157 return true;
1158}
1159
1160// Takes a RelocatedBase (base pointer relocation instruction) and Targets to
1161// replace, computes a replacement, and affects it.
1162static bool
1163simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase,
1164 const SmallVectorImpl<GCRelocateInst *> &Targets) {
1165 bool MadeChange = false;
1166 // We must ensure the relocation of derived pointer is defined after
1167 // relocation of base pointer. If we find a relocation corresponding to base
1168 // defined earlier than relocation of base then we move relocation of base
1169 // right before found relocation. We consider only relocation in the same
1170 // basic block as relocation of base. Relocations from other basic block will
1171 // be skipped by optimization and we do not care about them.
1172 for (auto R = RelocatedBase->getParent()->getFirstInsertionPt();
7
Loop condition is false. Execution continues on line 1181
1173 &*R != RelocatedBase; ++R)
6
Assuming the condition is false
1174 if (auto *RI = dyn_cast<GCRelocateInst>(R))
1175 if (RI->getStatepoint() == RelocatedBase->getStatepoint())
1176 if (RI->getBasePtrIndex() == RelocatedBase->getBasePtrIndex()) {
1177 RelocatedBase->moveBefore(RI);
1178 break;
1179 }
1180
1181 for (GCRelocateInst *ToReplace : Targets) {
8
Assuming '__begin1' is not equal to '__end1'
1182 assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&(static_cast <bool> (ToReplace->getBasePtrIndex() ==
RelocatedBase->getBasePtrIndex() && "Not relocating a derived object of the original base object"
) ? void (0) : __assert_fail ("ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() && \"Not relocating a derived object of the original base object\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 1183, __extension__ __PRETTY_FUNCTION__
))
9
Assuming the condition is true
10
'?' condition is true
1183 "Not relocating a derived object of the original base object")(static_cast <bool> (ToReplace->getBasePtrIndex() ==
RelocatedBase->getBasePtrIndex() && "Not relocating a derived object of the original base object"
) ? void (0) : __assert_fail ("ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() && \"Not relocating a derived object of the original base object\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 1183, __extension__ __PRETTY_FUNCTION__
))
;
1184 if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
11
Assuming the condition is false
12
Taking false branch
1185 // A duplicate relocate call. TODO: coalesce duplicates.
1186 continue;
1187 }
1188
1189 if (RelocatedBase->getParent() != ToReplace->getParent()) {
13
Assuming the condition is false
14
Taking false branch
1190 // Base and derived relocates are in different basic blocks.
1191 // In this case transform is only valid when base dominates derived
1192 // relocate. However it would be too expensive to check dominance
1193 // for each such relocate, so we skip the whole transformation.
1194 continue;
1195 }
1196
1197 Value *Base = ToReplace->getBasePtr();
15
'Base' initialized here
1198 auto *Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
16
Assuming the object is a 'CastReturnType'
1199 if (!Derived
16.1
'Derived' is non-null
|| Derived->getPointerOperand() != Base)
17
Assuming pointer value is null
18
Taking false branch
1200 continue;
1201
1202 SmallVector<Value *, 2> OffsetV;
1203 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
1204 continue;
1205
1206 // Create a Builder and replace the target callsite with a gep
1207 assert(RelocatedBase->getNextNode() &&(static_cast <bool> (RelocatedBase->getNextNode() &&
"Should always have one since it's not a terminator") ? void
(0) : __assert_fail ("RelocatedBase->getNextNode() && \"Should always have one since it's not a terminator\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 1208, __extension__ __PRETTY_FUNCTION__
))
19
Taking false branch
20
Assuming the condition is true
21
'?' condition is true
1208 "Should always have one since it's not a terminator")(static_cast <bool> (RelocatedBase->getNextNode() &&
"Should always have one since it's not a terminator") ? void
(0) : __assert_fail ("RelocatedBase->getNextNode() && \"Should always have one since it's not a terminator\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 1208, __extension__ __PRETTY_FUNCTION__
))
;
1209
1210 // Insert after RelocatedBase
1211 IRBuilder<> Builder(RelocatedBase->getNextNode());
1212 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
1213
1214 // If gc_relocate does not match the actual type, cast it to the right type.
1215 // In theory, there must be a bitcast after gc_relocate if the type does not
1216 // match, and we should reuse it to get the derived pointer. But it could be
1217 // cases like this:
1218 // bb1:
1219 // ...
1220 // %g1 = call coldcc i8 addrspace(1)*
1221 // @llvm.experimental.gc.relocate.p1i8(...) br label %merge
1222 //
1223 // bb2:
1224 // ...
1225 // %g2 = call coldcc i8 addrspace(1)*
1226 // @llvm.experimental.gc.relocate.p1i8(...) br label %merge
1227 //
1228 // merge:
1229 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
1230 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
1231 //
1232 // In this case, we can not find the bitcast any more. So we insert a new
1233 // bitcast no matter there is already one or not. In this way, we can handle
1234 // all cases, and the extra bitcast should be optimized away in later
1235 // passes.
1236 Value *ActualRelocatedBase = RelocatedBase;
1237 if (RelocatedBase->getType() != Base->getType()) {
22
Called C++ object pointer is null
1238 ActualRelocatedBase =
1239 Builder.CreateBitCast(RelocatedBase, Base->getType());
1240 }
1241 Value *Replacement =
1242 Builder.CreateGEP(Derived->getSourceElementType(), ActualRelocatedBase,
1243 makeArrayRef(OffsetV));
1244 Replacement->takeName(ToReplace);
1245 // If the newly generated derived pointer's type does not match the original
1246 // derived pointer's type, cast the new derived pointer to match it. Same
1247 // reasoning as above.
1248 Value *ActualReplacement = Replacement;
1249 if (Replacement->getType() != ToReplace->getType()) {
1250 ActualReplacement =
1251 Builder.CreateBitCast(Replacement, ToReplace->getType());
1252 }
1253 ToReplace->replaceAllUsesWith(ActualReplacement);
1254 ToReplace->eraseFromParent();
1255
1256 MadeChange = true;
1257 }
1258 return MadeChange;
1259}
1260
1261// Turns this:
1262//
1263// %base = ...
1264// %ptr = gep %base + 15
1265// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1266// %base' = relocate(%tok, i32 4, i32 4)
1267// %ptr' = relocate(%tok, i32 4, i32 5)
1268// %val = load %ptr'
1269//
1270// into this:
1271//
1272// %base = ...
1273// %ptr = gep %base + 15
1274// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1275// %base' = gc.relocate(%tok, i32 4, i32 4)
1276// %ptr' = gep %base' + 15
1277// %val = load %ptr'
1278bool CodeGenPrepare::simplifyOffsetableRelocate(GCStatepointInst &I) {
1279 bool MadeChange = false;
1280 SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
1281 for (auto *U : I.users())
1282 if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
1283 // Collect all the relocate calls associated with a statepoint
1284 AllRelocateCalls.push_back(Relocate);
1285
1286 // We need at least one base pointer relocation + one derived pointer
1287 // relocation to mangle
1288 if (AllRelocateCalls.size() < 2)
1
Assuming the condition is false
2
Taking false branch
1289 return false;
1290
1291 // RelocateInstMap is a mapping from the base relocate instruction to the
1292 // corresponding derived relocate instructions
1293 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap;
1294 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
1295 if (RelocateInstMap.empty())
3
Assuming the condition is false
4
Taking false branch
1296 return false;
1297
1298 for (auto &Item : RelocateInstMap)
1299 // Item.first is the RelocatedBase to offset against
1300 // Item.second is the vector of Targets to replace
1301 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
5
Calling 'simplifyRelocatesOffABase'
1302 return MadeChange;
1303}
1304
1305/// Sink the specified cast instruction into its user blocks.
1306static bool SinkCast(CastInst *CI) {
1307 BasicBlock *DefBB = CI->getParent();
1308
1309 /// InsertedCasts - Only insert a cast in each block once.
1310 DenseMap<BasicBlock *, CastInst *> InsertedCasts;
1311
1312 bool MadeChange = false;
1313 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
1314 UI != E;) {
1315 Use &TheUse = UI.getUse();
1316 Instruction *User = cast<Instruction>(*UI);
1317
1318 // Figure out which BB this cast is used in. For PHI's this is the
1319 // appropriate predecessor block.
1320 BasicBlock *UserBB = User->getParent();
1321 if (PHINode *PN = dyn_cast<PHINode>(User)) {
1322 UserBB = PN->getIncomingBlock(TheUse);
1323 }
1324
1325 // Preincrement use iterator so we don't invalidate it.
1326 ++UI;
1327
1328 // The first insertion point of a block containing an EH pad is after the
1329 // pad. If the pad is the user, we cannot sink the cast past the pad.
1330 if (User->isEHPad())
1331 continue;
1332
1333 // If the block selected to receive the cast is an EH pad that does not
1334 // allow non-PHI instructions before the terminator, we can't sink the
1335 // cast.
1336 if (UserBB->getTerminator()->isEHPad())
1337 continue;
1338
1339 // If this user is in the same block as the cast, don't change the cast.
1340 if (UserBB == DefBB)
1341 continue;
1342
1343 // If we have already inserted a cast into this block, use it.
1344 CastInst *&InsertedCast = InsertedCasts[UserBB];
1345
1346 if (!InsertedCast) {
1347 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1348 assert(InsertPt != UserBB->end())(static_cast <bool> (InsertPt != UserBB->end()) ? void
(0) : __assert_fail ("InsertPt != UserBB->end()", "llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 1348, __extension__ __PRETTY_FUNCTION__))
;
1349 InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
1350 CI->getType(), "", &*InsertPt);
1351 InsertedCast->setDebugLoc(CI->getDebugLoc());
1352 }
1353
1354 // Replace a use of the cast with a use of the new cast.
1355 TheUse = InsertedCast;
1356 MadeChange = true;
1357 ++NumCastUses;
1358 }
1359
1360 // If we removed all uses, nuke the cast.
1361 if (CI->use_empty()) {
1362 salvageDebugInfo(*CI);
1363 CI->eraseFromParent();
1364 MadeChange = true;
1365 }
1366
1367 return MadeChange;
1368}
1369
1370/// If the specified cast instruction is a noop copy (e.g. it's casting from
1371/// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
1372/// reduce the number of virtual registers that must be created and coalesced.
1373///
1374/// Return true if any changes are made.
1375static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
1376 const DataLayout &DL) {
1377 // Sink only "cheap" (or nop) address-space casts. This is a weaker condition
1378 // than sinking only nop casts, but is helpful on some platforms.
1379 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(CI)) {
1380 if (!TLI.isFreeAddrSpaceCast(ASC->getSrcAddressSpace(),
1381 ASC->getDestAddressSpace()))
1382 return false;
1383 }
1384
1385 // If this is a noop copy,
1386 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
1387 EVT DstVT = TLI.getValueType(DL, CI->getType());
1388
1389 // This is an fp<->int conversion?
1390 if (SrcVT.isInteger() != DstVT.isInteger())
1391 return false;
1392
1393 // If this is an extension, it will be a zero or sign extension, which
1394 // isn't a noop.
1395 if (SrcVT.bitsLT(DstVT))
1396 return false;
1397
1398 // If these values will be promoted, find out what they will be promoted
1399 // to. This helps us consider truncates on PPC as noop copies when they
1400 // are.
1401 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
1402 TargetLowering::TypePromoteInteger)
1403 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
1404 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
1405 TargetLowering::TypePromoteInteger)
1406 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
1407
1408 // If, after promotion, these are the same types, this is a noop copy.
1409 if (SrcVT != DstVT)
1410 return false;
1411
1412 return SinkCast(CI);
1413}
1414
1415// Match a simple increment by constant operation. Note that if a sub is
1416// matched, the step is negated (as if the step had been canonicalized to
1417// an add, even though we leave the instruction alone.)
1418bool matchIncrement(const Instruction *IVInc, Instruction *&LHS,
1419 Constant *&Step) {
1420 if (match(IVInc, m_Add(m_Instruction(LHS), m_Constant(Step))) ||
1421 match(IVInc, m_ExtractValue<0>(m_Intrinsic<Intrinsic::uadd_with_overflow>(
1422 m_Instruction(LHS), m_Constant(Step)))))
1423 return true;
1424 if (match(IVInc, m_Sub(m_Instruction(LHS), m_Constant(Step))) ||
1425 match(IVInc, m_ExtractValue<0>(m_Intrinsic<Intrinsic::usub_with_overflow>(
1426 m_Instruction(LHS), m_Constant(Step))))) {
1427 Step = ConstantExpr::getNeg(Step);
1428 return true;
1429 }
1430 return false;
1431}
1432
1433/// If given \p PN is an inductive variable with value IVInc coming from the
1434/// backedge, and on each iteration it gets increased by Step, return pair
1435/// <IVInc, Step>. Otherwise, return None.
1436static Optional<std::pair<Instruction *, Constant *>>
1437getIVIncrement(const PHINode *PN, const LoopInfo *LI) {
1438 const Loop *L = LI->getLoopFor(PN->getParent());
1439 if (!L || L->getHeader() != PN->getParent() || !L->getLoopLatch())
1440 return None;
1441 auto *IVInc =
1442 dyn_cast<Instruction>(PN->getIncomingValueForBlock(L->getLoopLatch()));
1443 if (!IVInc || LI->getLoopFor(IVInc->getParent()) != L)
1444 return None;
1445 Instruction *LHS = nullptr;
1446 Constant *Step = nullptr;
1447 if (matchIncrement(IVInc, LHS, Step) && LHS == PN)
1448 return std::make_pair(IVInc, Step);
1449 return None;
1450}
1451
1452static bool isIVIncrement(const Value *V, const LoopInfo *LI) {
1453 auto *I = dyn_cast<Instruction>(V);
1454 if (!I)
1455 return false;
1456 Instruction *LHS = nullptr;
1457 Constant *Step = nullptr;
1458 if (!matchIncrement(I, LHS, Step))
1459 return false;
1460 if (auto *PN = dyn_cast<PHINode>(LHS))
1461 if (auto IVInc = getIVIncrement(PN, LI))
1462 return IVInc->first == I;
1463 return false;
1464}
1465
1466bool CodeGenPrepare::replaceMathCmpWithIntrinsic(BinaryOperator *BO,
1467 Value *Arg0, Value *Arg1,
1468 CmpInst *Cmp,
1469 Intrinsic::ID IID) {
1470 auto IsReplacableIVIncrement = [this, &Cmp](BinaryOperator *BO) {
1471 if (!isIVIncrement(BO, LI))
1472 return false;
1473 const Loop *L = LI->getLoopFor(BO->getParent());
1474 assert(L && "L should not be null after isIVIncrement()")(static_cast <bool> (L && "L should not be null after isIVIncrement()"
) ? void (0) : __assert_fail ("L && \"L should not be null after isIVIncrement()\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 1474, __extension__ __PRETTY_FUNCTION__
))
;
1475 // Do not risk on moving increment into a child loop.
1476 if (LI->getLoopFor(Cmp->getParent()) != L)
1477 return false;
1478
1479 // Finally, we need to ensure that the insert point will dominate all
1480 // existing uses of the increment.
1481
1482 auto &DT = getDT(*BO->getParent()->getParent());
1483 if (DT.dominates(Cmp->getParent(), BO->getParent()))
1484 // If we're moving up the dom tree, all uses are trivially dominated.
1485 // (This is the common case for code produced by LSR.)
1486 return true;
1487
1488 // Otherwise, special case the single use in the phi recurrence.
1489 return BO->hasOneUse() && DT.dominates(Cmp->getParent(), L->getLoopLatch());
1490 };
1491 if (BO->getParent() != Cmp->getParent() && !IsReplacableIVIncrement(BO)) {
1492 // We used to use a dominator tree here to allow multi-block optimization.
1493 // But that was problematic because:
1494 // 1. It could cause a perf regression by hoisting the math op into the
1495 // critical path.
1496 // 2. It could cause a perf regression by creating a value that was live
1497 // across multiple blocks and increasing register pressure.
1498 // 3. Use of a dominator tree could cause large compile-time regression.
1499 // This is because we recompute the DT on every change in the main CGP
1500 // run-loop. The recomputing is probably unnecessary in many cases, so if
1501 // that was fixed, using a DT here would be ok.
1502 //
1503 // There is one important particular case we still want to handle: if BO is
1504 // the IV increment. Important properties that make it profitable:
1505 // - We can speculate IV increment anywhere in the loop (as long as the
1506 // indvar Phi is its only user);
1507 // - Upon computing Cmp, we effectively compute something equivalent to the
1508 // IV increment (despite it loops differently in the IR). So moving it up
1509 // to the cmp point does not really increase register pressure.
1510 return false;
1511 }
1512
1513 // We allow matching the canonical IR (add X, C) back to (usubo X, -C).
1514 if (BO->getOpcode() == Instruction::Add &&
1515 IID == Intrinsic::usub_with_overflow) {
1516 assert(isa<Constant>(Arg1) && "Unexpected input for usubo")(static_cast <bool> (isa<Constant>(Arg1) &&
"Unexpected input for usubo") ? void (0) : __assert_fail ("isa<Constant>(Arg1) && \"Unexpected input for usubo\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 1516, __extension__ __PRETTY_FUNCTION__
))
;
1517 Arg1 = ConstantExpr::getNeg(cast<Constant>(Arg1));
1518 }
1519
1520 // Insert at the first instruction of the pair.
1521 Instruction *InsertPt = nullptr;
1522 for (Instruction &Iter : *Cmp->getParent()) {
1523 // If BO is an XOR, it is not guaranteed that it comes after both inputs to
1524 // the overflow intrinsic are defined.
1525 if ((BO->getOpcode() != Instruction::Xor && &Iter == BO) || &Iter == Cmp) {
1526 InsertPt = &Iter;
1527 break;
1528 }
1529 }
1530 assert(InsertPt != nullptr && "Parent block did not contain cmp or binop")(static_cast <bool> (InsertPt != nullptr && "Parent block did not contain cmp or binop"
) ? void (0) : __assert_fail ("InsertPt != nullptr && \"Parent block did not contain cmp or binop\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 1530, __extension__ __PRETTY_FUNCTION__
))
;
1531
1532 IRBuilder<> Builder(InsertPt);
1533 Value *MathOV = Builder.CreateBinaryIntrinsic(IID, Arg0, Arg1);
1534 if (BO->getOpcode() != Instruction::Xor) {
1535 Value *Math = Builder.CreateExtractValue(MathOV, 0, "math");
1536 replaceAllUsesWith(BO, Math, FreshBBs, IsHugeFunc);
1537 } else
1538 assert(BO->hasOneUse() &&(static_cast <bool> (BO->hasOneUse() && "Patterns with XOr should use the BO only in the compare"
) ? void (0) : __assert_fail ("BO->hasOneUse() && \"Patterns with XOr should use the BO only in the compare\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 1539, __extension__ __PRETTY_FUNCTION__
))
1539 "Patterns with XOr should use the BO only in the compare")(static_cast <bool> (BO->hasOneUse() && "Patterns with XOr should use the BO only in the compare"
) ? void (0) : __assert_fail ("BO->hasOneUse() && \"Patterns with XOr should use the BO only in the compare\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 1539, __extension__ __PRETTY_FUNCTION__
))
;
1540 Value *OV = Builder.CreateExtractValue(MathOV, 1, "ov");
1541 replaceAllUsesWith(Cmp, OV, FreshBBs, IsHugeFunc);
1542 Cmp->eraseFromParent();
1543 BO->eraseFromParent();
1544 return true;
1545}
1546
1547/// Match special-case patterns that check for unsigned add overflow.
1548static bool matchUAddWithOverflowConstantEdgeCases(CmpInst *Cmp,
1549 BinaryOperator *&Add) {
1550 // Add = add A, 1; Cmp = icmp eq A,-1 (overflow if A is max val)
1551 // Add = add A,-1; Cmp = icmp ne A, 0 (overflow if A is non-zero)
1552 Value *A = Cmp->getOperand(0), *B = Cmp->getOperand(1);
1553
1554 // We are not expecting non-canonical/degenerate code. Just bail out.
1555 if (isa<Constant>(A))
1556 return false;
1557
1558 ICmpInst::Predicate Pred = Cmp->getPredicate();
1559 if (Pred == ICmpInst::ICMP_EQ && match(B, m_AllOnes()))
1560 B = ConstantInt::get(B->getType(), 1);
1561 else if (Pred == ICmpInst::ICMP_NE && match(B, m_ZeroInt()))
1562 B = ConstantInt::get(B->getType(), -1);
1563 else
1564 return false;
1565
1566 // Check the users of the variable operand of the compare looking for an add
1567 // with the adjusted constant.
1568 for (User *U : A->users()) {
1569 if (match(U, m_Add(m_Specific(A), m_Specific(B)))) {
1570 Add = cast<BinaryOperator>(U);
1571 return true;
1572 }
1573 }
1574 return false;
1575}
1576
1577/// Try to combine the compare into a call to the llvm.uadd.with.overflow
1578/// intrinsic. Return true if any changes were made.
1579bool CodeGenPrepare::combineToUAddWithOverflow(CmpInst *Cmp,
1580 ModifyDT &ModifiedDT) {
1581 Value *A, *B;
1582 BinaryOperator *Add;
1583 if (!match(Cmp, m_UAddWithOverflow(m_Value(A), m_Value(B), m_BinOp(Add)))) {
1584 if (!matchUAddWithOverflowConstantEdgeCases(Cmp, Add))
1585 return false;
1586 // Set A and B in case we match matchUAddWithOverflowConstantEdgeCases.
1587 A = Add->getOperand(0);
1588 B = Add->getOperand(1);
1589 }
1590
1591 if (!TLI->shouldFormOverflowOp(ISD::UADDO,
1592 TLI->getValueType(*DL, Add->getType()),
1593 Add->hasNUsesOrMore(2)))
1594 return false;
1595
1596 // We don't want to move around uses of condition values this late, so we
1597 // check if it is legal to create the call to the intrinsic in the basic
1598 // block containing the icmp.
1599 if (Add->getParent() != Cmp->getParent() && !Add->hasOneUse())
1600 return false;
1601
1602 if (!replaceMathCmpWithIntrinsic(Add, A, B, Cmp,
1603 Intrinsic::uadd_with_overflow))
1604 return false;
1605
1606 // Reset callers - do not crash by iterating over a dead instruction.
1607 ModifiedDT = ModifyDT::ModifyInstDT;
1608 return true;
1609}
1610
1611bool CodeGenPrepare::combineToUSubWithOverflow(CmpInst *Cmp,
1612 ModifyDT &ModifiedDT) {
1613 // We are not expecting non-canonical/degenerate code. Just bail out.
1614 Value *A = Cmp->getOperand(0), *B = Cmp->getOperand(1);
1615 if (isa<Constant>(A) && isa<Constant>(B))
1616 return false;
1617
1618 // Convert (A u> B) to (A u< B) to simplify pattern matching.
1619 ICmpInst::Predicate Pred = Cmp->getPredicate();
1620 if (Pred == ICmpInst::ICMP_UGT) {
1621 std::swap(A, B);
1622 Pred = ICmpInst::ICMP_ULT;
1623 }
1624 // Convert special-case: (A == 0) is the same as (A u< 1).
1625 if (Pred == ICmpInst::ICMP_EQ && match(B, m_ZeroInt())) {
1626 B = ConstantInt::get(B->getType(), 1);
1627 Pred = ICmpInst::ICMP_ULT;
1628 }
1629 // Convert special-case: (A != 0) is the same as (0 u< A).
1630 if (Pred == ICmpInst::ICMP_NE && match(B, m_ZeroInt())) {
1631 std::swap(A, B);
1632 Pred = ICmpInst::ICMP_ULT;
1633 }
1634 if (Pred != ICmpInst::ICMP_ULT)
1635 return false;
1636
1637 // Walk the users of a variable operand of a compare looking for a subtract or
1638 // add with that same operand. Also match the 2nd operand of the compare to
1639 // the add/sub, but that may be a negated constant operand of an add.
1640 Value *CmpVariableOperand = isa<Constant>(A) ? B : A;
1641 BinaryOperator *Sub = nullptr;
1642 for (User *U : CmpVariableOperand->users()) {
1643 // A - B, A u< B --> usubo(A, B)
1644 if (match(U, m_Sub(m_Specific(A), m_Specific(B)))) {
1645 Sub = cast<BinaryOperator>(U);
1646 break;
1647 }
1648
1649 // A + (-C), A u< C (canonicalized form of (sub A, C))
1650 const APInt *CmpC, *AddC;
1651 if (match(U, m_Add(m_Specific(A), m_APInt(AddC))) &&
1652 match(B, m_APInt(CmpC)) && *AddC == -(*CmpC)) {
1653 Sub = cast<BinaryOperator>(U);
1654 break;
1655 }
1656 }
1657 if (!Sub)
1658 return false;
1659
1660 if (!TLI->shouldFormOverflowOp(ISD::USUBO,
1661 TLI->getValueType(*DL, Sub->getType()),
1662 Sub->hasNUsesOrMore(2)))
1663 return false;
1664
1665 if (!replaceMathCmpWithIntrinsic(Sub, Sub->getOperand(0), Sub->getOperand(1),
1666 Cmp, Intrinsic::usub_with_overflow))
1667 return false;
1668
1669 // Reset callers - do not crash by iterating over a dead instruction.
1670 ModifiedDT = ModifyDT::ModifyInstDT;
1671 return true;
1672}
1673
1674/// Sink the given CmpInst into user blocks to reduce the number of virtual
1675/// registers that must be created and coalesced. This is a clear win except on
1676/// targets with multiple condition code registers (PowerPC), where it might
1677/// lose; some adjustment may be wanted there.
1678///
1679/// Return true if any changes are made.
1680static bool sinkCmpExpression(CmpInst *Cmp, const TargetLowering &TLI) {
1681 if (TLI.hasMultipleConditionRegisters())
1682 return false;
1683
1684 // Avoid sinking soft-FP comparisons, since this can move them into a loop.
1685 if (TLI.useSoftFloat() && isa<FCmpInst>(Cmp))
1686 return false;
1687
1688 // Only insert a cmp in each block once.
1689 DenseMap<BasicBlock *, CmpInst *> InsertedCmps;
1690
1691 bool MadeChange = false;
1692 for (Value::user_iterator UI = Cmp->user_begin(), E = Cmp->user_end();
1693 UI != E;) {
1694 Use &TheUse = UI.getUse();
1695 Instruction *User = cast<Instruction>(*UI);
1696
1697 // Preincrement use iterator so we don't invalidate it.
1698 ++UI;
1699
1700 // Don't bother for PHI nodes.
1701 if (isa<PHINode>(User))
1702 continue;
1703
1704 // Figure out which BB this cmp is used in.
1705 BasicBlock *UserBB = User->getParent();
1706 BasicBlock *DefBB = Cmp->getParent();
1707
1708 // If this user is in the same block as the cmp, don't change the cmp.
1709 if (UserBB == DefBB)
1710 continue;
1711
1712 // If we have already inserted a cmp into this block, use it.
1713 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
1714
1715 if (!InsertedCmp) {
1716 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1717 assert(InsertPt != UserBB->end())(static_cast <bool> (InsertPt != UserBB->end()) ? void
(0) : __assert_fail ("InsertPt != UserBB->end()", "llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 1717, __extension__ __PRETTY_FUNCTION__))
;
1718 InsertedCmp = CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(),
1719 Cmp->getOperand(0), Cmp->getOperand(1), "",
1720 &*InsertPt);
1721 // Propagate the debug info.
1722 InsertedCmp->setDebugLoc(Cmp->getDebugLoc());
1723 }
1724
1725 // Replace a use of the cmp with a use of the new cmp.
1726 TheUse = InsertedCmp;
1727 MadeChange = true;
1728 ++NumCmpUses;
1729 }
1730
1731 // If we removed all uses, nuke the cmp.
1732 if (Cmp->use_empty()) {
1733 Cmp->eraseFromParent();
1734 MadeChange = true;
1735 }
1736
1737 return MadeChange;
1738}
1739
1740/// For pattern like:
1741///
1742/// DomCond = icmp sgt/slt CmpOp0, CmpOp1 (might not be in DomBB)
1743/// ...
1744/// DomBB:
1745/// ...
1746/// br DomCond, TrueBB, CmpBB
1747/// CmpBB: (with DomBB being the single predecessor)
1748/// ...
1749/// Cmp = icmp eq CmpOp0, CmpOp1
1750/// ...
1751///
1752/// It would use two comparison on targets that lowering of icmp sgt/slt is
1753/// different from lowering of icmp eq (PowerPC). This function try to convert
1754/// 'Cmp = icmp eq CmpOp0, CmpOp1' to ' Cmp = icmp slt/sgt CmpOp0, CmpOp1'.
1755/// After that, DomCond and Cmp can use the same comparison so reduce one
1756/// comparison.
1757///
1758/// Return true if any changes are made.
1759static bool foldICmpWithDominatingICmp(CmpInst *Cmp,
1760 const TargetLowering &TLI) {
1761 if (!EnableICMP_EQToICMP_ST && TLI.isEqualityCmpFoldedWithSignedCmp())
1762 return false;
1763
1764 ICmpInst::Predicate Pred = Cmp->getPredicate();
1765 if (Pred != ICmpInst::ICMP_EQ)
1766 return false;
1767
1768 // If icmp eq has users other than BranchInst and SelectInst, converting it to
1769 // icmp slt/sgt would introduce more redundant LLVM IR.
1770 for (User *U : Cmp->users()) {
1771 if (isa<BranchInst>(U))
1772 continue;
1773 if (isa<SelectInst>(U) && cast<SelectInst>(U)->getCondition() == Cmp)
1774 continue;
1775 return false;
1776 }
1777
1778 // This is a cheap/incomplete check for dominance - just match a single
1779 // predecessor with a conditional branch.
1780 BasicBlock *CmpBB = Cmp->getParent();
1781 BasicBlock *DomBB = CmpBB->getSinglePredecessor();
1782 if (!DomBB)
1783 return false;
1784
1785 // We want to ensure that the only way control gets to the comparison of
1786 // interest is that a less/greater than comparison on the same operands is
1787 // false.
1788 Value *DomCond;
1789 BasicBlock *TrueBB, *FalseBB;
1790 if (!match(DomBB->getTerminator(), m_Br(m_Value(DomCond), TrueBB, FalseBB)))
1791 return false;
1792 if (CmpBB != FalseBB)
1793 return false;
1794
1795 Value *CmpOp0 = Cmp->getOperand(0), *CmpOp1 = Cmp->getOperand(1);
1796 ICmpInst::Predicate DomPred;
1797 if (!match(DomCond, m_ICmp(DomPred, m_Specific(CmpOp0), m_Specific(CmpOp1))))
1798 return false;
1799 if (DomPred != ICmpInst::ICMP_SGT && DomPred != ICmpInst::ICMP_SLT)
1800 return false;
1801
1802 // Convert the equality comparison to the opposite of the dominating
1803 // comparison and swap the direction for all branch/select users.
1804 // We have conceptually converted:
1805 // Res = (a < b) ? <LT_RES> : (a == b) ? <EQ_RES> : <GT_RES>;
1806 // to
1807 // Res = (a < b) ? <LT_RES> : (a > b) ? <GT_RES> : <EQ_RES>;
1808 // And similarly for branches.
1809 for (User *U : Cmp->users()) {
1810 if (auto *BI = dyn_cast<BranchInst>(U)) {
1811 assert(BI->isConditional() && "Must be conditional")(static_cast <bool> (BI->isConditional() && "Must be conditional"
) ? void (0) : __assert_fail ("BI->isConditional() && \"Must be conditional\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 1811, __extension__ __PRETTY_FUNCTION__
))
;
1812 BI->swapSuccessors();
1813 continue;
1814 }
1815 if (auto *SI = dyn_cast<SelectInst>(U)) {
1816 // Swap operands
1817 SI->swapValues();
1818 SI->swapProfMetadata();
1819 continue;
1820 }
1821 llvm_unreachable("Must be a branch or a select")::llvm::llvm_unreachable_internal("Must be a branch or a select"
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 1821)
;
1822 }
1823 Cmp->setPredicate(CmpInst::getSwappedPredicate(DomPred));
1824 return true;
1825}
1826
1827bool CodeGenPrepare::optimizeCmp(CmpInst *Cmp, ModifyDT &ModifiedDT) {
1828 if (sinkCmpExpression(Cmp, *TLI))
1829 return true;
1830
1831 if (combineToUAddWithOverflow(Cmp, ModifiedDT))
1832 return true;
1833
1834 if (combineToUSubWithOverflow(Cmp, ModifiedDT))
1835 return true;
1836
1837 if (foldICmpWithDominatingICmp(Cmp, *TLI))
1838 return true;
1839
1840 return false;
1841}
1842
1843/// Duplicate and sink the given 'and' instruction into user blocks where it is
1844/// used in a compare to allow isel to generate better code for targets where
1845/// this operation can be combined.
1846///
1847/// Return true if any changes are made.
1848static bool sinkAndCmp0Expression(Instruction *AndI, const TargetLowering &TLI,
1849 SetOfInstrs &InsertedInsts) {
1850 // Double-check that we're not trying to optimize an instruction that was
1851 // already optimized by some other part of this pass.
1852 assert(!InsertedInsts.count(AndI) &&(static_cast <bool> (!InsertedInsts.count(AndI) &&
"Attempting to optimize already optimized and instruction") ?
void (0) : __assert_fail ("!InsertedInsts.count(AndI) && \"Attempting to optimize already optimized and instruction\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 1853, __extension__ __PRETTY_FUNCTION__
))
1853 "Attempting to optimize already optimized and instruction")(static_cast <bool> (!InsertedInsts.count(AndI) &&
"Attempting to optimize already optimized and instruction") ?
void (0) : __assert_fail ("!InsertedInsts.count(AndI) && \"Attempting to optimize already optimized and instruction\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 1853, __extension__ __PRETTY_FUNCTION__
))
;
1854 (void)InsertedInsts;
1855
1856 // Nothing to do for single use in same basic block.
1857 if (AndI->hasOneUse() &&
1858 AndI->getParent() == cast<Instruction>(*AndI->user_begin())->getParent())
1859 return false;
1860
1861 // Try to avoid cases where sinking/duplicating is likely to increase register
1862 // pressure.
1863 if (!isa<ConstantInt>(AndI->getOperand(0)) &&
1864 !isa<ConstantInt>(AndI->getOperand(1)) &&
1865 AndI->getOperand(0)->hasOneUse() && AndI->getOperand(1)->hasOneUse())
1866 return false;
1867
1868 for (auto *U : AndI->users()) {
1869 Instruction *User = cast<Instruction>(U);
1870
1871 // Only sink 'and' feeding icmp with 0.
1872 if (!isa<ICmpInst>(User))
1873 return false;
1874
1875 auto *CmpC = dyn_cast<ConstantInt>(User->getOperand(1));
1876 if (!CmpC || !CmpC->isZero())
1877 return false;
1878 }
1879
1880 if (!TLI.isMaskAndCmp0FoldingBeneficial(*AndI))
1881 return false;
1882
1883 LLVM_DEBUG(dbgs() << "found 'and' feeding only icmp 0;\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "found 'and' feeding only icmp 0;\n"
; } } while (false)
;
1884 LLVM_DEBUG(AndI->getParent()->dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { AndI->getParent()->dump(); } } while
(false)
;
1885
1886 // Push the 'and' into the same block as the icmp 0. There should only be
1887 // one (icmp (and, 0)) in each block, since CSE/GVN should have removed any
1888 // others, so we don't need to keep track of which BBs we insert into.
1889 for (Value::user_iterator UI = AndI->user_begin(), E = AndI->user_end();
1890 UI != E;) {
1891 Use &TheUse = UI.getUse();
1892 Instruction *User = cast<Instruction>(*UI);
1893
1894 // Preincrement use iterator so we don't invalidate it.
1895 ++UI;
1896
1897 LLVM_DEBUG(dbgs() << "sinking 'and' use: " << *User << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "sinking 'and' use: " <<
*User << "\n"; } } while (false)
;
1898
1899 // Keep the 'and' in the same place if the use is already in the same block.
1900 Instruction *InsertPt =
1901 User->getParent() == AndI->getParent() ? AndI : User;
1902 Instruction *InsertedAnd =
1903 BinaryOperator::Create(Instruction::And, AndI->getOperand(0),
1904 AndI->getOperand(1), "", InsertPt);
1905 // Propagate the debug info.
1906 InsertedAnd->setDebugLoc(AndI->getDebugLoc());
1907
1908 // Replace a use of the 'and' with a use of the new 'and'.
1909 TheUse = InsertedAnd;
1910 ++NumAndUses;
1911 LLVM_DEBUG(User->getParent()->dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { User->getParent()->dump(); } } while
(false)
;
1912 }
1913
1914 // We removed all uses, nuke the and.
1915 AndI->eraseFromParent();
1916 return true;
1917}
1918
1919/// Check if the candidates could be combined with a shift instruction, which
1920/// includes:
1921/// 1. Truncate instruction
1922/// 2. And instruction and the imm is a mask of the low bits:
1923/// imm & (imm+1) == 0
1924static bool isExtractBitsCandidateUse(Instruction *User) {
1925 if (!isa<TruncInst>(User)) {
1926 if (User->getOpcode() != Instruction::And ||
1927 !isa<ConstantInt>(User->getOperand(1)))
1928 return false;
1929
1930 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
1931
1932 if ((Cimm & (Cimm + 1)).getBoolValue())
1933 return false;
1934 }
1935 return true;
1936}
1937
1938/// Sink both shift and truncate instruction to the use of truncate's BB.
1939static bool
1940SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
1941 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
1942 const TargetLowering &TLI, const DataLayout &DL) {
1943 BasicBlock *UserBB = User->getParent();
1944 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
1945 auto *TruncI = cast<TruncInst>(User);
1946 bool MadeChange = false;
1947
1948 for (Value::user_iterator TruncUI = TruncI->user_begin(),
1949 TruncE = TruncI->user_end();
1950 TruncUI != TruncE;) {
1951
1952 Use &TruncTheUse = TruncUI.getUse();
1953 Instruction *TruncUser = cast<Instruction>(*TruncUI);
1954 // Preincrement use iterator so we don't invalidate it.
1955
1956 ++TruncUI;
1957
1958 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
1959 if (!ISDOpcode)
1960 continue;
1961
1962 // If the use is actually a legal node, there will not be an
1963 // implicit truncate.
1964 // FIXME: always querying the result type is just an
1965 // approximation; some nodes' legality is determined by the
1966 // operand or other means. There's no good way to find out though.
1967 if (TLI.isOperationLegalOrCustom(
1968 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
1969 continue;
1970
1971 // Don't bother for PHI nodes.
1972 if (isa<PHINode>(TruncUser))
1973 continue;
1974
1975 BasicBlock *TruncUserBB = TruncUser->getParent();
1976
1977 if (UserBB == TruncUserBB)
1978 continue;
1979
1980 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
1981 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
1982
1983 if (!InsertedShift && !InsertedTrunc) {
1984 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
1985 assert(InsertPt != TruncUserBB->end())(static_cast <bool> (InsertPt != TruncUserBB->end())
? void (0) : __assert_fail ("InsertPt != TruncUserBB->end()"
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 1985, __extension__ __PRETTY_FUNCTION__
))
;
1986 // Sink the shift
1987 if (ShiftI->getOpcode() == Instruction::AShr)
1988 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1989 "", &*InsertPt);
1990 else
1991 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1992 "", &*InsertPt);
1993 InsertedShift->setDebugLoc(ShiftI->getDebugLoc());
1994
1995 // Sink the trunc
1996 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
1997 TruncInsertPt++;
1998 assert(TruncInsertPt != TruncUserBB->end())(static_cast <bool> (TruncInsertPt != TruncUserBB->end
()) ? void (0) : __assert_fail ("TruncInsertPt != TruncUserBB->end()"
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 1998, __extension__ __PRETTY_FUNCTION__
))
;
1999
2000 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
2001 TruncI->getType(), "", &*TruncInsertPt);
2002 InsertedTrunc->setDebugLoc(TruncI->getDebugLoc());
2003
2004 MadeChange = true;
2005
2006 TruncTheUse = InsertedTrunc;
2007 }
2008 }
2009 return MadeChange;
2010}
2011
2012/// Sink the shift *right* instruction into user blocks if the uses could
2013/// potentially be combined with this shift instruction and generate BitExtract
2014/// instruction. It will only be applied if the architecture supports BitExtract
2015/// instruction. Here is an example:
2016/// BB1:
2017/// %x.extract.shift = lshr i64 %arg1, 32
2018/// BB2:
2019/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
2020/// ==>
2021///
2022/// BB2:
2023/// %x.extract.shift.1 = lshr i64 %arg1, 32
2024/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
2025///
2026/// CodeGen will recognize the pattern in BB2 and generate BitExtract
2027/// instruction.
2028/// Return true if any changes are made.
2029static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
2030 const TargetLowering &TLI,
2031 const DataLayout &DL) {
2032 BasicBlock *DefBB = ShiftI->getParent();
2033
2034 /// Only insert instructions in each block once.
2035 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
2036
2037 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
2038
2039 bool MadeChange = false;
2040 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
2041 UI != E;) {
2042 Use &TheUse = UI.getUse();
2043 Instruction *User = cast<Instruction>(*UI);
2044 // Preincrement use iterator so we don't invalidate it.
2045 ++UI;
2046
2047 // Don't bother for PHI nodes.
2048 if (isa<PHINode>(User))
2049 continue;
2050
2051 if (!isExtractBitsCandidateUse(User))
2052 continue;
2053
2054 BasicBlock *UserBB = User->getParent();
2055
2056 if (UserBB == DefBB) {
2057 // If the shift and truncate instruction are in the same BB. The use of
2058 // the truncate(TruncUse) may still introduce another truncate if not
2059 // legal. In this case, we would like to sink both shift and truncate
2060 // instruction to the BB of TruncUse.
2061 // for example:
2062 // BB1:
2063 // i64 shift.result = lshr i64 opnd, imm
2064 // trunc.result = trunc shift.result to i16
2065 //
2066 // BB2:
2067 // ----> We will have an implicit truncate here if the architecture does
2068 // not have i16 compare.
2069 // cmp i16 trunc.result, opnd2
2070 //
2071 if (isa<TruncInst>(User) &&
2072 shiftIsLegal
2073 // If the type of the truncate is legal, no truncate will be
2074 // introduced in other basic blocks.
2075 && (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
2076 MadeChange =
2077 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
2078
2079 continue;
2080 }
2081 // If we have already inserted a shift into this block, use it.
2082 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
2083
2084 if (!InsertedShift) {
2085 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
2086 assert(InsertPt != UserBB->end())(static_cast <bool> (InsertPt != UserBB->end()) ? void
(0) : __assert_fail ("InsertPt != UserBB->end()", "llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 2086, __extension__ __PRETTY_FUNCTION__))
;
2087
2088 if (ShiftI->getOpcode() == Instruction::AShr)
2089 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
2090 "", &*InsertPt);
2091 else
2092 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
2093 "", &*InsertPt);
2094 InsertedShift->setDebugLoc(ShiftI->getDebugLoc());
2095
2096 MadeChange = true;
2097 }
2098
2099 // Replace a use of the shift with a use of the new shift.
2100 TheUse = InsertedShift;
2101 }
2102
2103 // If we removed all uses, or there are none, nuke the shift.
2104 if (ShiftI->use_empty()) {
2105 salvageDebugInfo(*ShiftI);
2106 ShiftI->eraseFromParent();
2107 MadeChange = true;
2108 }
2109
2110 return MadeChange;
2111}
2112
2113/// If counting leading or trailing zeros is an expensive operation and a zero
2114/// input is defined, add a check for zero to avoid calling the intrinsic.
2115///
2116/// We want to transform:
2117/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
2118///
2119/// into:
2120/// entry:
2121/// %cmpz = icmp eq i64 %A, 0
2122/// br i1 %cmpz, label %cond.end, label %cond.false
2123/// cond.false:
2124/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
2125/// br label %cond.end
2126/// cond.end:
2127/// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
2128///
2129/// If the transform is performed, return true and set ModifiedDT to true.
2130static bool despeculateCountZeros(IntrinsicInst *CountZeros,
2131 const TargetLowering *TLI,
2132 const DataLayout *DL, ModifyDT &ModifiedDT,
2133 SmallSet<BasicBlock *, 32> &FreshBBs,
2134 bool IsHugeFunc) {
2135 // If a zero input is undefined, it doesn't make sense to despeculate that.
2136 if (match(CountZeros->getOperand(1), m_One()))
2137 return false;
2138
2139 // If it's cheap to speculate, there's nothing to do.
2140 Type *Ty = CountZeros->getType();
2141 auto IntrinsicID = CountZeros->getIntrinsicID();
2142 if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz(Ty)) ||
2143 (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz(Ty)))
2144 return false;
2145
2146 // Only handle legal scalar cases. Anything else requires too much work.
2147 unsigned SizeInBits = Ty->getScalarSizeInBits();
2148 if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSizeInBits())
2149 return false;
2150
2151 // Bail if the value is never zero.
2152 Use &Op = CountZeros->getOperandUse(0);
2153 if (isKnownNonZero(Op, *DL))
2154 return false;
2155
2156 // The intrinsic will be sunk behind a compare against zero and branch.
2157 BasicBlock *StartBlock = CountZeros->getParent();
2158 BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
2159 if (IsHugeFunc)
2160 FreshBBs.insert(CallBlock);
2161
2162 // Create another block after the count zero intrinsic. A PHI will be added
2163 // in this block to select the result of the intrinsic or the bit-width
2164 // constant if the input to the intrinsic is zero.
2165 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
2166 BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
2167 if (IsHugeFunc)
2168 FreshBBs.insert(EndBlock);
2169
2170 // Set up a builder to create a compare, conditional branch, and PHI.
2171 IRBuilder<> Builder(CountZeros->getContext());
2172 Builder.SetInsertPoint(StartBlock->getTerminator());
2173 Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
2174
2175 // Replace the unconditional branch that was created by the first split with
2176 // a compare against zero and a conditional branch.
2177 Value *Zero = Constant::getNullValue(Ty);
2178 // Avoid introducing branch on poison. This also replaces the ctz operand.
2179 if (!isGuaranteedNotToBeUndefOrPoison(Op))
2180 Op = Builder.CreateFreeze(Op, Op->getName() + ".fr");
2181 Value *Cmp = Builder.CreateICmpEQ(Op, Zero, "cmpz");
2182 Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
2183 StartBlock->getTerminator()->eraseFromParent();
2184
2185 // Create a PHI in the end block to select either the output of the intrinsic
2186 // or the bit width of the operand.
2187 Builder.SetInsertPoint(&EndBlock->front());
2188 PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
2189 replaceAllUsesWith(CountZeros, PN, FreshBBs, IsHugeFunc);
2190 Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
2191 PN->addIncoming(BitWidth, StartBlock);
2192 PN->addIncoming(CountZeros, CallBlock);
2193
2194 // We are explicitly handling the zero case, so we can set the intrinsic's
2195 // undefined zero argument to 'true'. This will also prevent reprocessing the
2196 // intrinsic; we only despeculate when a zero input is defined.
2197 CountZeros->setArgOperand(1, Builder.getTrue());
2198 ModifiedDT = ModifyDT::ModifyBBDT;
2199 return true;
2200}
2201
2202bool CodeGenPrepare::optimizeCallInst(CallInst *CI, ModifyDT &ModifiedDT) {
2203 BasicBlock *BB = CI->getParent();
2204
2205 // Lower inline assembly if we can.
2206 // If we found an inline asm expession, and if the target knows how to
2207 // lower it to normal LLVM code, do so now.
2208 if (CI->isInlineAsm()) {
2209 if (TLI->ExpandInlineAsm(CI)) {
2210 // Avoid invalidating the iterator.
2211 CurInstIterator = BB->begin();
2212 // Avoid processing instructions out of order, which could cause
2213 // reuse before a value is defined.
2214 SunkAddrs.clear();
2215 return true;
2216 }
2217 // Sink address computing for memory operands into the block.
2218 if (optimizeInlineAsmInst(CI))
2219 return true;
2220 }
2221
2222 // Align the pointer arguments to this call if the target thinks it's a good
2223 // idea
2224 unsigned MinSize;
2225 Align PrefAlign;
2226 if (TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
2227 for (auto &Arg : CI->args()) {
2228 // We want to align both objects whose address is used directly and
2229 // objects whose address is used in casts and GEPs, though it only makes
2230 // sense for GEPs if the offset is a multiple of the desired alignment and
2231 // if size - offset meets the size threshold.
2232 if (!Arg->getType()->isPointerTy())
2233 continue;
2234 APInt Offset(DL->getIndexSizeInBits(
2235 cast<PointerType>(Arg->getType())->getAddressSpace()),
2236 0);
2237 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
2238 uint64_t Offset2 = Offset.getLimitedValue();
2239 if (!isAligned(PrefAlign, Offset2))
2240 continue;
2241 AllocaInst *AI;
2242 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlign() < PrefAlign &&
2243 DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
2244 AI->setAlignment(PrefAlign);
2245 // Global variables can only be aligned if they are defined in this
2246 // object (i.e. they are uniquely initialized in this object), and
2247 // over-aligning global variables that have an explicit section is
2248 // forbidden.
2249 GlobalVariable *GV;
2250 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
2251 GV->getPointerAlignment(*DL) < PrefAlign &&
2252 DL->getTypeAllocSize(GV->getValueType()) >= MinSize + Offset2)
2253 GV->setAlignment(PrefAlign);
2254 }
2255 // If this is a memcpy (or similar) then we may be able to improve the
2256 // alignment
2257 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
2258 Align DestAlign = getKnownAlignment(MI->getDest(), *DL);
2259 MaybeAlign MIDestAlign = MI->getDestAlign();
2260 if (!MIDestAlign || DestAlign > *MIDestAlign)
2261 MI->setDestAlignment(DestAlign);
2262 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
2263 MaybeAlign MTISrcAlign = MTI->getSourceAlign();
2264 Align SrcAlign = getKnownAlignment(MTI->getSource(), *DL);
2265 if (!MTISrcAlign || SrcAlign > *MTISrcAlign)
2266 MTI->setSourceAlignment(SrcAlign);
2267 }
2268 }
2269 }
2270
2271 // If we have a cold call site, try to sink addressing computation into the
2272 // cold block. This interacts with our handling for loads and stores to
2273 // ensure that we can fold all uses of a potential addressing computation
2274 // into their uses. TODO: generalize this to work over profiling data
2275 if (CI->hasFnAttr(Attribute::Cold) && !OptSize &&
2276 !llvm::shouldOptimizeForSize(BB, PSI, BFI.get()))
2277 for (auto &Arg : CI->args()) {
2278 if (!Arg->getType()->isPointerTy())
2279 continue;
2280 unsigned AS = Arg->getType()->getPointerAddressSpace();
2281 return optimizeMemoryInst(CI, Arg, Arg->getType(), AS);
2282 }
2283
2284 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
2285 if (II) {
2286 switch (II->getIntrinsicID()) {
2287 default:
2288 break;
2289 case Intrinsic::assume:
2290 llvm_unreachable("llvm.assume should have been removed already")::llvm::llvm_unreachable_internal("llvm.assume should have been removed already"
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 2290)
;
2291 case Intrinsic::experimental_widenable_condition: {
2292 // Give up on future widening oppurtunties so that we can fold away dead
2293 // paths and merge blocks before going into block-local instruction
2294 // selection.
2295 if (II->use_empty()) {
2296 II->eraseFromParent();
2297 return true;
2298 }
2299 Constant *RetVal = ConstantInt::getTrue(II->getContext());
2300 resetIteratorIfInvalidatedWhileCalling(BB, [&]() {
2301 replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
2302 });
2303 return true;
2304 }
2305 case Intrinsic::objectsize:
2306 llvm_unreachable("llvm.objectsize.* should have been lowered already")::llvm::llvm_unreachable_internal("llvm.objectsize.* should have been lowered already"
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 2306)
;
2307 case Intrinsic::is_constant:
2308 llvm_unreachable("llvm.is.constant.* should have been lowered already")::llvm::llvm_unreachable_internal("llvm.is.constant.* should have been lowered already"
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 2308)
;
2309 case Intrinsic::aarch64_stlxr:
2310 case Intrinsic::aarch64_stxr: {
2311 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
2312 if (!ExtVal || !ExtVal->hasOneUse() ||
2313 ExtVal->getParent() == CI->getParent())
2314 return false;
2315 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
2316 ExtVal->moveBefore(CI);
2317 // Mark this instruction as "inserted by CGP", so that other
2318 // optimizations don't touch it.
2319 InsertedInsts.insert(ExtVal);
2320 return true;
2321 }
2322
2323 case Intrinsic::launder_invariant_group:
2324 case Intrinsic::strip_invariant_group: {
2325 Value *ArgVal = II->getArgOperand(0);
2326 auto it = LargeOffsetGEPMap.find(II);
2327 if (it != LargeOffsetGEPMap.end()) {
2328 // Merge entries in LargeOffsetGEPMap to reflect the RAUW.
2329 // Make sure not to have to deal with iterator invalidation
2330 // after possibly adding ArgVal to LargeOffsetGEPMap.
2331 auto GEPs = std::move(it->second);
2332 LargeOffsetGEPMap[ArgVal].append(GEPs.begin(), GEPs.end());
2333 LargeOffsetGEPMap.erase(II);
2334 }
2335
2336 replaceAllUsesWith(II, ArgVal, FreshBBs, IsHugeFunc);
2337 II->eraseFromParent();
2338 return true;
2339 }
2340 case Intrinsic::cttz:
2341 case Intrinsic::ctlz:
2342 // If counting zeros is expensive, try to avoid it.
2343 return despeculateCountZeros(II, TLI, DL, ModifiedDT, FreshBBs,
2344 IsHugeFunc);
2345 case Intrinsic::fshl:
2346 case Intrinsic::fshr:
2347 return optimizeFunnelShift(II);
2348 case Intrinsic::dbg_value:
2349 return fixupDbgValue(II);
2350 case Intrinsic::vscale: {
2351 // If datalayout has no special restrictions on vector data layout,
2352 // replace `llvm.vscale` by an equivalent constant expression
2353 // to benefit from cheap constant propagation.
2354 Type *ScalableVectorTy =
2355 VectorType::get(Type::getInt8Ty(II->getContext()), 1, true);
2356 if (DL->getTypeAllocSize(ScalableVectorTy).getKnownMinSize() == 8) {
2357 auto *Null = Constant::getNullValue(ScalableVectorTy->getPointerTo());
2358 auto *One = ConstantInt::getSigned(II->getType(), 1);
2359 auto *CGep =
2360 ConstantExpr::getGetElementPtr(ScalableVectorTy, Null, One);
2361 replaceAllUsesWith(II, ConstantExpr::getPtrToInt(CGep, II->getType()),
2362 FreshBBs, IsHugeFunc);
2363 II->eraseFromParent();
2364 return true;
2365 }
2366 break;
2367 }
2368 case Intrinsic::masked_gather:
2369 return optimizeGatherScatterInst(II, II->getArgOperand(0));
2370 case Intrinsic::masked_scatter:
2371 return optimizeGatherScatterInst(II, II->getArgOperand(1));
2372 }
2373
2374 SmallVector<Value *, 2> PtrOps;
2375 Type *AccessTy;
2376 if (TLI->getAddrModeArguments(II, PtrOps, AccessTy))
2377 while (!PtrOps.empty()) {
2378 Value *PtrVal = PtrOps.pop_back_val();
2379 unsigned AS = PtrVal->getType()->getPointerAddressSpace();
2380 if (optimizeMemoryInst(II, PtrVal, AccessTy, AS))
2381 return true;
2382 }
2383 }
2384
2385 // From here on out we're working with named functions.
2386 if (!CI->getCalledFunction())
2387 return false;
2388
2389 // Lower all default uses of _chk calls. This is very similar
2390 // to what InstCombineCalls does, but here we are only lowering calls
2391 // to fortified library functions (e.g. __memcpy_chk) that have the default
2392 // "don't know" as the objectsize. Anything else should be left alone.
2393 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
2394 IRBuilder<> Builder(CI);
2395 if (Value *V = Simplifier.optimizeCall(CI, Builder)) {
2396 replaceAllUsesWith(CI, V, FreshBBs, IsHugeFunc);
2397 CI->eraseFromParent();
2398 return true;
2399 }
2400
2401 return false;
2402}
2403
2404/// Look for opportunities to duplicate return instructions to the predecessor
2405/// to enable tail call optimizations. The case it is currently looking for is:
2406/// @code
2407/// bb0:
2408/// %tmp0 = tail call i32 @f0()
2409/// br label %return
2410/// bb1:
2411/// %tmp1 = tail call i32 @f1()
2412/// br label %return
2413/// bb2:
2414/// %tmp2 = tail call i32 @f2()
2415/// br label %return
2416/// return:
2417/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
2418/// ret i32 %retval
2419/// @endcode
2420///
2421/// =>
2422///
2423/// @code
2424/// bb0:
2425/// %tmp0 = tail call i32 @f0()
2426/// ret i32 %tmp0
2427/// bb1:
2428/// %tmp1 = tail call i32 @f1()
2429/// ret i32 %tmp1
2430/// bb2:
2431/// %tmp2 = tail call i32 @f2()
2432/// ret i32 %tmp2
2433/// @endcode
2434bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB,
2435 ModifyDT &ModifiedDT) {
2436 if (!BB->getTerminator())
2437 return false;
2438
2439 ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator());
2440 if (!RetI)
2441 return false;
2442
2443 PHINode *PN = nullptr;
2444 ExtractValueInst *EVI = nullptr;
2445 BitCastInst *BCI = nullptr;
2446 Value *V = RetI->getReturnValue();
2447 if (V) {
2448 BCI = dyn_cast<BitCastInst>(V);
2449 if (BCI)
2450 V = BCI->getOperand(0);
2451
2452 EVI = dyn_cast<ExtractValueInst>(V);
2453 if (EVI) {
2454 V = EVI->getOperand(0);
2455 if (!llvm::all_of(EVI->indices(), [](unsigned idx) { return idx == 0; }))
2456 return false;
2457 }
2458
2459 PN = dyn_cast<PHINode>(V);
2460 if (!PN)
2461 return false;
2462 }
2463
2464 if (PN && PN->getParent() != BB)
2465 return false;
2466
2467 auto isLifetimeEndOrBitCastFor = [](const Instruction *Inst) {
2468 const BitCastInst *BC = dyn_cast<BitCastInst>(Inst);
2469 if (BC && BC->hasOneUse())
2470 Inst = BC->user_back();
2471
2472 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst))
2473 return II->getIntrinsicID() == Intrinsic::lifetime_end;
2474 return false;
2475 };
2476
2477 // Make sure there are no instructions between the first instruction
2478 // and return.
2479 const Instruction *BI = BB->getFirstNonPHI();
2480 // Skip over debug and the bitcast.
2481 while (isa<DbgInfoIntrinsic>(BI) || BI == BCI || BI == EVI ||
2482 isa<PseudoProbeInst>(BI) || isLifetimeEndOrBitCastFor(BI))
2483 BI = BI->getNextNode();
2484 if (BI != RetI)
2485 return false;
2486
2487 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
2488 /// call.
2489 const Function *F = BB->getParent();
2490 SmallVector<BasicBlock *, 4> TailCallBBs;
2491 if (PN) {
2492 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
2493 // Look through bitcasts.
2494 Value *IncomingVal = PN->getIncomingValue(I)->stripPointerCasts();
2495 CallInst *CI = dyn_cast<CallInst>(IncomingVal);
2496 BasicBlock *PredBB = PN->getIncomingBlock(I);
2497 // Make sure the phi value is indeed produced by the tail call.
2498 if (CI && CI->hasOneUse() && CI->getParent() == PredBB &&
2499 TLI->mayBeEmittedAsTailCall(CI) &&
2500 attributesPermitTailCall(F, CI, RetI, *TLI))
2501 TailCallBBs.push_back(PredBB);
2502 }
2503 } else {
2504 SmallPtrSet<BasicBlock *, 4> VisitedBBs;
2505 for (BasicBlock *Pred : predecessors(BB)) {
2506 if (!VisitedBBs.insert(Pred).second)
2507 continue;
2508 if (Instruction *I = Pred->rbegin()->getPrevNonDebugInstruction(true)) {
2509 CallInst *CI = dyn_cast<CallInst>(I);
2510 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI) &&
2511 attributesPermitTailCall(F, CI, RetI, *TLI))
2512 TailCallBBs.push_back(Pred);
2513 }
2514 }
2515 }
2516
2517 bool Changed = false;
2518 for (auto const &TailCallBB : TailCallBBs) {
2519 // Make sure the call instruction is followed by an unconditional branch to
2520 // the return block.
2521 BranchInst *BI = dyn_cast<BranchInst>(TailCallBB->getTerminator());
2522 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
2523 continue;
2524
2525 // Duplicate the return into TailCallBB.
2526 (void)FoldReturnIntoUncondBranch(RetI, BB, TailCallBB);
2527 assert(!VerifyBFIUpdates ||(static_cast <bool> (!VerifyBFIUpdates || BFI->getBlockFreq
(BB) >= BFI->getBlockFreq(TailCallBB)) ? void (0) : __assert_fail
("!VerifyBFIUpdates || BFI->getBlockFreq(BB) >= BFI->getBlockFreq(TailCallBB)"
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 2528, __extension__ __PRETTY_FUNCTION__
))
2528 BFI->getBlockFreq(BB) >= BFI->getBlockFreq(TailCallBB))(static_cast <bool> (!VerifyBFIUpdates || BFI->getBlockFreq
(BB) >= BFI->getBlockFreq(TailCallBB)) ? void (0) : __assert_fail
("!VerifyBFIUpdates || BFI->getBlockFreq(BB) >= BFI->getBlockFreq(TailCallBB)"
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 2528, __extension__ __PRETTY_FUNCTION__
))
;
2529 BFI->setBlockFreq(
2530 BB,
2531 (BFI->getBlockFreq(BB) - BFI->getBlockFreq(TailCallBB)).getFrequency());
2532 ModifiedDT = ModifyDT::ModifyBBDT;
2533 Changed = true;
2534 ++NumRetsDup;
2535 }
2536
2537 // If we eliminated all predecessors of the block, delete the block now.
2538 if (Changed && !BB->hasAddressTaken() && pred_empty(BB))
2539 BB->eraseFromParent();
2540
2541 return Changed;
2542}
2543
2544//===----------------------------------------------------------------------===//
2545// Memory Optimization
2546//===----------------------------------------------------------------------===//
2547
2548namespace {
2549
2550/// This is an extended version of TargetLowering::AddrMode
2551/// which holds actual Value*'s for register values.
2552struct ExtAddrMode : public TargetLowering::AddrMode {
2553 Value *BaseReg = nullptr;
2554 Value *ScaledReg = nullptr;
2555 Value *OriginalValue = nullptr;
2556 bool InBounds = true;
2557
2558 enum FieldName {
2559 NoField = 0x00,
2560 BaseRegField = 0x01,
2561 BaseGVField = 0x02,
2562 BaseOffsField = 0x04,
2563 ScaledRegField = 0x08,
2564 ScaleField = 0x10,
2565 MultipleFields = 0xff
2566 };
2567
2568 ExtAddrMode() = default;
2569
2570 void print(raw_ostream &OS) const;
2571 void dump() const;
2572
2573 FieldName compare(const ExtAddrMode &other) {
2574 // First check that the types are the same on each field, as differing types
2575 // is something we can't cope with later on.
2576 if (BaseReg && other.BaseReg &&
2577 BaseReg->getType() != other.BaseReg->getType())
2578 return MultipleFields;
2579 if (BaseGV && other.BaseGV && BaseGV->getType() != other.BaseGV->getType())
2580 return MultipleFields;
2581 if (ScaledReg && other.ScaledReg &&
2582 ScaledReg->getType() != other.ScaledReg->getType())
2583 return MultipleFields;
2584
2585 // Conservatively reject 'inbounds' mismatches.
2586 if (InBounds != other.InBounds)
2587 return MultipleFields;
2588
2589 // Check each field to see if it differs.
2590 unsigned Result = NoField;
2591 if (BaseReg != other.BaseReg)
2592 Result |= BaseRegField;
2593 if (BaseGV != other.BaseGV)
2594 Result |= BaseGVField;
2595 if (BaseOffs != other.BaseOffs)
2596 Result |= BaseOffsField;
2597 if (ScaledReg != other.ScaledReg)
2598 Result |= ScaledRegField;
2599 // Don't count 0 as being a different scale, because that actually means
2600 // unscaled (which will already be counted by having no ScaledReg).
2601 if (Scale && other.Scale && Scale != other.Scale)
2602 Result |= ScaleField;
2603
2604 if (countPopulation(Result) > 1)
2605 return MultipleFields;
2606 else
2607 return static_cast<FieldName>(Result);
2608 }
2609
2610 // An AddrMode is trivial if it involves no calculation i.e. it is just a base
2611 // with no offset.
2612 bool isTrivial() {
2613 // An AddrMode is (BaseGV + BaseReg + BaseOffs + ScaleReg * Scale) so it is
2614 // trivial if at most one of these terms is nonzero, except that BaseGV and
2615 // BaseReg both being zero actually means a null pointer value, which we
2616 // consider to be 'non-zero' here.
2617 return !BaseOffs && !Scale && !(BaseGV && BaseReg);
2618 }
2619
2620 Value *GetFieldAsValue(FieldName Field, Type *IntPtrTy) {
2621 switch (Field) {
2622 default:
2623 return nullptr;
2624 case BaseRegField:
2625 return BaseReg;
2626 case BaseGVField:
2627 return BaseGV;
2628 case ScaledRegField:
2629 return ScaledReg;
2630 case BaseOffsField:
2631 return ConstantInt::get(IntPtrTy, BaseOffs);
2632 }
2633 }
2634
2635 void SetCombinedField(FieldName Field, Value *V,
2636 const SmallVectorImpl<ExtAddrMode> &AddrModes) {
2637 switch (Field) {
2638 default:
2639 llvm_unreachable("Unhandled fields are expected to be rejected earlier")::llvm::llvm_unreachable_internal("Unhandled fields are expected to be rejected earlier"
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 2639)
;
2640 break;
2641 case ExtAddrMode::BaseRegField:
2642 BaseReg = V;
2643 break;
2644 case ExtAddrMode::BaseGVField:
2645 // A combined BaseGV is an Instruction, not a GlobalValue, so it goes
2646 // in the BaseReg field.
2647 assert(BaseReg == nullptr)(static_cast <bool> (BaseReg == nullptr) ? void (0) : __assert_fail
("BaseReg == nullptr", "llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 2647, __extension__ __PRETTY_FUNCTION__))
;
2648 BaseReg = V;
2649 BaseGV = nullptr;
2650 break;
2651 case ExtAddrMode::ScaledRegField:
2652 ScaledReg = V;
2653 // If we have a mix of scaled and unscaled addrmodes then we want scale
2654 // to be the scale and not zero.
2655 if (!Scale)
2656 for (const ExtAddrMode &AM : AddrModes)
2657 if (AM.Scale) {
2658 Scale = AM.Scale;
2659 break;
2660 }
2661 break;
2662 case ExtAddrMode::BaseOffsField:
2663 // The offset is no longer a constant, so it goes in ScaledReg with a
2664 // scale of 1.
2665 assert(ScaledReg == nullptr)(static_cast <bool> (ScaledReg == nullptr) ? void (0) :
__assert_fail ("ScaledReg == nullptr", "llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 2665, __extension__ __PRETTY_FUNCTION__))
;
2666 ScaledReg = V;
2667 Scale = 1;
2668 BaseOffs = 0;
2669 break;
2670 }
2671 }
2672};
2673
2674#ifndef NDEBUG
2675static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
2676 AM.print(OS);
2677 return OS;
2678}
2679#endif
2680
2681#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2682void ExtAddrMode::print(raw_ostream &OS) const {
2683 bool NeedPlus = false;
2684 OS << "[";
2685 if (InBounds)
2686 OS << "inbounds ";
2687 if (BaseGV) {
2688 OS << (NeedPlus ? " + " : "") << "GV:";
2689 BaseGV->printAsOperand(OS, /*PrintType=*/false);
2690 NeedPlus = true;
2691 }
2692
2693 if (BaseOffs) {
2694 OS << (NeedPlus ? " + " : "") << BaseOffs;
2695 NeedPlus = true;
2696 }
2697
2698 if (BaseReg) {
2699 OS << (NeedPlus ? " + " : "") << "Base:";
2700 BaseReg->printAsOperand(OS, /*PrintType=*/false);
2701 NeedPlus = true;
2702 }
2703 if (Scale) {
2704 OS << (NeedPlus ? " + " : "") << Scale << "*";
2705 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
2706 }
2707
2708 OS << ']';
2709}
2710
2711LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void ExtAddrMode::dump() const {
2712 print(dbgs());
2713 dbgs() << '\n';
2714}
2715#endif
2716
2717} // end anonymous namespace
2718
2719namespace {
2720
2721/// This class provides transaction based operation on the IR.
2722/// Every change made through this class is recorded in the internal state and
2723/// can be undone (rollback) until commit is called.
2724/// CGP does not check if instructions could be speculatively executed when
2725/// moved. Preserving the original location would pessimize the debugging
2726/// experience, as well as negatively impact the quality of sample PGO.
2727class TypePromotionTransaction {
2728 /// This represents the common interface of the individual transaction.
2729 /// Each class implements the logic for doing one specific modification on
2730 /// the IR via the TypePromotionTransaction.
2731 class TypePromotionAction {
2732 protected:
2733 /// The Instruction modified.
2734 Instruction *Inst;
2735
2736 public:
2737 /// Constructor of the action.
2738 /// The constructor performs the related action on the IR.
2739 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
2740
2741 virtual ~TypePromotionAction() = default;
2742
2743 /// Undo the modification done by this action.
2744 /// When this method is called, the IR must be in the same state as it was
2745 /// before this action was applied.
2746 /// \pre Undoing the action works if and only if the IR is in the exact same
2747 /// state as it was directly after this action was applied.
2748 virtual void undo() = 0;
2749
2750 /// Advocate every change made by this action.
2751 /// When the results on the IR of the action are to be kept, it is important
2752 /// to call this function, otherwise hidden information may be kept forever.
2753 virtual void commit() {
2754 // Nothing to be done, this action is not doing anything.
2755 }
2756 };
2757
2758 /// Utility to remember the position of an instruction.
2759 class InsertionHandler {
2760 /// Position of an instruction.
2761 /// Either an instruction:
2762 /// - Is the first in a basic block: BB is used.
2763 /// - Has a previous instruction: PrevInst is used.
2764 union {
2765 Instruction *PrevInst;
2766 BasicBlock *BB;
2767 } Point;
2768
2769 /// Remember whether or not the instruction had a previous instruction.
2770 bool HasPrevInstruction;
2771
2772 public:
2773 /// Record the position of \p Inst.
2774 InsertionHandler(Instruction *Inst) {
2775 BasicBlock::iterator It = Inst->getIterator();
2776 HasPrevInstruction = (It != (Inst->getParent()->begin()));
2777 if (HasPrevInstruction)
2778 Point.PrevInst = &*--It;
2779 else
2780 Point.BB = Inst->getParent();
2781 }
2782
2783 /// Insert \p Inst at the recorded position.
2784 void insert(Instruction *Inst) {
2785 if (HasPrevInstruction) {
2786 if (Inst->getParent())
2787 Inst->removeFromParent();
2788 Inst->insertAfter(Point.PrevInst);
2789 } else {
2790 Instruction *Position = &*Point.BB->getFirstInsertionPt();
2791 if (Inst->getParent())
2792 Inst->moveBefore(Position);
2793 else
2794 Inst->insertBefore(Position);
2795 }
2796 }
2797 };
2798
2799 /// Move an instruction before another.
2800 class InstructionMoveBefore : public TypePromotionAction {
2801 /// Original position of the instruction.
2802 InsertionHandler Position;
2803
2804 public:
2805 /// Move \p Inst before \p Before.
2806 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
2807 : TypePromotionAction(Inst), Position(Inst) {
2808 LLVM_DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Beforedo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Do: move: " << *
Inst << "\nbefore: " << *Before << "\n"; } }
while (false)
2809 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Do: move: " << *
Inst << "\nbefore: " << *Before << "\n"; } }
while (false)
;
2810 Inst->moveBefore(Before);
2811 }
2812
2813 /// Move the instruction back to its original position.
2814 void undo() override {
2815 LLVM_DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Undo: moveBefore: " <<
*Inst << "\n"; } } while (false)
;
2816 Position.insert(Inst);
2817 }
2818 };
2819
2820 /// Set the operand of an instruction with a new value.
2821 class OperandSetter : public TypePromotionAction {
2822 /// Original operand of the instruction.
2823 Value *Origin;
2824
2825 /// Index of the modified instruction.
2826 unsigned Idx;
2827
2828 public:
2829 /// Set \p Idx operand of \p Inst with \p NewVal.
2830 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
2831 : TypePromotionAction(Inst), Idx(Idx) {
2832 LLVM_DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Do: setOperand: " <<
Idx << "\n" << "for:" << *Inst << "\n"
<< "with:" << *NewVal << "\n"; } } while (
false)
2833 << "for:" << *Inst << "\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Do: setOperand: " <<
Idx << "\n" << "for:" << *Inst << "\n"
<< "with:" << *NewVal << "\n"; } } while (
false)
2834 << "with:" << *NewVal << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Do: setOperand: " <<
Idx << "\n" << "for:" << *Inst << "\n"
<< "with:" << *NewVal << "\n"; } } while (
false)
;
2835 Origin = Inst->getOperand(Idx);
2836 Inst->setOperand(Idx, NewVal);
2837 }
2838
2839 /// Restore the original value of the instruction.
2840 void undo() override {
2841 LLVM_DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Undo: setOperand:" <<
Idx << "\n" << "for: " << *Inst << "\n"
<< "with: " << *Origin << "\n"; } } while (
false)
2842 << "for: " << *Inst << "\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Undo: setOperand:" <<
Idx << "\n" << "for: " << *Inst << "\n"
<< "with: " << *Origin << "\n"; } } while (
false)
2843 << "with: " << *Origin << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Undo: setOperand:" <<
Idx << "\n" << "for: " << *Inst << "\n"
<< "with: " << *Origin << "\n"; } } while (
false)
;
2844 Inst->setOperand(Idx, Origin);
2845 }
2846 };
2847
2848 /// Hide the operands of an instruction.
2849 /// Do as if this instruction was not using any of its operands.
2850 class OperandsHider : public TypePromotionAction {
2851 /// The list of original operands.
2852 SmallVector<Value *, 4> OriginalValues;
2853
2854 public:
2855 /// Remove \p Inst from the uses of the operands of \p Inst.
2856 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
2857 LLVM_DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Do: OperandsHider: " <<
*Inst << "\n"; } } while (false)
;
2858 unsigned NumOpnds = Inst->getNumOperands();
2859 OriginalValues.reserve(NumOpnds);
2860 for (unsigned It = 0; It < NumOpnds; ++It) {
2861 // Save the current operand.
2862 Value *Val = Inst->getOperand(It);
2863 OriginalValues.push_back(Val);
2864 // Set a dummy one.
2865 // We could use OperandSetter here, but that would imply an overhead
2866 // that we are not willing to pay.
2867 Inst->setOperand(It, UndefValue::get(Val->getType()));
2868 }
2869 }
2870
2871 /// Restore the original list of uses.
2872 void undo() override {
2873 LLVM_DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Undo: OperandsHider: "
<< *Inst << "\n"; } } while (false)
;
2874 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
2875 Inst->setOperand(It, OriginalValues[It]);
2876 }
2877 };
2878
2879 /// Build a truncate instruction.
2880 class TruncBuilder : public TypePromotionAction {
2881 Value *Val;
2882
2883 public:
2884 /// Build a truncate instruction of \p Opnd producing a \p Ty
2885 /// result.
2886 /// trunc Opnd to Ty.
2887 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
2888 IRBuilder<> Builder(Opnd);
2889 Builder.SetCurrentDebugLocation(DebugLoc());
2890 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
2891 LLVM_DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Do: TruncBuilder: " <<
*Val << "\n"; } } while (false)
;
2892 }
2893
2894 /// Get the built value.
2895 Value *getBuiltValue() { return Val; }
2896
2897 /// Remove the built instruction.
2898 void undo() override {
2899 LLVM_DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Undo: TruncBuilder: " <<
*Val << "\n"; } } while (false)
;
2900 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2901 IVal->eraseFromParent();
2902 }
2903 };
2904
2905 /// Build a sign extension instruction.
2906 class SExtBuilder : public TypePromotionAction {
2907 Value *Val;
2908
2909 public:
2910 /// Build a sign extension instruction of \p Opnd producing a \p Ty
2911 /// result.
2912 /// sext Opnd to Ty.
2913 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
2914 : TypePromotionAction(InsertPt) {
2915 IRBuilder<> Builder(InsertPt);
2916 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
2917 LLVM_DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Do: SExtBuilder: " <<
*Val << "\n"; } } while (false)
;
2918 }
2919
2920 /// Get the built value.
2921 Value *getBuiltValue() { return Val; }
2922
2923 /// Remove the built instruction.
2924 void undo() override {
2925 LLVM_DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Undo: SExtBuilder: " <<
*Val << "\n"; } } while (false)
;
2926 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2927 IVal->eraseFromParent();
2928 }
2929 };
2930
2931 /// Build a zero extension instruction.
2932 class ZExtBuilder : public TypePromotionAction {
2933 Value *Val;
2934
2935 public:
2936 /// Build a zero extension instruction of \p Opnd producing a \p Ty
2937 /// result.
2938 /// zext Opnd to Ty.
2939 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
2940 : TypePromotionAction(InsertPt) {
2941 IRBuilder<> Builder(InsertPt);
2942 Builder.SetCurrentDebugLocation(DebugLoc());
2943 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
2944 LLVM_DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Do: ZExtBuilder: " <<
*Val << "\n"; } } while (false)
;
2945 }
2946
2947 /// Get the built value.
2948 Value *getBuiltValue() { return Val; }
2949
2950 /// Remove the built instruction.
2951 void undo() override {
2952 LLVM_DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Undo: ZExtBuilder: " <<
*Val << "\n"; } } while (false)
;
2953 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2954 IVal->eraseFromParent();
2955 }
2956 };
2957
2958 /// Mutate an instruction to another type.
2959 class TypeMutator : public TypePromotionAction {
2960 /// Record the original type.
2961 Type *OrigTy;
2962
2963 public:
2964 /// Mutate the type of \p Inst into \p NewTy.
2965 TypeMutator(Instruction *Inst, Type *NewTy)
2966 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
2967 LLVM_DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTydo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Do: MutateType: " <<
*Inst << " with " << *NewTy << "\n"; } } while
(false)
2968 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Do: MutateType: " <<
*Inst << " with " << *NewTy << "\n"; } } while
(false)
;
2969 Inst->mutateType(NewTy);
2970 }
2971
2972 /// Mutate the instruction back to its original type.
2973 void undo() override {
2974 LLVM_DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTydo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Undo: MutateType: " <<
*Inst << " with " << *OrigTy << "\n"; } } while
(false)
2975 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Undo: MutateType: " <<
*Inst << " with " << *OrigTy << "\n"; } } while
(false)
;
2976 Inst->mutateType(OrigTy);
2977 }
2978 };
2979
2980 /// Replace the uses of an instruction by another instruction.
2981 class UsesReplacer : public TypePromotionAction {
2982 /// Helper structure to keep track of the replaced uses.
2983 struct InstructionAndIdx {
2984 /// The instruction using the instruction.
2985 Instruction *Inst;
2986
2987 /// The index where this instruction is used for Inst.
2988 unsigned Idx;
2989
2990 InstructionAndIdx(Instruction *Inst, unsigned Idx)
2991 : Inst(Inst), Idx(Idx) {}
2992 };
2993
2994 /// Keep track of the original uses (pair Instruction, Index).
2995 SmallVector<InstructionAndIdx, 4> OriginalUses;
2996 /// Keep track of the debug users.
2997 SmallVector<DbgValueInst *, 1> DbgValues;
2998
2999 /// Keep track of the new value so that we can undo it by replacing
3000 /// instances of the new value with the original value.
3001 Value *New;
3002
3003 using use_iterator = SmallVectorImpl<InstructionAndIdx>::iterator;
3004
3005 public:
3006 /// Replace all the use of \p Inst by \p New.
3007 UsesReplacer(Instruction *Inst, Value *New)
3008 : TypePromotionAction(Inst), New(New) {
3009 LLVM_DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *Newdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Do: UsersReplacer: " <<
*Inst << " with " << *New << "\n"; } } while
(false)
3010 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Do: UsersReplacer: " <<
*Inst << " with " << *New << "\n"; } } while
(false)
;
3011 // Record the original uses.
3012 for (Use &U : Inst->uses()) {
3013 Instruction *UserI = cast<Instruction>(U.getUser());
3014 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
3015 }
3016 // Record the debug uses separately. They are not in the instruction's
3017 // use list, but they are replaced by RAUW.
3018 findDbgValues(DbgValues, Inst);
3019
3020 // Now, we can replace the uses.
3021 Inst->replaceAllUsesWith(New);
3022 }
3023
3024 /// Reassign the original uses of Inst to Inst.
3025 void undo() override {
3026 LLVM_DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Undo: UsersReplacer: "
<< *Inst << "\n"; } } while (false)
;
3027 for (InstructionAndIdx &Use : OriginalUses)
3028 Use.Inst->setOperand(Use.Idx, Inst);
3029 // RAUW has replaced all original uses with references to the new value,
3030 // including the debug uses. Since we are undoing the replacements,
3031 // the original debug uses must also be reinstated to maintain the
3032 // correctness and utility of debug value instructions.
3033 for (auto *DVI : DbgValues)
3034 DVI->replaceVariableLocationOp(New, Inst);
3035 }
3036 };
3037
3038 /// Remove an instruction from the IR.
3039 class InstructionRemover : public TypePromotionAction {
3040 /// Original position of the instruction.
3041 InsertionHandler Inserter;
3042
3043 /// Helper structure to hide all the link to the instruction. In other
3044 /// words, this helps to do as if the instruction was removed.
3045 OperandsHider Hider;
3046
3047 /// Keep track of the uses replaced, if any.
3048 UsesReplacer *Replacer = nullptr;
3049
3050 /// Keep track of instructions removed.
3051 SetOfInstrs &RemovedInsts;
3052
3053 public:
3054 /// Remove all reference of \p Inst and optionally replace all its
3055 /// uses with New.
3056 /// \p RemovedInsts Keep track of the instructions removed by this Action.
3057 /// \pre If !Inst->use_empty(), then New != nullptr
3058 InstructionRemover(Instruction *Inst, SetOfInstrs &RemovedInsts,
3059 Value *New = nullptr)
3060 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
3061 RemovedInsts(RemovedInsts) {
3062 if (New)
3063 Replacer = new UsesReplacer(Inst, New);
3064 LLVM_DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Do: InstructionRemover: "
<< *Inst << "\n"; } } while (false)
;
3065 RemovedInsts.insert(Inst);
3066 /// The instructions removed here will be freed after completing
3067 /// optimizeBlock() for all blocks as we need to keep track of the
3068 /// removed instructions during promotion.
3069 Inst->removeFromParent();
3070 }
3071
3072 ~InstructionRemover() override { delete Replacer; }
3073
3074 /// Resurrect the instruction and reassign it to the proper uses if
3075 /// new value was provided when build this action.
3076 void undo() override {
3077 LLVM_DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Undo: InstructionRemover: "
<< *Inst << "\n"; } } while (false)
;
3078 Inserter.insert(Inst);
3079 if (Replacer)
3080 Replacer->undo();
3081 Hider.undo();
3082 RemovedInsts.erase(Inst);
3083 }
3084 };
3085
3086public:
3087 /// Restoration point.
3088 /// The restoration point is a pointer to an action instead of an iterator
3089 /// because the iterator may be invalidated but not the pointer.
3090 using ConstRestorationPt = const TypePromotionAction *;
3091
3092 TypePromotionTransaction(SetOfInstrs &RemovedInsts)
3093 : RemovedInsts(RemovedInsts) {}
3094
3095 /// Advocate every changes made in that transaction. Return true if any change
3096 /// happen.
3097 bool commit();
3098
3099 /// Undo all the changes made after the given point.
3100 void rollback(ConstRestorationPt Point);
3101
3102 /// Get the current restoration point.
3103 ConstRestorationPt getRestorationPoint() const;
3104
3105 /// \name API for IR modification with state keeping to support rollback.
3106 /// @{
3107 /// Same as Instruction::setOperand.
3108 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
3109
3110 /// Same as Instruction::eraseFromParent.
3111 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
3112
3113 /// Same as Value::replaceAllUsesWith.
3114 void replaceAllUsesWith(Instruction *Inst, Value *New);
3115
3116 /// Same as Value::mutateType.
3117 void mutateType(Instruction *Inst, Type *NewTy);
3118
3119 /// Same as IRBuilder::createTrunc.
3120 Value *createTrunc(Instruction *Opnd, Type *Ty);
3121
3122 /// Same as IRBuilder::createSExt.
3123 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
3124
3125 /// Same as IRBuilder::createZExt.
3126 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
3127
3128 /// Same as Instruction::moveBefore.
3129 void moveBefore(Instruction *Inst, Instruction *Before);
3130 /// @}
3131
3132private:
3133 /// The ordered list of actions made so far.
3134 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
3135
3136 using CommitPt =
3137 SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator;
3138
3139 SetOfInstrs &RemovedInsts;
3140};
3141
3142} // end anonymous namespace
3143
3144void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
3145 Value *NewVal) {
3146 Actions.push_back(std::make_unique<TypePromotionTransaction::OperandSetter>(
3147 Inst, Idx, NewVal));
3148}
3149
3150void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
3151 Value *NewVal) {
3152 Actions.push_back(
3153 std::make_unique<TypePromotionTransaction::InstructionRemover>(
3154 Inst, RemovedInsts, NewVal));
3155}
3156
3157void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
3158 Value *New) {
3159 Actions.push_back(
3160 std::make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
3161}
3162
3163void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
3164 Actions.push_back(
3165 std::make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
3166}
3167
3168Value *TypePromotionTransaction::createTrunc(Instruction *Opnd, Type *Ty) {
3169 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
3170 Value *Val = Ptr->getBuiltValue();
3171 Actions.push_back(std::move(Ptr));
3172 return Val;
3173}
3174
3175Value *TypePromotionTransaction::createSExt(Instruction *Inst, Value *Opnd,
3176 Type *Ty) {
3177 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
3178 Value *Val = Ptr->getBuiltValue();
3179 Actions.push_back(std::move(Ptr));
3180 return Val;
3181}
3182
3183Value *TypePromotionTransaction::createZExt(Instruction *Inst, Value *Opnd,
3184 Type *Ty) {
3185 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
3186 Value *Val = Ptr->getBuiltValue();
3187 Actions.push_back(std::move(Ptr));
3188 return Val;
3189}
3190
3191void TypePromotionTransaction::moveBefore(Instruction *Inst,
3192 Instruction *Before) {
3193 Actions.push_back(
3194 std::make_unique<TypePromotionTransaction::InstructionMoveBefore>(
3195 Inst, Before));
3196}
3197
3198TypePromotionTransaction::ConstRestorationPt
3199TypePromotionTransaction::getRestorationPoint() const {
3200 return !Actions.empty() ? Actions.back().get() : nullptr;
3201}
3202
3203bool TypePromotionTransaction::commit() {
3204 for (std::unique_ptr<TypePromotionAction> &Action : Actions)
3205 Action->commit();
3206 bool Modified = !Actions.empty();
3207 Actions.clear();
3208 return Modified;
3209}
3210
3211void TypePromotionTransaction::rollback(
3212 TypePromotionTransaction::ConstRestorationPt Point) {
3213 while (!Actions.empty() && Point != Actions.back().get()) {
3214 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
3215 Curr->undo();
3216 }
3217}
3218
3219namespace {
3220
3221/// A helper class for matching addressing modes.
3222///
3223/// This encapsulates the logic for matching the target-legal addressing modes.
3224class AddressingModeMatcher {
3225 SmallVectorImpl<Instruction *> &AddrModeInsts;
3226 const TargetLowering &TLI;
3227 const TargetRegisterInfo &TRI;
3228 const DataLayout &DL;
3229 const LoopInfo &LI;
3230 const std::function<const DominatorTree &()> getDTFn;
3231
3232 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
3233 /// the memory instruction that we're computing this address for.
3234 Type *AccessTy;
3235 unsigned AddrSpace;
3236 Instruction *MemoryInst;
3237
3238 /// This is the addressing mode that we're building up. This is
3239 /// part of the return value of this addressing mode matching stuff.
3240 ExtAddrMode &AddrMode;
3241
3242 /// The instructions inserted by other CodeGenPrepare optimizations.
3243 const SetOfInstrs &InsertedInsts;
3244
3245 /// A map from the instructions to their type before promotion.
3246 InstrToOrigTy &PromotedInsts;
3247
3248 /// The ongoing transaction where every action should be registered.
3249 TypePromotionTransaction &TPT;
3250
3251 // A GEP which has too large offset to be folded into the addressing mode.
3252 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP;
3253
3254 /// This is set to true when we should not do profitability checks.
3255 /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
3256 bool IgnoreProfitability;
3257
3258 /// True if we are optimizing for size.
3259 bool OptSize;
3260
3261 ProfileSummaryInfo *PSI;
3262 BlockFrequencyInfo *BFI;
3263
3264 AddressingModeMatcher(
3265 SmallVectorImpl<Instruction *> &AMI, const TargetLowering &TLI,
3266 const TargetRegisterInfo &TRI, const LoopInfo &LI,
3267 const std::function<const DominatorTree &()> getDTFn, Type *AT,
3268 unsigned AS, Instruction *MI, ExtAddrMode &AM,
3269 const SetOfInstrs &InsertedInsts, InstrToOrigTy &PromotedInsts,
3270 TypePromotionTransaction &TPT,
3271 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP,
3272 bool OptSize, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI)
3273 : AddrModeInsts(AMI), TLI(TLI), TRI(TRI),
3274 DL(MI->getModule()->getDataLayout()), LI(LI), getDTFn(getDTFn),
3275 AccessTy(AT), AddrSpace(AS), MemoryInst(MI), AddrMode(AM),
3276 InsertedInsts(InsertedInsts), PromotedInsts(PromotedInsts), TPT(TPT),
3277 LargeOffsetGEP(LargeOffsetGEP), OptSize(OptSize), PSI(PSI), BFI(BFI) {
3278 IgnoreProfitability = false;
3279 }
3280
3281public:
3282 /// Find the maximal addressing mode that a load/store of V can fold,
3283 /// give an access type of AccessTy. This returns a list of involved
3284 /// instructions in AddrModeInsts.
3285 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
3286 /// optimizations.
3287 /// \p PromotedInsts maps the instructions to their type before promotion.
3288 /// \p The ongoing transaction where every action should be registered.
3289 static ExtAddrMode
3290 Match(Value *V, Type *AccessTy, unsigned AS, Instruction *MemoryInst,
3291 SmallVectorImpl<Instruction *> &AddrModeInsts,
3292 const TargetLowering &TLI, const LoopInfo &LI,
3293 const std::function<const DominatorTree &()> getDTFn,
3294 const TargetRegisterInfo &TRI, const SetOfInstrs &InsertedInsts,
3295 InstrToOrigTy &PromotedInsts, TypePromotionTransaction &TPT,
3296 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP,
3297 bool OptSize, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI) {
3298 ExtAddrMode Result;
3299
3300 bool Success = AddressingModeMatcher(AddrModeInsts, TLI, TRI, LI, getDTFn,
3301 AccessTy, AS, MemoryInst, Result,
3302 InsertedInsts, PromotedInsts, TPT,
3303 LargeOffsetGEP, OptSize, PSI, BFI)
3304 .matchAddr(V, 0);
3305 (void)Success;
3306 assert(Success && "Couldn't select *anything*?")(static_cast <bool> (Success && "Couldn't select *anything*?"
) ? void (0) : __assert_fail ("Success && \"Couldn't select *anything*?\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 3306, __extension__ __PRETTY_FUNCTION__
))
;
3307 return Result;
3308 }
3309
3310private:
3311 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
3312 bool matchAddr(Value *Addr, unsigned Depth);
3313 bool matchOperationAddr(User *AddrInst, unsigned Opcode, unsigned Depth,
3314 bool *MovedAway = nullptr);
3315 bool isProfitableToFoldIntoAddressingMode(Instruction *I,
3316 ExtAddrMode &AMBefore,
3317 ExtAddrMode &AMAfter);
3318 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
3319 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
3320 Value *PromotedOperand) const;
3321};
3322
3323class PhiNodeSet;
3324
3325/// An iterator for PhiNodeSet.
3326class PhiNodeSetIterator {
3327 PhiNodeSet *const Set;
3328 size_t CurrentIndex = 0;
3329
3330public:
3331 /// The constructor. Start should point to either a valid element, or be equal
3332 /// to the size of the underlying SmallVector of the PhiNodeSet.
3333 PhiNodeSetIterator(PhiNodeSet *const Set, size_t Start);
3334 PHINode *operator*() const;
3335 PhiNodeSetIterator &operator++();
3336 bool operator==(const PhiNodeSetIterator &RHS) const;
3337 bool operator!=(const PhiNodeSetIterator &RHS) const;
3338};
3339
3340/// Keeps a set of PHINodes.
3341///
3342/// This is a minimal set implementation for a specific use case:
3343/// It is very fast when there are very few elements, but also provides good
3344/// performance when there are many. It is similar to SmallPtrSet, but also
3345/// provides iteration by insertion order, which is deterministic and stable
3346/// across runs. It is also similar to SmallSetVector, but provides removing
3347/// elements in O(1) time. This is achieved by not actually removing the element
3348/// from the underlying vector, so comes at the cost of using more memory, but
3349/// that is fine, since PhiNodeSets are used as short lived objects.
3350class PhiNodeSet {
3351 friend class PhiNodeSetIterator;
3352
3353 using MapType = SmallDenseMap<PHINode *, size_t, 32>;
3354 using iterator = PhiNodeSetIterator;
3355
3356 /// Keeps the elements in the order of their insertion in the underlying
3357 /// vector. To achieve constant time removal, it never deletes any element.
3358 SmallVector<PHINode *, 32> NodeList;
3359
3360 /// Keeps the elements in the underlying set implementation. This (and not the
3361 /// NodeList defined above) is the source of truth on whether an element
3362 /// is actually in the collection.
3363 MapType NodeMap;
3364
3365 /// Points to the first valid (not deleted) element when the set is not empty
3366 /// and the value is not zero. Equals to the size of the underlying vector
3367 /// when the set is empty. When the value is 0, as in the beginning, the
3368 /// first element may or may not be valid.
3369 size_t FirstValidElement = 0;
3370
3371public:
3372 /// Inserts a new element to the collection.
3373 /// \returns true if the element is actually added, i.e. was not in the
3374 /// collection before the operation.
3375 bool insert(PHINode *Ptr) {
3376 if (NodeMap.insert(std::make_pair(Ptr, NodeList.size())).second) {
3377 NodeList.push_back(Ptr);
3378 return true;
3379 }
3380 return false;
3381 }
3382
3383 /// Removes the element from the collection.
3384 /// \returns whether the element is actually removed, i.e. was in the
3385 /// collection before the operation.
3386 bool erase(PHINode *Ptr) {
3387 if (NodeMap.erase(Ptr)) {
3388 SkipRemovedElements(FirstValidElement);
3389 return true;
3390 }
3391 return false;
3392 }
3393
3394 /// Removes all elements and clears the collection.
3395 void clear() {
3396 NodeMap.clear();
3397 NodeList.clear();
3398 FirstValidElement = 0;
3399 }
3400
3401 /// \returns an iterator that will iterate the elements in the order of
3402 /// insertion.
3403 iterator begin() {
3404 if (FirstValidElement == 0)
3405 SkipRemovedElements(FirstValidElement);
3406 return PhiNodeSetIterator(this, FirstValidElement);
3407 }
3408
3409 /// \returns an iterator that points to the end of the collection.
3410 iterator end() { return PhiNodeSetIterator(this, NodeList.size()); }
3411
3412 /// Returns the number of elements in the collection.
3413 size_t size() const { return NodeMap.size(); }
3414
3415 /// \returns 1 if the given element is in the collection, and 0 if otherwise.
3416 size_t count(PHINode *Ptr) const { return NodeMap.count(Ptr); }
3417
3418private:
3419 /// Updates the CurrentIndex so that it will point to a valid element.
3420 ///
3421 /// If the element of NodeList at CurrentIndex is valid, it does not
3422 /// change it. If there are no more valid elements, it updates CurrentIndex
3423 /// to point to the end of the NodeList.
3424 void SkipRemovedElements(size_t &CurrentIndex) {
3425 while (CurrentIndex < NodeList.size()) {
3426 auto it = NodeMap.find(NodeList[CurrentIndex]);
3427 // If the element has been deleted and added again later, NodeMap will
3428 // point to a different index, so CurrentIndex will still be invalid.
3429 if (it != NodeMap.end() && it->second == CurrentIndex)
3430 break;
3431 ++CurrentIndex;
3432 }
3433 }
3434};
3435
3436PhiNodeSetIterator::PhiNodeSetIterator(PhiNodeSet *const Set, size_t Start)
3437 : Set(Set), CurrentIndex(Start) {}
3438
3439PHINode *PhiNodeSetIterator::operator*() const {
3440 assert(CurrentIndex < Set->NodeList.size() &&(static_cast <bool> (CurrentIndex < Set->NodeList
.size() && "PhiNodeSet access out of range") ? void (
0) : __assert_fail ("CurrentIndex < Set->NodeList.size() && \"PhiNodeSet access out of range\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 3441, __extension__ __PRETTY_FUNCTION__
))
3441 "PhiNodeSet access out of range")(static_cast <bool> (CurrentIndex < Set->NodeList
.size() && "PhiNodeSet access out of range") ? void (
0) : __assert_fail ("CurrentIndex < Set->NodeList.size() && \"PhiNodeSet access out of range\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 3441, __extension__ __PRETTY_FUNCTION__
))
;
3442 return Set->NodeList[CurrentIndex];
3443}
3444
3445PhiNodeSetIterator &PhiNodeSetIterator::operator++() {
3446 assert(CurrentIndex < Set->NodeList.size() &&(static_cast <bool> (CurrentIndex < Set->NodeList
.size() && "PhiNodeSet access out of range") ? void (
0) : __assert_fail ("CurrentIndex < Set->NodeList.size() && \"PhiNodeSet access out of range\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 3447, __extension__ __PRETTY_FUNCTION__
))
3447 "PhiNodeSet access out of range")(static_cast <bool> (CurrentIndex < Set->NodeList
.size() && "PhiNodeSet access out of range") ? void (
0) : __assert_fail ("CurrentIndex < Set->NodeList.size() && \"PhiNodeSet access out of range\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 3447, __extension__ __PRETTY_FUNCTION__
))
;
3448 ++CurrentIndex;
3449 Set->SkipRemovedElements(CurrentIndex);
3450 return *this;
3451}
3452
3453bool PhiNodeSetIterator::operator==(const PhiNodeSetIterator &RHS) const {
3454 return CurrentIndex == RHS.CurrentIndex;
3455}
3456
3457bool PhiNodeSetIterator::operator!=(const PhiNodeSetIterator &RHS) const {
3458 return !((*this) == RHS);
3459}
3460
3461/// Keep track of simplification of Phi nodes.
3462/// Accept the set of all phi nodes and erase phi node from this set
3463/// if it is simplified.
3464class SimplificationTracker {
3465 DenseMap<Value *, Value *> Storage;
3466 const SimplifyQuery &SQ;
3467 // Tracks newly created Phi nodes. The elements are iterated by insertion
3468 // order.
3469 PhiNodeSet AllPhiNodes;
3470 // Tracks newly created Select nodes.
3471 SmallPtrSet<SelectInst *, 32> AllSelectNodes;
3472
3473public:
3474 SimplificationTracker(const SimplifyQuery &sq) : SQ(sq) {}
3475
3476 Value *Get(Value *V) {
3477 do {
3478 auto SV = Storage.find(V);
3479 if (SV == Storage.end())
3480 return V;
3481 V = SV->second;
3482 } while (true);
3483 }
3484
3485 Value *Simplify(Value *Val) {
3486 SmallVector<Value *, 32> WorkList;
3487 SmallPtrSet<Value *, 32> Visited;
3488 WorkList.push_back(Val);
3489 while (!WorkList.empty()) {
3490 auto *P = WorkList.pop_back_val();
3491 if (!Visited.insert(P).second)
3492 continue;
3493 if (auto *PI = dyn_cast<Instruction>(P))
3494 if (Value *V = simplifyInstruction(cast<Instruction>(PI), SQ)) {
3495 for (auto *U : PI->users())
3496 WorkList.push_back(cast<Value>(U));
3497 Put(PI, V);
3498 PI->replaceAllUsesWith(V);
3499 if (auto *PHI = dyn_cast<PHINode>(PI))
3500 AllPhiNodes.erase(PHI);
3501 if (auto *Select = dyn_cast<SelectInst>(PI))
3502 AllSelectNodes.erase(Select);
3503 PI->eraseFromParent();
3504 }
3505 }
3506 return Get(Val);
3507 }
3508
3509 void Put(Value *From, Value *To) { Storage.insert({From, To}); }
3510
3511 void ReplacePhi(PHINode *From, PHINode *To) {
3512 Value *OldReplacement = Get(From);
3513 while (OldReplacement != From) {
3514 From = To;
3515 To = dyn_cast<PHINode>(OldReplacement);
3516 OldReplacement = Get(From);
3517 }
3518 assert(To && Get(To) == To && "Replacement PHI node is already replaced.")(static_cast <bool> (To && Get(To) == To &&
"Replacement PHI node is already replaced.") ? void (0) : __assert_fail
("To && Get(To) == To && \"Replacement PHI node is already replaced.\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 3518, __extension__ __PRETTY_FUNCTION__
))
;
3519 Put(From, To);
3520 From->replaceAllUsesWith(To);
3521 AllPhiNodes.erase(From);
3522 From->eraseFromParent();
3523 }
3524
3525 PhiNodeSet &newPhiNodes() { return AllPhiNodes; }
3526
3527 void insertNewPhi(PHINode *PN) { AllPhiNodes.insert(PN); }
3528
3529 void insertNewSelect(SelectInst *SI) { AllSelectNodes.insert(SI); }
3530
3531 unsigned countNewPhiNodes() const { return AllPhiNodes.size(); }
3532
3533 unsigned countNewSelectNodes() const { return AllSelectNodes.size(); }
3534
3535 void destroyNewNodes(Type *CommonType) {
3536 // For safe erasing, replace the uses with dummy value first.
3537 auto *Dummy = PoisonValue::get(CommonType);
3538 for (auto *I : AllPhiNodes) {
3539 I->replaceAllUsesWith(Dummy);
3540 I->eraseFromParent();
3541 }
3542 AllPhiNodes.clear();
3543 for (auto *I : AllSelectNodes) {
3544 I->replaceAllUsesWith(Dummy);
3545 I->eraseFromParent();
3546 }
3547 AllSelectNodes.clear();
3548 }
3549};
3550
3551/// A helper class for combining addressing modes.
3552class AddressingModeCombiner {
3553 typedef DenseMap<Value *, Value *> FoldAddrToValueMapping;
3554 typedef std::pair<PHINode *, PHINode *> PHIPair;
3555
3556private:
3557 /// The addressing modes we've collected.
3558 SmallVector<ExtAddrMode, 16> AddrModes;
3559
3560 /// The field in which the AddrModes differ, when we have more than one.
3561 ExtAddrMode::FieldName DifferentField = ExtAddrMode::NoField;
3562
3563 /// Are the AddrModes that we have all just equal to their original values?
3564 bool AllAddrModesTrivial = true;
3565
3566 /// Common Type for all different fields in addressing modes.
3567 Type *CommonType = nullptr;
3568
3569 /// SimplifyQuery for simplifyInstruction utility.
3570 const SimplifyQuery &SQ;
3571
3572 /// Original Address.
3573 Value *Original;
3574
3575public:
3576 AddressingModeCombiner(const SimplifyQuery &_SQ, Value *OriginalValue)
3577 : SQ(_SQ), Original(OriginalValue) {}
3578
3579 /// Get the combined AddrMode
3580 const ExtAddrMode &getAddrMode() const { return AddrModes[0]; }
3581
3582 /// Add a new AddrMode if it's compatible with the AddrModes we already
3583 /// have.
3584 /// \return True iff we succeeded in doing so.
3585 bool addNewAddrMode(ExtAddrMode &NewAddrMode) {
3586 // Take note of if we have any non-trivial AddrModes, as we need to detect
3587 // when all AddrModes are trivial as then we would introduce a phi or select
3588 // which just duplicates what's already there.
3589 AllAddrModesTrivial = AllAddrModesTrivial && NewAddrMode.isTrivial();
3590
3591 // If this is the first addrmode then everything is fine.
3592 if (AddrModes.empty()) {
3593 AddrModes.emplace_back(NewAddrMode);
3594 return true;
3595 }
3596
3597 // Figure out how different this is from the other address modes, which we
3598 // can do just by comparing against the first one given that we only care
3599 // about the cumulative difference.
3600 ExtAddrMode::FieldName ThisDifferentField =
3601 AddrModes[0].compare(NewAddrMode);
3602 if (DifferentField == ExtAddrMode::NoField)
3603 DifferentField = ThisDifferentField;
3604 else if (DifferentField != ThisDifferentField)
3605 DifferentField = ExtAddrMode::MultipleFields;
3606
3607 // If NewAddrMode differs in more than one dimension we cannot handle it.
3608 bool CanHandle = DifferentField != ExtAddrMode::MultipleFields;
3609
3610 // If Scale Field is different then we reject.
3611 CanHandle = CanHandle && DifferentField != ExtAddrMode::ScaleField;
3612
3613 // We also must reject the case when base offset is different and
3614 // scale reg is not null, we cannot handle this case due to merge of
3615 // different offsets will be used as ScaleReg.
3616 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseOffsField ||
3617 !NewAddrMode.ScaledReg);
3618
3619 // We also must reject the case when GV is different and BaseReg installed
3620 // due to we want to use base reg as a merge of GV values.
3621 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseGVField ||
3622 !NewAddrMode.HasBaseReg);
3623
3624 // Even if NewAddMode is the same we still need to collect it due to
3625 // original value is different. And later we will need all original values
3626 // as anchors during finding the common Phi node.
3627 if (CanHandle)
3628 AddrModes.emplace_back(NewAddrMode);
3629 else
3630 AddrModes.clear();
3631
3632 return CanHandle;
3633 }
3634
3635 /// Combine the addressing modes we've collected into a single
3636 /// addressing mode.
3637 /// \return True iff we successfully combined them or we only had one so
3638 /// didn't need to combine them anyway.
3639 bool combineAddrModes() {
3640 // If we have no AddrModes then they can't be combined.
3641 if (AddrModes.size() == 0)
3642 return false;
3643
3644 // A single AddrMode can trivially be combined.
3645 if (AddrModes.size() == 1 || DifferentField == ExtAddrMode::NoField)
3646 return true;
3647
3648 // If the AddrModes we collected are all just equal to the value they are
3649 // derived from then combining them wouldn't do anything useful.
3650 if (AllAddrModesTrivial)
3651 return false;
3652
3653 if (!addrModeCombiningAllowed())
3654 return false;
3655
3656 // Build a map between <original value, basic block where we saw it> to
3657 // value of base register.
3658 // Bail out if there is no common type.
3659 FoldAddrToValueMapping Map;
3660 if (!initializeMap(Map))
3661 return false;
3662
3663 Value *CommonValue = findCommon(Map);
3664 if (CommonValue)
3665 AddrModes[0].SetCombinedField(DifferentField, CommonValue, AddrModes);
3666 return CommonValue != nullptr;
3667 }
3668
3669private:
3670 /// Initialize Map with anchor values. For address seen
3671 /// we set the value of different field saw in this address.
3672 /// At the same time we find a common type for different field we will
3673 /// use to create new Phi/Select nodes. Keep it in CommonType field.
3674 /// Return false if there is no common type found.
3675 bool initializeMap(FoldAddrToValueMapping &Map) {
3676 // Keep track of keys where the value is null. We will need to replace it
3677 // with constant null when we know the common type.
3678 SmallVector<Value *, 2> NullValue;
3679 Type *IntPtrTy = SQ.DL.getIntPtrType(AddrModes[0].OriginalValue->getType());
3680 for (auto &AM : AddrModes) {
3681 Value *DV = AM.GetFieldAsValue(DifferentField, IntPtrTy);
3682 if (DV) {
3683 auto *Type = DV->getType();
3684 if (CommonType && CommonType != Type)
3685 return false;
3686 CommonType = Type;
3687 Map[AM.OriginalValue] = DV;
3688 } else {
3689 NullValue.push_back(AM.OriginalValue);
3690 }
3691 }
3692 assert(CommonType && "At least one non-null value must be!")(static_cast <bool> (CommonType && "At least one non-null value must be!"
) ? void (0) : __assert_fail ("CommonType && \"At least one non-null value must be!\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 3692, __extension__ __PRETTY_FUNCTION__
))
;
3693 for (auto *V : NullValue)
3694 Map[V] = Constant::getNullValue(CommonType);
3695 return true;
3696 }
3697
3698 /// We have mapping between value A and other value B where B was a field in
3699 /// addressing mode represented by A. Also we have an original value C
3700 /// representing an address we start with. Traversing from C through phi and
3701 /// selects we ended up with A's in a map. This utility function tries to find
3702 /// a value V which is a field in addressing mode C and traversing through phi
3703 /// nodes and selects we will end up in corresponded values B in a map.
3704 /// The utility will create a new Phi/Selects if needed.
3705 // The simple example looks as follows:
3706 // BB1:
3707 // p1 = b1 + 40
3708 // br cond BB2, BB3
3709 // BB2:
3710 // p2 = b2 + 40
3711 // br BB3
3712 // BB3:
3713 // p = phi [p1, BB1], [p2, BB2]
3714 // v = load p
3715 // Map is
3716 // p1 -> b1
3717 // p2 -> b2
3718 // Request is
3719 // p -> ?
3720 // The function tries to find or build phi [b1, BB1], [b2, BB2] in BB3.
3721 Value *findCommon(FoldAddrToValueMapping &Map) {
3722 // Tracks the simplification of newly created phi nodes. The reason we use
3723 // this mapping is because we will add new created Phi nodes in AddrToBase.
3724 // Simplification of Phi nodes is recursive, so some Phi node may
3725 // be simplified after we added it to AddrToBase. In reality this
3726 // simplification is possible only if original phi/selects were not
3727 // simplified yet.
3728 // Using this mapping we can find the current value in AddrToBase.
3729 SimplificationTracker ST(SQ);
3730
3731 // First step, DFS to create PHI nodes for all intermediate blocks.
3732 // Also fill traverse order for the second step.
3733 SmallVector<Value *, 32> TraverseOrder;
3734 InsertPlaceholders(Map, TraverseOrder, ST);
3735
3736 // Second Step, fill new nodes by merged values and simplify if possible.
3737 FillPlaceholders(Map, TraverseOrder, ST);
3738
3739 if (!AddrSinkNewSelects && ST.countNewSelectNodes() > 0) {
3740 ST.destroyNewNodes(CommonType);
3741 return nullptr;
3742 }
3743
3744 // Now we'd like to match New Phi nodes to existed ones.
3745 unsigned PhiNotMatchedCount = 0;
3746 if (!MatchPhiSet(ST, AddrSinkNewPhis, PhiNotMatchedCount)) {
3747 ST.destroyNewNodes(CommonType);
3748 return nullptr;
3749 }
3750
3751 auto *Result = ST.Get(Map.find(Original)->second);
3752 if (Result) {
3753 NumMemoryInstsPhiCreated += ST.countNewPhiNodes() + PhiNotMatchedCount;
3754 NumMemoryInstsSelectCreated += ST.countNewSelectNodes();
3755 }
3756 return Result;
3757 }
3758
3759 /// Try to match PHI node to Candidate.
3760 /// Matcher tracks the matched Phi nodes.
3761 bool MatchPhiNode(PHINode *PHI, PHINode *Candidate,
3762 SmallSetVector<PHIPair, 8> &Matcher,
3763 PhiNodeSet &PhiNodesToMatch) {
3764 SmallVector<PHIPair, 8> WorkList;
3765 Matcher.insert({PHI, Candidate});
3766 SmallSet<PHINode *, 8> MatchedPHIs;
3767 MatchedPHIs.insert(PHI);
3768 WorkList.push_back({PHI, Candidate});
3769 SmallSet<PHIPair, 8> Visited;
3770 while (!WorkList.empty()) {
3771 auto Item = WorkList.pop_back_val();
3772 if (!Visited.insert(Item).second)
3773 continue;
3774 // We iterate over all incoming values to Phi to compare them.
3775 // If values are different and both of them Phi and the first one is a
3776 // Phi we added (subject to match) and both of them is in the same basic
3777 // block then we can match our pair if values match. So we state that
3778 // these values match and add it to work list to verify that.
3779 for (auto *B : Item.first->blocks()) {
3780 Value *FirstValue = Item.first->getIncomingValueForBlock(B);
3781 Value *SecondValue = Item.second->getIncomingValueForBlock(B);
3782 if (FirstValue == SecondValue)
3783 continue;
3784
3785 PHINode *FirstPhi = dyn_cast<PHINode>(FirstValue);
3786 PHINode *SecondPhi = dyn_cast<PHINode>(SecondValue);
3787
3788 // One of them is not Phi or
3789 // The first one is not Phi node from the set we'd like to match or
3790 // Phi nodes from different basic blocks then
3791 // we will not be able to match.
3792 if (!FirstPhi || !SecondPhi || !PhiNodesToMatch.count(FirstPhi) ||
3793 FirstPhi->getParent() != SecondPhi->getParent())
3794 return false;
3795
3796 // If we already matched them then continue.
3797 if (Matcher.count({FirstPhi, SecondPhi}))
3798 continue;
3799 // So the values are different and does not match. So we need them to
3800 // match. (But we register no more than one match per PHI node, so that
3801 // we won't later try to replace them twice.)
3802 if (MatchedPHIs.insert(FirstPhi).second)
3803 Matcher.insert({FirstPhi, SecondPhi});
3804 // But me must check it.
3805 WorkList.push_back({FirstPhi, SecondPhi});
3806 }
3807 }
3808 return true;
3809 }
3810
3811 /// For the given set of PHI nodes (in the SimplificationTracker) try
3812 /// to find their equivalents.
3813 /// Returns false if this matching fails and creation of new Phi is disabled.
3814 bool MatchPhiSet(SimplificationTracker &ST, bool AllowNewPhiNodes,
3815 unsigned &PhiNotMatchedCount) {
3816 // Matched and PhiNodesToMatch iterate their elements in a deterministic
3817 // order, so the replacements (ReplacePhi) are also done in a deterministic
3818 // order.
3819 SmallSetVector<PHIPair, 8> Matched;
3820 SmallPtrSet<PHINode *, 8> WillNotMatch;
3821 PhiNodeSet &PhiNodesToMatch = ST.newPhiNodes();
3822 while (PhiNodesToMatch.size()) {
3823 PHINode *PHI = *PhiNodesToMatch.begin();
3824
3825 // Add us, if no Phi nodes in the basic block we do not match.
3826 WillNotMatch.clear();
3827 WillNotMatch.insert(PHI);
3828
3829 // Traverse all Phis until we found equivalent or fail to do that.
3830 bool IsMatched = false;
3831 for (auto &P : PHI->getParent()->phis()) {
3832 // Skip new Phi nodes.
3833 if (PhiNodesToMatch.count(&P))
3834 continue;
3835 if ((IsMatched = MatchPhiNode(PHI, &P, Matched, PhiNodesToMatch)))
3836 break;
3837 // If it does not match, collect all Phi nodes from matcher.
3838 // if we end up with no match, them all these Phi nodes will not match
3839 // later.
3840 for (auto M : Matched)
3841 WillNotMatch.insert(M.first);
3842 Matched.clear();
3843 }
3844 if (IsMatched) {
3845 // Replace all matched values and erase them.
3846 for (auto MV : Matched)
3847 ST.ReplacePhi(MV.first, MV.second);
3848 Matched.clear();
3849 continue;
3850 }
3851 // If we are not allowed to create new nodes then bail out.
3852 if (!AllowNewPhiNodes)
3853 return false;
3854 // Just remove all seen values in matcher. They will not match anything.
3855 PhiNotMatchedCount += WillNotMatch.size();
3856 for (auto *P : WillNotMatch)
3857 PhiNodesToMatch.erase(P);
3858 }
3859 return true;
3860 }
3861 /// Fill the placeholders with values from predecessors and simplify them.
3862 void FillPlaceholders(FoldAddrToValueMapping &Map,
3863 SmallVectorImpl<Value *> &TraverseOrder,
3864 SimplificationTracker &ST) {
3865 while (!TraverseOrder.empty()) {
3866 Value *Current = TraverseOrder.pop_back_val();
3867 assert(Map.find(Current) != Map.end() && "No node to fill!!!")(static_cast <bool> (Map.find(Current) != Map.end() &&
"No node to fill!!!") ? void (0) : __assert_fail ("Map.find(Current) != Map.end() && \"No node to fill!!!\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 3867, __extension__ __PRETTY_FUNCTION__
))
;
3868 Value *V = Map[Current];
3869
3870 if (SelectInst *Select = dyn_cast<SelectInst>(V)) {
3871 // CurrentValue also must be Select.
3872 auto *CurrentSelect = cast<SelectInst>(Current);
3873 auto *TrueValue = CurrentSelect->getTrueValue();
3874 assert(Map.find(TrueValue) != Map.end() && "No True Value!")(static_cast <bool> (Map.find(TrueValue) != Map.end() &&
"No True Value!") ? void (0) : __assert_fail ("Map.find(TrueValue) != Map.end() && \"No True Value!\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 3874, __extension__ __PRETTY_FUNCTION__
))
;
3875 Select->setTrueValue(ST.Get(Map[TrueValue]));
3876 auto *FalseValue = CurrentSelect->getFalseValue();
3877 assert(Map.find(FalseValue) != Map.end() && "No False Value!")(static_cast <bool> (Map.find(FalseValue) != Map.end() &&
"No False Value!") ? void (0) : __assert_fail ("Map.find(FalseValue) != Map.end() && \"No False Value!\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 3877, __extension__ __PRETTY_FUNCTION__
))
;
3878 Select->setFalseValue(ST.Get(Map[FalseValue]));
3879 } else {
3880 // Must be a Phi node then.
3881 auto *PHI = cast<PHINode>(V);
3882 // Fill the Phi node with values from predecessors.
3883 for (auto *B : predecessors(PHI->getParent())) {
3884 Value *PV = cast<PHINode>(Current)->getIncomingValueForBlock(B);
3885 assert(Map.find(PV) != Map.end() && "No predecessor Value!")(static_cast <bool> (Map.find(PV) != Map.end() &&
"No predecessor Value!") ? void (0) : __assert_fail ("Map.find(PV) != Map.end() && \"No predecessor Value!\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 3885, __extension__ __PRETTY_FUNCTION__
))
;
3886 PHI->addIncoming(ST.Get(Map[PV]), B);
3887 }
3888 }
3889 Map[Current] = ST.Simplify(V);
3890 }
3891 }
3892
3893 /// Starting from original value recursively iterates over def-use chain up to
3894 /// known ending values represented in a map. For each traversed phi/select
3895 /// inserts a placeholder Phi or Select.
3896 /// Reports all new created Phi/Select nodes by adding them to set.
3897 /// Also reports and order in what values have been traversed.
3898 void InsertPlaceholders(FoldAddrToValueMapping &Map,
3899 SmallVectorImpl<Value *> &TraverseOrder,
3900 SimplificationTracker &ST) {
3901 SmallVector<Value *, 32> Worklist;
3902 assert((isa<PHINode>(Original) || isa<SelectInst>(Original)) &&(static_cast <bool> ((isa<PHINode>(Original) || isa
<SelectInst>(Original)) && "Address must be a Phi or Select node"
) ? void (0) : __assert_fail ("(isa<PHINode>(Original) || isa<SelectInst>(Original)) && \"Address must be a Phi or Select node\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 3903, __extension__ __PRETTY_FUNCTION__
))
3903 "Address must be a Phi or Select node")(static_cast <bool> ((isa<PHINode>(Original) || isa
<SelectInst>(Original)) && "Address must be a Phi or Select node"
) ? void (0) : __assert_fail ("(isa<PHINode>(Original) || isa<SelectInst>(Original)) && \"Address must be a Phi or Select node\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 3903, __extension__ __PRETTY_FUNCTION__
))
;
3904 auto *Dummy = PoisonValue::get(CommonType);
3905 Worklist.push_back(Original);
3906 while (!Worklist.empty()) {
3907 Value *Current = Worklist.pop_back_val();
3908 // if it is already visited or it is an ending value then skip it.
3909 if (Map.find(Current) != Map.end())
3910 continue;
3911 TraverseOrder.push_back(Current);
3912
3913 // CurrentValue must be a Phi node or select. All others must be covered
3914 // by anchors.
3915 if (SelectInst *CurrentSelect = dyn_cast<SelectInst>(Current)) {
3916 // Is it OK to get metadata from OrigSelect?!
3917 // Create a Select placeholder with dummy value.
3918 SelectInst *Select = SelectInst::Create(
3919 CurrentSelect->getCondition(), Dummy, Dummy,
3920 CurrentSelect->getName(), CurrentSelect, CurrentSelect);
3921 Map[Current] = Select;
3922 ST.insertNewSelect(Select);
3923 // We are interested in True and False values.
3924 Worklist.push_back(CurrentSelect->getTrueValue());
3925 Worklist.push_back(CurrentSelect->getFalseValue());
3926 } else {
3927 // It must be a Phi node then.
3928 PHINode *CurrentPhi = cast<PHINode>(Current);
3929 unsigned PredCount = CurrentPhi->getNumIncomingValues();
3930 PHINode *PHI =
3931 PHINode::Create(CommonType, PredCount, "sunk_phi", CurrentPhi);
3932 Map[Current] = PHI;
3933 ST.insertNewPhi(PHI);
3934 append_range(Worklist, CurrentPhi->incoming_values());
3935 }
3936 }
3937 }
3938
3939 bool addrModeCombiningAllowed() {
3940 if (DisableComplexAddrModes)
3941 return false;
3942 switch (DifferentField) {
3943 default:
3944 return false;
3945 case ExtAddrMode::BaseRegField:
3946 return AddrSinkCombineBaseReg;
3947 case ExtAddrMode::BaseGVField:
3948 return AddrSinkCombineBaseGV;
3949 case ExtAddrMode::BaseOffsField:
3950 return AddrSinkCombineBaseOffs;
3951 case ExtAddrMode::ScaledRegField:
3952 return AddrSinkCombineScaledReg;
3953 }
3954 }
3955};
3956} // end anonymous namespace
3957
3958/// Try adding ScaleReg*Scale to the current addressing mode.
3959/// Return true and update AddrMode if this addr mode is legal for the target,
3960/// false if not.
3961bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
3962 unsigned Depth) {
3963 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
3964 // mode. Just process that directly.
3965 if (Scale == 1)
3966 return matchAddr(ScaleReg, Depth);
3967
3968 // If the scale is 0, it takes nothing to add this.
3969 if (Scale == 0)
3970 return true;
3971
3972 // If we already have a scale of this value, we can add to it, otherwise, we
3973 // need an available scale field.
3974 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
3975 return false;
3976
3977 ExtAddrMode TestAddrMode = AddrMode;
3978
3979 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
3980 // [A+B + A*7] -> [B+A*8].
3981 TestAddrMode.Scale += Scale;
3982 TestAddrMode.ScaledReg = ScaleReg;
3983
3984 // If the new address isn't legal, bail out.
3985 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
3986 return false;
3987
3988 // It was legal, so commit it.
3989 AddrMode = TestAddrMode;
3990
3991 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
3992 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
3993 // X*Scale + C*Scale to addr mode. If we found available IV increment, do not
3994 // go any further: we can reuse it and cannot eliminate it.
3995 ConstantInt *CI = nullptr;
3996 Value *AddLHS = nullptr;
3997 if (isa<Instruction>(ScaleReg) && // not a constant expr.
3998 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI))) &&
3999 !isIVIncrement(ScaleReg, &LI) && CI->getValue().isSignedIntN(64)) {
4000 TestAddrMode.InBounds = false;
4001 TestAddrMode.ScaledReg = AddLHS;
4002 TestAddrMode.BaseOffs += CI->getSExtValue() * TestAddrMode.Scale;
4003
4004 // If this addressing mode is legal, commit it and remember that we folded
4005 // this instruction.
4006 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
4007 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
4008 AddrMode = TestAddrMode;
4009 return true;
4010 }
4011 // Restore status quo.
4012 TestAddrMode = AddrMode;
4013 }
4014
4015 // If this is an add recurrence with a constant step, return the increment
4016 // instruction and the canonicalized step.
4017 auto GetConstantStep =
4018 [this](const Value *V) -> Optional<std::pair<Instruction *, APInt>> {
4019 auto *PN = dyn_cast<PHINode>(V);
4020 if (!PN)
4021 return None;
4022 auto IVInc = getIVIncrement(PN, &LI);
4023 if (!IVInc)
4024 return None;
4025 // TODO: The result of the intrinsics above is two-compliment. However when
4026 // IV inc is expressed as add or sub, iv.next is potentially a poison value.
4027 // If it has nuw or nsw flags, we need to make sure that these flags are
4028 // inferrable at the point of memory instruction. Otherwise we are replacing
4029 // well-defined two-compliment computation with poison. Currently, to avoid
4030 // potentially complex analysis needed to prove this, we reject such cases.
4031 if (auto *OIVInc = dyn_cast<OverflowingBinaryOperator>(IVInc->first))
4032 if (OIVInc->hasNoSignedWrap() || OIVInc->hasNoUnsignedWrap())
4033 return None;
4034 if (auto *ConstantStep = dyn_cast<ConstantInt>(IVInc->second))
4035 return std::make_pair(IVInc->first, ConstantStep->getValue());
4036 return None;
4037 };
4038
4039 // Try to account for the following special case:
4040 // 1. ScaleReg is an inductive variable;
4041 // 2. We use it with non-zero offset;
4042 // 3. IV's increment is available at the point of memory instruction.
4043 //
4044 // In this case, we may reuse the IV increment instead of the IV Phi to
4045 // achieve the following advantages:
4046 // 1. If IV step matches the offset, we will have no need in the offset;
4047 // 2. Even if they don't match, we will reduce the overlap of living IV
4048 // and IV increment, that will potentially lead to better register
4049 // assignment.
4050 if (AddrMode.BaseOffs) {
4051 if (auto IVStep = GetConstantStep(ScaleReg)) {
4052 Instruction *IVInc = IVStep->first;
4053 // The following assert is important to ensure a lack of infinite loops.
4054 // This transforms is (intentionally) the inverse of the one just above.
4055 // If they don't agree on the definition of an increment, we'd alternate
4056 // back and forth indefinitely.
4057 assert(isIVIncrement(IVInc, &LI) && "implied by GetConstantStep")(static_cast <bool> (isIVIncrement(IVInc, &LI) &&
"implied by GetConstantStep") ? void (0) : __assert_fail ("isIVIncrement(IVInc, &LI) && \"implied by GetConstantStep\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 4057, __extension__ __PRETTY_FUNCTION__
))
;
4058 APInt Step = IVStep->second;
4059 APInt Offset = Step * AddrMode.Scale;
4060 if (Offset.isSignedIntN(64)) {
4061 TestAddrMode.InBounds = false;
4062 TestAddrMode.ScaledReg = IVInc;
4063 TestAddrMode.BaseOffs -= Offset.getLimitedValue();
4064 // If this addressing mode is legal, commit it..
4065 // (Note that we defer the (expensive) domtree base legality check
4066 // to the very last possible point.)
4067 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace) &&
4068 getDTFn().dominates(IVInc, MemoryInst)) {
4069 AddrModeInsts.push_back(cast<Instruction>(IVInc));
4070 AddrMode = TestAddrMode;
4071 return true;
4072 }
4073 // Restore status quo.
4074 TestAddrMode = AddrMode;
4075 }
4076 }
4077 }
4078
4079 // Otherwise, just return what we have.
4080 return true;
4081}
4082
4083/// This is a little filter, which returns true if an addressing computation
4084/// involving I might be folded into a load/store accessing it.
4085/// This doesn't need to be perfect, but needs to accept at least
4086/// the set of instructions that MatchOperationAddr can.
4087static bool MightBeFoldableInst(Instruction *I) {
4088 switch (I->getOpcode()) {
4089 case Instruction::BitCast:
4090 case Instruction::AddrSpaceCast:
4091 // Don't touch identity bitcasts.
4092 if (I->getType() == I->getOperand(0)->getType())
4093 return false;
4094 return I->getType()->isIntOrPtrTy();
4095 case Instruction::PtrToInt:
4096 // PtrToInt is always a noop, as we know that the int type is pointer sized.
4097 return true;
4098 case Instruction::IntToPtr:
4099 // We know the input is intptr_t, so this is foldable.
4100 return true;
4101 case Instruction::Add:
4102 return true;
4103 case Instruction::Mul:
4104 case Instruction::Shl:
4105 // Can only handle X*C and X << C.
4106 return isa<ConstantInt>(I->getOperand(1));
4107 case Instruction::GetElementPtr:
4108 return true;
4109 default:
4110 return false;
4111 }
4112}
4113
4114/// Check whether or not \p Val is a legal instruction for \p TLI.
4115/// \note \p Val is assumed to be the product of some type promotion.
4116/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
4117/// to be legal, as the non-promoted value would have had the same state.
4118static bool isPromotedInstructionLegal(const TargetLowering &TLI,
4119 const DataLayout &DL, Value *Val) {
4120 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
4121 if (!PromotedInst)
4122 return false;
4123 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
4124 // If the ISDOpcode is undefined, it was undefined before the promotion.
4125 if (!ISDOpcode)
4126 return true;
4127 // Otherwise, check if the promoted instruction is legal or not.
4128 return TLI.isOperationLegalOrCustom(
4129 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
4130}
4131
4132namespace {
4133
4134/// Hepler class to perform type promotion.
4135class TypePromotionHelper {
4136 /// Utility function to add a promoted instruction \p ExtOpnd to
4137 /// \p PromotedInsts and record the type of extension we have seen.
4138 static void addPromotedInst(InstrToOrigTy &PromotedInsts,
4139 Instruction *ExtOpnd, bool IsSExt) {
4140 ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension;
4141 InstrToOrigTy::iterator It = PromotedInsts.find(ExtOpnd);
4142 if (It != PromotedInsts.end()) {
4143 // If the new extension is same as original, the information in
4144 // PromotedInsts[ExtOpnd] is still correct.
4145 if (It->second.getInt() == ExtTy)
4146 return;
4147
4148 // Now the new extension is different from old extension, we make
4149 // the type information invalid by setting extension type to
4150 // BothExtension.
4151 ExtTy = BothExtension;
4152 }
4153 PromotedInsts[ExtOpnd] = TypeIsSExt(ExtOpnd->getType(), ExtTy);
4154 }
4155
4156 /// Utility function to query the original type of instruction \p Opnd
4157 /// with a matched extension type. If the extension doesn't match, we
4158 /// cannot use the information we had on the original type.
4159 /// BothExtension doesn't match any extension type.
4160 static const Type *getOrigType(const InstrToOrigTy &PromotedInsts,
4161 Instruction *Opnd, bool IsSExt) {
4162 ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension;
4163 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
4164 if (It != PromotedInsts.end() && It->second.getInt() == ExtTy)
4165 return It->second.getPointer();
4166 return nullptr;
4167 }
4168
4169 /// Utility function to check whether or not a sign or zero extension
4170 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
4171 /// either using the operands of \p Inst or promoting \p Inst.
4172 /// The type of the extension is defined by \p IsSExt.
4173 /// In other words, check if:
4174 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
4175 /// #1 Promotion applies:
4176 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
4177 /// #2 Operand reuses:
4178 /// ext opnd1 to ConsideredExtType.
4179 /// \p PromotedInsts maps the instructions to their type before promotion.
4180 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
4181 const InstrToOrigTy &PromotedInsts, bool IsSExt);
4182
4183 /// Utility function to determine if \p OpIdx should be promoted when
4184 /// promoting \p Inst.
4185 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
4186 return !(isa<SelectInst>(Inst) && OpIdx == 0);
4187 }
4188
4189 /// Utility function to promote the operand of \p Ext when this
4190 /// operand is a promotable trunc or sext or zext.
4191 /// \p PromotedInsts maps the instructions to their type before promotion.
4192 /// \p CreatedInstsCost[out] contains the cost of all instructions
4193 /// created to promote the operand of Ext.
4194 /// Newly added extensions are inserted in \p Exts.
4195 /// Newly added truncates are inserted in \p Truncs.
4196 /// Should never be called directly.
4197 /// \return The promoted value which is used instead of Ext.
4198 static Value *promoteOperandForTruncAndAnyExt(
4199 Instruction *Ext, TypePromotionTransaction &TPT,
4200 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4201 SmallVectorImpl<Instruction *> *Exts,
4202 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
4203
4204 /// Utility function to promote the operand of \p Ext when this
4205 /// operand is promotable and is not a supported trunc or sext.
4206 /// \p PromotedInsts maps the instructions to their type before promotion.
4207 /// \p CreatedInstsCost[out] contains the cost of all the instructions
4208 /// created to promote the operand of Ext.
4209 /// Newly added extensions are inserted in \p Exts.
4210 /// Newly added truncates are inserted in \p Truncs.
4211 /// Should never be called directly.
4212 /// \return The promoted value which is used instead of Ext.
4213 static Value *promoteOperandForOther(Instruction *Ext,
4214 TypePromotionTransaction &TPT,
4215 InstrToOrigTy &PromotedInsts,
4216 unsigned &CreatedInstsCost,
4217 SmallVectorImpl<Instruction *> *Exts,
4218 SmallVectorImpl<Instruction *> *Truncs,
4219 const TargetLowering &TLI, bool IsSExt);
4220
4221 /// \see promoteOperandForOther.
4222 static Value *signExtendOperandForOther(
4223 Instruction *Ext, TypePromotionTransaction &TPT,
4224 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4225 SmallVectorImpl<Instruction *> *Exts,
4226 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
4227 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
4228 Exts, Truncs, TLI, true);
4229 }
4230
4231 /// \see promoteOperandForOther.
4232 static Value *zeroExtendOperandForOther(
4233 Instruction *Ext, TypePromotionTransaction &TPT,
4234 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4235 SmallVectorImpl<Instruction *> *Exts,
4236 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
4237 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
4238 Exts, Truncs, TLI, false);
4239 }
4240
4241public:
4242 /// Type for the utility function that promotes the operand of Ext.
4243 using Action = Value *(*)(Instruction *Ext, TypePromotionTransaction &TPT,
4244 InstrToOrigTy &PromotedInsts,
4245 unsigned &CreatedInstsCost,
4246 SmallVectorImpl<Instruction *> *Exts,
4247 SmallVectorImpl<Instruction *> *Truncs,
4248 const TargetLowering &TLI);
4249
4250 /// Given a sign/zero extend instruction \p Ext, return the appropriate
4251 /// action to promote the operand of \p Ext instead of using Ext.
4252 /// \return NULL if no promotable action is possible with the current
4253 /// sign extension.
4254 /// \p InsertedInsts keeps track of all the instructions inserted by the
4255 /// other CodeGenPrepare optimizations. This information is important
4256 /// because we do not want to promote these instructions as CodeGenPrepare
4257 /// will reinsert them later. Thus creating an infinite loop: create/remove.
4258 /// \p PromotedInsts maps the instructions to their type before promotion.
4259 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
4260 const TargetLowering &TLI,
4261 const InstrToOrigTy &PromotedInsts);
4262};
4263
4264} // end anonymous namespace
4265
4266bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
4267 Type *ConsideredExtType,
4268 const InstrToOrigTy &PromotedInsts,
4269 bool IsSExt) {
4270 // The promotion helper does not know how to deal with vector types yet.
4271 // To be able to fix that, we would need to fix the places where we
4272 // statically extend, e.g., constants and such.
4273 if (Inst->getType()->isVectorTy())
4274 return false;
4275
4276 // We can always get through zext.
4277 if (isa<ZExtInst>(Inst))
4278 return true;
4279
4280 // sext(sext) is ok too.
4281 if (IsSExt && isa<SExtInst>(Inst))
4282 return true;
4283
4284 // We can get through binary operator, if it is legal. In other words, the
4285 // binary operator must have a nuw or nsw flag.
4286 if (const auto *BinOp = dyn_cast<BinaryOperator>(Inst))
4287 if (isa<OverflowingBinaryOperator>(BinOp) &&
4288 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
4289 (IsSExt && BinOp->hasNoSignedWrap())))
4290 return true;
4291
4292 // ext(and(opnd, cst)) --> and(ext(opnd), ext(cst))
4293 if ((Inst->getOpcode() == Instruction::And ||
4294 Inst->getOpcode() == Instruction::Or))
4295 return true;
4296
4297 // ext(xor(opnd, cst)) --> xor(ext(opnd), ext(cst))
4298 if (Inst->getOpcode() == Instruction::Xor) {
4299 // Make sure it is not a NOT.
4300 if (const auto *Cst = dyn_cast<ConstantInt>(Inst->getOperand(1)))
4301 if (!Cst->getValue().isAllOnes())
4302 return true;
4303 }
4304
4305 // zext(shrl(opnd, cst)) --> shrl(zext(opnd), zext(cst))
4306 // It may change a poisoned value into a regular value, like
4307 // zext i32 (shrl i8 %val, 12) --> shrl i32 (zext i8 %val), 12
4308 // poisoned value regular value
4309 // It should be OK since undef covers valid value.
4310 if (Inst->getOpcode() == Instruction::LShr && !IsSExt)
4311 return true;
4312
4313 // and(ext(shl(opnd, cst)), cst) --> and(shl(ext(opnd), ext(cst)), cst)
4314 // It may change a poisoned value into a regular value, like
4315 // zext i32 (shl i8 %val, 12) --> shl i32 (zext i8 %val), 12
4316 // poisoned value regular value
4317 // It should be OK since undef covers valid value.
4318 if (Inst->getOpcode() == Instruction::Shl && Inst->hasOneUse()) {
4319 const auto *ExtInst = cast<const Instruction>(*Inst->user_begin());
4320 if (ExtInst->hasOneUse()) {
4321 const auto *AndInst = dyn_cast<const Instruction>(*ExtInst->user_begin());
4322 if (AndInst && AndInst->getOpcode() == Instruction::And) {
4323 const auto *Cst = dyn_cast<ConstantInt>(AndInst->getOperand(1));
4324 if (Cst &&
4325 Cst->getValue().isIntN(Inst->getType()->getIntegerBitWidth()))
4326 return true;
4327 }
4328 }
4329 }
4330
4331 // Check if we can do the following simplification.
4332 // ext(trunc(opnd)) --> ext(opnd)
4333 if (!isa<TruncInst>(Inst))
4334 return false;
4335
4336 Value *OpndVal = Inst->getOperand(0);
4337 // Check if we can use this operand in the extension.
4338 // If the type is larger than the result type of the extension, we cannot.
4339 if (!OpndVal->getType()->isIntegerTy() ||
4340 OpndVal->getType()->getIntegerBitWidth() >
4341 ConsideredExtType->getIntegerBitWidth())
4342 return false;
4343
4344 // If the operand of the truncate is not an instruction, we will not have
4345 // any information on the dropped bits.
4346 // (Actually we could for constant but it is not worth the extra logic).
4347 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
4348 if (!Opnd)
4349 return false;
4350
4351 // Check if the source of the type is narrow enough.
4352 // I.e., check that trunc just drops extended bits of the same kind of
4353 // the extension.
4354 // #1 get the type of the operand and check the kind of the extended bits.
4355 const Type *OpndType = getOrigType(PromotedInsts, Opnd, IsSExt);
4356 if (OpndType)
4357 ;
4358 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
4359 OpndType = Opnd->getOperand(0)->getType();
4360 else
4361 return false;
4362
4363 // #2 check that the truncate just drops extended bits.
4364 return Inst->getType()->getIntegerBitWidth() >=
4365 OpndType->getIntegerBitWidth();
4366}
4367
4368TypePromotionHelper::Action TypePromotionHelper::getAction(
4369 Instruction *Ext, const SetOfInstrs &InsertedInsts,
4370 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
4371 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&(static_cast <bool> ((isa<SExtInst>(Ext) || isa<
ZExtInst>(Ext)) && "Unexpected instruction type") ?
void (0) : __assert_fail ("(isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) && \"Unexpected instruction type\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 4372, __extension__ __PRETTY_FUNCTION__
))
4372 "Unexpected instruction type")(static_cast <bool> ((isa<SExtInst>(Ext) || isa<
ZExtInst>(Ext)) && "Unexpected instruction type") ?
void (0) : __assert_fail ("(isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) && \"Unexpected instruction type\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 4372, __extension__ __PRETTY_FUNCTION__
))
;
4373 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
4374 Type *ExtTy = Ext->getType();
4375 bool IsSExt = isa<SExtInst>(Ext);
4376 // If the operand of the extension is not an instruction, we cannot
4377 // get through.
4378 // If it, check we can get through.
4379 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
4380 return nullptr;
4381
4382 // Do not promote if the operand has been added by codegenprepare.
4383 // Otherwise, it means we are undoing an optimization that is likely to be
4384 // redone, thus causing potential infinite loop.
4385 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
4386 return nullptr;
4387
4388 // SExt or Trunc instructions.
4389 // Return the related handler.
4390 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
4391 isa<ZExtInst>(ExtOpnd))
4392 return promoteOperandForTruncAndAnyExt;
4393
4394 // Regular instruction.
4395 // Abort early if we will have to insert non-free instructions.
4396 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
4397 return nullptr;
4398 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
4399}
4400
4401Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
4402 Instruction *SExt, TypePromotionTransaction &TPT,
4403 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4404 SmallVectorImpl<Instruction *> *Exts,
4405 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
4406 // By construction, the operand of SExt is an instruction. Otherwise we cannot
4407 // get through it and this method should not be called.
4408 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
4409 Value *ExtVal = SExt;
4410 bool HasMergedNonFreeExt = false;
4411 if (isa<ZExtInst>(SExtOpnd)) {
4412 // Replace s|zext(zext(opnd))
4413 // => zext(opnd).
4414 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
4415 Value *ZExt =
4416 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
4417 TPT.replaceAllUsesWith(SExt, ZExt);
4418 TPT.eraseInstruction(SExt);
4419 ExtVal = ZExt;
4420 } else {
4421 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
4422 // => z|sext(opnd).
4423 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
4424 }
4425 CreatedInstsCost = 0;
4426
4427 // Remove dead code.
4428 if (SExtOpnd->use_empty())
4429 TPT.eraseInstruction(SExtOpnd);
4430
4431 // Check if the extension is still needed.
4432 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
4433 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
4434 if (ExtInst) {
4435 if (Exts)
4436 Exts->push_back(ExtInst);
4437 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
4438 }
4439 return ExtVal;
4440 }
4441
4442 // At this point we have: ext ty opnd to ty.
4443 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
4444 Value *NextVal = ExtInst->getOperand(0);
4445 TPT.eraseInstruction(ExtInst, NextVal);
4446 return NextVal;
4447}
4448
4449Value *TypePromotionHelper::promoteOperandForOther(
4450 Instruction *Ext, TypePromotionTransaction &TPT,
4451 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4452 SmallVectorImpl<Instruction *> *Exts,
4453 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
4454 bool IsSExt) {
4455 // By construction, the operand of Ext is an instruction. Otherwise we cannot
4456 // get through it and this method should not be called.
4457 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
4458 CreatedInstsCost = 0;
4459 if (!ExtOpnd->hasOneUse()) {
4460 // ExtOpnd will be promoted.
4461 // All its uses, but Ext, will need to use a truncated value of the
4462 // promoted version.
4463 // Create the truncate now.
4464 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
4465 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
4466 // Insert it just after the definition.
4467 ITrunc->moveAfter(ExtOpnd);
4468 if (Truncs)
4469 Truncs->push_back(ITrunc);
4470 }
4471
4472 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
4473 // Restore the operand of Ext (which has been replaced by the previous call
4474 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
4475 TPT.setOperand(Ext, 0, ExtOpnd);
4476 }
4477
4478 // Get through the Instruction:
4479 // 1. Update its type.
4480 // 2. Replace the uses of Ext by Inst.
4481 // 3. Extend each operand that needs to be extended.
4482
4483 // Remember the original type of the instruction before promotion.
4484 // This is useful to know that the high bits are sign extended bits.
4485 addPromotedInst(PromotedInsts, ExtOpnd, IsSExt);
4486 // Step #1.
4487 TPT.mutateType(ExtOpnd, Ext->getType());
4488 // Step #2.
4489 TPT.replaceAllUsesWith(Ext, ExtOpnd);
4490 // Step #3.
4491 Instruction *ExtForOpnd = Ext;
4492
4493 LLVM_DEBUG(dbgs() << "Propagate Ext to operands\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Propagate Ext to operands\n"
; } } while (false)
;
4494 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
4495 ++OpIdx) {
4496 LLVM_DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Operand:\n" << *
(ExtOpnd->getOperand(OpIdx)) << '\n'; } } while (false
)
;
4497 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
4498 !shouldExtOperand(ExtOpnd, OpIdx)) {
4499 LLVM_DEBUG(dbgs() << "No need to propagate\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "No need to propagate\n"
; } } while (false)
;
4500 continue;
4501 }
4502 // Check if we can statically extend the operand.
4503 Value *Opnd = ExtOpnd->getOperand(OpIdx);
4504 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
4505 LLVM_DEBUG(dbgs() << "Statically extend\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Statically extend\n"; }
} while (false)
;
4506 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
4507 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
4508 : Cst->getValue().zext(BitWidth);
4509 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
4510 continue;
4511 }
4512 // UndefValue are typed, so we have to statically sign extend them.
4513 if (isa<UndefValue>(Opnd)) {
4514 LLVM_DEBUG(dbgs() << "Statically extend\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Statically extend\n"; }
} while (false)
;
4515 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
4516 continue;
4517 }
4518
4519 // Otherwise we have to explicitly sign extend the operand.
4520 // Check if Ext was reused to extend an operand.
4521 if (!ExtForOpnd) {
4522 // If yes, create a new one.
4523 LLVM_DEBUG(dbgs() << "More operands to ext\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "More operands to ext\n"
; } } while (false)
;
4524 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
4525 : TPT.createZExt(Ext, Opnd, Ext->getType());
4526 if (!isa<Instruction>(ValForExtOpnd)) {
4527 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
4528 continue;
4529 }
4530 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
4531 }
4532 if (Exts)
4533 Exts->push_back(ExtForOpnd);
4534 TPT.setOperand(ExtForOpnd, 0, Opnd);
4535
4536 // Move the sign extension before the insertion point.
4537 TPT.moveBefore(ExtForOpnd, ExtOpnd);
4538 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
4539 CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
4540 // If more sext are required, new instructions will have to be created.
4541 ExtForOpnd = nullptr;
4542 }
4543 if (ExtForOpnd == Ext) {
4544 LLVM_DEBUG(dbgs() << "Extension is useless now\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Extension is useless now\n"
; } } while (false)
;
4545 TPT.eraseInstruction(Ext);
4546 }
4547 return ExtOpnd;
4548}
4549
4550/// Check whether or not promoting an instruction to a wider type is profitable.
4551/// \p NewCost gives the cost of extension instructions created by the
4552/// promotion.
4553/// \p OldCost gives the cost of extension instructions before the promotion
4554/// plus the number of instructions that have been
4555/// matched in the addressing mode the promotion.
4556/// \p PromotedOperand is the value that has been promoted.
4557/// \return True if the promotion is profitable, false otherwise.
4558bool AddressingModeMatcher::isPromotionProfitable(
4559 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
4560 LLVM_DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCostdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "OldCost: " << OldCost
<< "\tNewCost: " << NewCost << '\n'; } } while
(false)
4561 << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "OldCost: " << OldCost
<< "\tNewCost: " << NewCost << '\n'; } } while
(false)
;
4562 // The cost of the new extensions is greater than the cost of the
4563 // old extension plus what we folded.
4564 // This is not profitable.
4565 if (NewCost > OldCost)
4566 return false;
4567 if (NewCost < OldCost)
4568 return true;
4569 // The promotion is neutral but it may help folding the sign extension in
4570 // loads for instance.
4571 // Check that we did not create an illegal instruction.
4572 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
4573}
4574
4575/// Given an instruction or constant expr, see if we can fold the operation
4576/// into the addressing mode. If so, update the addressing mode and return
4577/// true, otherwise return false without modifying AddrMode.
4578/// If \p MovedAway is not NULL, it contains the information of whether or
4579/// not AddrInst has to be folded into the addressing mode on success.
4580/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
4581/// because it has been moved away.
4582/// Thus AddrInst must not be added in the matched instructions.
4583/// This state can happen when AddrInst is a sext, since it may be moved away.
4584/// Therefore, AddrInst may not be valid when MovedAway is true and it must
4585/// not be referenced anymore.
4586bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
4587 unsigned Depth,
4588 bool *MovedAway) {
4589 // Avoid exponential behavior on extremely deep expression trees.
4590 if (Depth >= 5)
4591 return false;
4592
4593 // By default, all matched instructions stay in place.
4594 if (MovedAway)
4595 *MovedAway = false;
4596
4597 switch (Opcode) {
4598 case Instruction::PtrToInt:
4599 // PtrToInt is always a noop, as we know that the int type is pointer sized.
4600 return matchAddr(AddrInst->getOperand(0), Depth);
4601 case Instruction::IntToPtr: {
4602 auto AS = AddrInst->getType()->getPointerAddressSpace();
4603 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
4604 // This inttoptr is a no-op if the integer type is pointer sized.
4605 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
4606 return matchAddr(AddrInst->getOperand(0), Depth);
4607 return false;
4608 }
4609 case Instruction::BitCast:
4610 // BitCast is always a noop, and we can handle it as long as it is
4611 // int->int or pointer->pointer (we don't want int<->fp or something).
4612 if (AddrInst->getOperand(0)->getType()->isIntOrPtrTy() &&
4613 // Don't touch identity bitcasts. These were probably put here by LSR,
4614 // and we don't want to mess around with them. Assume it knows what it
4615 // is doing.
4616 AddrInst->getOperand(0)->getType() != AddrInst->getType())
4617 return matchAddr(AddrInst->getOperand(0), Depth);
4618 return false;
4619 case Instruction::AddrSpaceCast: {
4620 unsigned SrcAS =
4621 AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
4622 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
4623 if (TLI.getTargetMachine().isNoopAddrSpaceCast(SrcAS, DestAS))
4624 return matchAddr(AddrInst->getOperand(0), Depth);
4625 return false;
4626 }
4627 case Instruction::Add: {
4628 // Check to see if we can merge in the RHS then the LHS. If so, we win.
4629 ExtAddrMode BackupAddrMode = AddrMode;
4630 unsigned OldSize = AddrModeInsts.size();
4631 // Start a transaction at this point.
4632 // The LHS may match but not the RHS.
4633 // Therefore, we need a higher level restoration point to undo partially
4634 // matched operation.
4635 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4636 TPT.getRestorationPoint();
4637
4638 AddrMode.InBounds = false;
4639 if (matchAddr(AddrInst->getOperand(1), Depth + 1) &&
4640 matchAddr(AddrInst->getOperand(0), Depth + 1))
4641 return true;
4642
4643 // Restore the old addr mode info.
4644 AddrMode = BackupAddrMode;
4645 AddrModeInsts.resize(OldSize);
4646 TPT.rollback(LastKnownGood);
4647
4648 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
4649 if (matchAddr(AddrInst->getOperand(0), Depth + 1) &&
4650 matchAddr(AddrInst->getOperand(1), Depth + 1))
4651 return true;
4652
4653 // Otherwise we definitely can't merge the ADD in.
4654 AddrMode = BackupAddrMode;
4655 AddrModeInsts.resize(OldSize);
4656 TPT.rollback(LastKnownGood);
4657 break;
4658 }
4659 // case Instruction::Or:
4660 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
4661 // break;
4662 case Instruction::Mul:
4663 case Instruction::Shl: {
4664 // Can only handle X*C and X << C.
4665 AddrMode.InBounds = false;
4666 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
4667 if (!RHS || RHS->getBitWidth() > 64)
4668 return false;
4669 int64_t Scale = Opcode == Instruction::Shl
4670 ? 1LL << RHS->getLimitedValue(RHS->getBitWidth() - 1)
4671 : RHS->getSExtValue();
4672
4673 return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
4674 }
4675 case Instruction::GetElementPtr: {
4676 // Scan the GEP. We check it if it contains constant offsets and at most
4677 // one variable offset.
4678 int VariableOperand = -1;
4679 unsigned VariableScale = 0;
4680
4681 int64_t ConstantOffset = 0;
4682 gep_type_iterator GTI = gep_type_begin(AddrInst);
4683 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
4684 if (StructType *STy = GTI.getStructTypeOrNull()) {
4685 const StructLayout *SL = DL.getStructLayout(STy);
4686 unsigned Idx =
4687 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
4688 ConstantOffset += SL->getElementOffset(Idx);
4689 } else {
4690 TypeSize TS = DL.getTypeAllocSize(GTI.getIndexedType());
4691 if (TS.isNonZero()) {
4692 // The optimisations below currently only work for fixed offsets.
4693 if (TS.isScalable())
4694 return false;
4695 int64_t TypeSize = TS.getFixedSize();
4696 if (ConstantInt *CI =
4697 dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
4698 const APInt &CVal = CI->getValue();
4699 if (CVal.getMinSignedBits() <= 64) {
4700 ConstantOffset += CVal.getSExtValue() * TypeSize;
4701 continue;
4702 }
4703 }
4704 // We only allow one variable index at the moment.
4705 if (VariableOperand != -1)
4706 return false;
4707
4708 // Remember the variable index.
4709 VariableOperand = i;
4710 VariableScale = TypeSize;
4711 }
4712 }
4713 }
4714
4715 // A common case is for the GEP to only do a constant offset. In this case,
4716 // just add it to the disp field and check validity.
4717 if (VariableOperand == -1) {
4718 AddrMode.BaseOffs += ConstantOffset;
4719 if (ConstantOffset == 0 ||
4720 TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
4721 // Check to see if we can fold the base pointer in too.
4722 if (matchAddr(AddrInst->getOperand(0), Depth + 1)) {
4723 if (!cast<GEPOperator>(AddrInst)->isInBounds())
4724 AddrMode.InBounds = false;
4725 return true;
4726 }
4727 } else if (EnableGEPOffsetSplit && isa<GetElementPtrInst>(AddrInst) &&
4728 TLI.shouldConsiderGEPOffsetSplit() && Depth == 0 &&
4729 ConstantOffset > 0) {
4730 // Record GEPs with non-zero offsets as candidates for splitting in the
4731 // event that the offset cannot fit into the r+i addressing mode.
4732 // Simple and common case that only one GEP is used in calculating the
4733 // address for the memory access.
4734 Value *Base = AddrInst->getOperand(0);
4735 auto *BaseI = dyn_cast<Instruction>(Base);
4736 auto *GEP = cast<GetElementPtrInst>(AddrInst);
4737 if (isa<Argument>(Base) || isa<GlobalValue>(Base) ||
4738 (BaseI && !isa<CastInst>(BaseI) &&
4739 !isa<GetElementPtrInst>(BaseI))) {
4740 // Make sure the parent block allows inserting non-PHI instructions
4741 // before the terminator.
4742 BasicBlock *Parent =
4743 BaseI ? BaseI->getParent() : &GEP->getFunction()->getEntryBlock();
4744 if (!Parent->getTerminator()->isEHPad())
4745 LargeOffsetGEP = std::make_pair(GEP, ConstantOffset);
4746 }
4747 }
4748 AddrMode.BaseOffs -= ConstantOffset;
4749 return false;
4750 }
4751
4752 // Save the valid addressing mode in case we can't match.
4753 ExtAddrMode BackupAddrMode = AddrMode;
4754 unsigned OldSize = AddrModeInsts.size();
4755
4756 // See if the scale and offset amount is valid for this target.
4757 AddrMode.BaseOffs += ConstantOffset;
4758 if (!cast<GEPOperator>(AddrInst)->isInBounds())
4759 AddrMode.InBounds = false;
4760
4761 // Match the base operand of the GEP.
4762 if (!matchAddr(AddrInst->getOperand(0), Depth + 1)) {
4763 // If it couldn't be matched, just stuff the value in a register.
4764 if (AddrMode.HasBaseReg) {
4765 AddrMode = BackupAddrMode;
4766 AddrModeInsts.resize(OldSize);
4767 return false;
4768 }
4769 AddrMode.HasBaseReg = true;
4770 AddrMode.BaseReg = AddrInst->getOperand(0);
4771 }
4772
4773 // Match the remaining variable portion of the GEP.
4774 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
4775 Depth)) {
4776 // If it couldn't be matched, try stuffing the base into a register
4777 // instead of matching it, and retrying the match of the scale.
4778 AddrMode = BackupAddrMode;
4779 AddrModeInsts.resize(OldSize);
4780 if (AddrMode.HasBaseReg)
4781 return false;
4782 AddrMode.HasBaseReg = true;
4783 AddrMode.BaseReg = AddrInst->getOperand(0);
4784 AddrMode.BaseOffs += ConstantOffset;
4785 if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
4786 VariableScale, Depth)) {
4787 // If even that didn't work, bail.
4788 AddrMode = BackupAddrMode;
4789 AddrModeInsts.resize(OldSize);
4790 return false;
4791 }
4792 }
4793
4794 return true;
4795 }
4796 case Instruction::SExt:
4797 case Instruction::ZExt: {
4798 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
4799 if (!Ext)
4800 return false;
4801
4802 // Try to move this ext out of the way of the addressing mode.
4803 // Ask for a method for doing so.
4804 TypePromotionHelper::Action TPH =
4805 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
4806 if (!TPH)
4807 return false;
4808
4809 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4810 TPT.getRestorationPoint();
4811 unsigned CreatedInstsCost = 0;
4812 unsigned ExtCost = !TLI.isExtFree(Ext);
4813 Value *PromotedOperand =
4814 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
4815 // SExt has been moved away.
4816 // Thus either it will be rematched later in the recursive calls or it is
4817 // gone. Anyway, we must not fold it into the addressing mode at this point.
4818 // E.g.,
4819 // op = add opnd, 1
4820 // idx = ext op
4821 // addr = gep base, idx
4822 // is now:
4823 // promotedOpnd = ext opnd <- no match here
4824 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
4825 // addr = gep base, op <- match
4826 if (MovedAway)
4827 *MovedAway = true;
4828
4829 assert(PromotedOperand &&(static_cast <bool> (PromotedOperand && "TypePromotionHelper should have filtered out those cases"
) ? void (0) : __assert_fail ("PromotedOperand && \"TypePromotionHelper should have filtered out those cases\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 4830, __extension__ __PRETTY_FUNCTION__
))
4830 "TypePromotionHelper should have filtered out those cases")(static_cast <bool> (PromotedOperand && "TypePromotionHelper should have filtered out those cases"
) ? void (0) : __assert_fail ("PromotedOperand && \"TypePromotionHelper should have filtered out those cases\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 4830, __extension__ __PRETTY_FUNCTION__
))
;
4831
4832 ExtAddrMode BackupAddrMode = AddrMode;
4833 unsigned OldSize = AddrModeInsts.size();
4834
4835 if (!matchAddr(PromotedOperand, Depth) ||
4836 // The total of the new cost is equal to the cost of the created
4837 // instructions.
4838 // The total of the old cost is equal to the cost of the extension plus
4839 // what we have saved in the addressing mode.
4840 !isPromotionProfitable(CreatedInstsCost,
4841 ExtCost + (AddrModeInsts.size() - OldSize),
4842 PromotedOperand)) {
4843 AddrMode = BackupAddrMode;
4844 AddrModeInsts.resize(OldSize);
4845 LLVM_DEBUG(dbgs() << "Sign extension does not pay off: rollback\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Sign extension does not pay off: rollback\n"
; } } while (false)
;
4846 TPT.rollback(LastKnownGood);
4847 return false;
4848 }
4849 return true;
4850 }
4851 }
4852 return false;
4853}
4854
4855/// If we can, try to add the value of 'Addr' into the current addressing mode.
4856/// If Addr can't be added to AddrMode this returns false and leaves AddrMode
4857/// unmodified. This assumes that Addr is either a pointer type or intptr_t
4858/// for the target.
4859///
4860bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
4861 // Start a transaction at this point that we will rollback if the matching
4862 // fails.
4863 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4864 TPT.getRestorationPoint();
4865 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
4866 if (CI->getValue().isSignedIntN(64)) {
4867 // Fold in immediates if legal for the target.
4868 AddrMode.BaseOffs += CI->getSExtValue();
4869 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
4870 return true;
4871 AddrMode.BaseOffs -= CI->getSExtValue();
4872 }
4873 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
4874 // If this is a global variable, try to fold it into the addressing mode.
4875 if (!AddrMode.BaseGV) {
4876 AddrMode.BaseGV = GV;
4877 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
4878 return true;
4879 AddrMode.BaseGV = nullptr;
4880 }
4881 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
4882 ExtAddrMode BackupAddrMode = AddrMode;
4883 unsigned OldSize = AddrModeInsts.size();
4884
4885 // Check to see if it is possible to fold this operation.
4886 bool MovedAway = false;
4887 if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
4888 // This instruction may have been moved away. If so, there is nothing
4889 // to check here.
4890 if (MovedAway)
4891 return true;
4892 // Okay, it's possible to fold this. Check to see if it is actually
4893 // *profitable* to do so. We use a simple cost model to avoid increasing
4894 // register pressure too much.
4895 if (I->hasOneUse() ||
4896 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
4897 AddrModeInsts.push_back(I);
4898 return true;
4899 }
4900
4901 // It isn't profitable to do this, roll back.
4902 AddrMode = BackupAddrMode;
4903 AddrModeInsts.resize(OldSize);
4904 TPT.rollback(LastKnownGood);
4905 }
4906 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
4907 if (matchOperationAddr(CE, CE->getOpcode(), Depth))
4908 return true;
4909 TPT.rollback(LastKnownGood);
4910 } else if (isa<ConstantPointerNull>(Addr)) {
4911 // Null pointer gets folded without affecting the addressing mode.
4912 return true;
4913 }
4914
4915 // Worse case, the target should support [reg] addressing modes. :)
4916 if (!AddrMode.HasBaseReg) {
4917 AddrMode.HasBaseReg = true;
4918 AddrMode.BaseReg = Addr;
4919 // Still check for legality in case the target supports [imm] but not [i+r].
4920 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
4921 return true;
4922 AddrMode.HasBaseReg = false;
4923 AddrMode.BaseReg = nullptr;
4924 }
4925
4926 // If the base register is already taken, see if we can do [r+r].
4927 if (AddrMode.Scale == 0) {
4928 AddrMode.Scale = 1;
4929 AddrMode.ScaledReg = Addr;
4930 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
4931 return true;
4932 AddrMode.Scale = 0;
4933 AddrMode.ScaledReg = nullptr;
4934 }
4935 // Couldn't match.
4936 TPT.rollback(LastKnownGood);
4937 return false;
4938}
4939
4940/// Check to see if all uses of OpVal by the specified inline asm call are due
4941/// to memory operands. If so, return true, otherwise return false.
4942static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
4943 const TargetLowering &TLI,
4944 const TargetRegisterInfo &TRI) {
4945 const Function *F = CI->getFunction();
4946 TargetLowering::AsmOperandInfoVector TargetConstraints =
4947 TLI.ParseConstraints(F->getParent()->getDataLayout(), &TRI, *CI);
4948
4949 for (TargetLowering::AsmOperandInfo &OpInfo : TargetConstraints) {
4950 // Compute the constraint code and ConstraintType to use.
4951 TLI.ComputeConstraintToUse(OpInfo, SDValue());
4952
4953 // If this asm operand is our Value*, and if it isn't an indirect memory
4954 // operand, we can't fold it! TODO: Also handle C_Address?
4955 if (OpInfo.CallOperandVal == OpVal &&
4956 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
4957 !OpInfo.isIndirect))
4958 return false;
4959 }
4960
4961 return true;
4962}
4963
4964// Max number of memory uses to look at before aborting the search to conserve
4965// compile time.
4966static constexpr int MaxMemoryUsesToScan = 20;
4967
4968/// Recursively walk all the uses of I until we find a memory use.
4969/// If we find an obviously non-foldable instruction, return true.
4970/// Add accessed addresses and types to MemoryUses.
4971static bool FindAllMemoryUses(
4972 Instruction *I, SmallVectorImpl<std::pair<Value *, Type *>> &MemoryUses,
4973 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetLowering &TLI,
4974 const TargetRegisterInfo &TRI, bool OptSize, ProfileSummaryInfo *PSI,
4975 BlockFrequencyInfo *BFI, int SeenInsts = 0) {
4976 // If we already considered this instruction, we're done.
4977 if (!ConsideredInsts.insert(I).second)
4978 return false;
4979
4980 // If this is an obviously unfoldable instruction, bail out.
4981 if (!MightBeFoldableInst(I))
4982 return true;
4983
4984 // Loop over all the uses, recursively processing them.
4985 for (Use &U : I->uses()) {
4986 // Conservatively return true if we're seeing a large number or a deep chain
4987 // of users. This avoids excessive compilation times in pathological cases.
4988 if (SeenInsts++ >= MaxMemoryUsesToScan)
4989 return true;
4990
4991 Instruction *UserI = cast<Instruction>(U.getUser());
4992 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
4993 MemoryUses.push_back({U.get(), LI->getType()});
4994 continue;
4995 }
4996
4997 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
4998 if (U.getOperandNo() != StoreInst::getPointerOperandIndex())
4999 return true; // Storing addr, not into addr.
5000 MemoryUses.push_back({U.get(), SI->getValueOperand()->getType()});
5001 continue;
5002 }
5003
5004 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UserI)) {
5005 if (U.getOperandNo() != AtomicRMWInst::getPointerOperandIndex())
5006 return true; // Storing addr, not into addr.
5007 MemoryUses.push_back({U.get(), RMW->getValOperand()->getType()});
5008 continue;
5009 }
5010
5011 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(UserI)) {
5012 if (U.getOperandNo() != AtomicCmpXchgInst::getPointerOperandIndex())
5013 return true; // Storing addr, not into addr.
5014 MemoryUses.push_back({U.get(), CmpX->getCompareOperand()->getType()});
5015 continue;
5016 }
5017
5018 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
5019 if (CI->hasFnAttr(Attribute::Cold)) {
5020 // If this is a cold call, we can sink the addressing calculation into
5021 // the cold path. See optimizeCallInst
5022 bool OptForSize =
5023 OptSize || llvm::shouldOptimizeForSize(CI->getParent(), PSI, BFI);
5024 if (!OptForSize)
5025 continue;
5026 }
5027
5028 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledOperand());
5029 if (!IA)
5030 return true;
5031
5032 // If this is a memory operand, we're cool, otherwise bail out.
5033 if (!IsOperandAMemoryOperand(CI, IA, I, TLI, TRI))
5034 return true;
5035 continue;
5036 }
5037
5038 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI, TRI, OptSize,
5039 PSI, BFI, SeenInsts))
5040 return true;
5041 }
5042
5043 return false;
5044}
5045
5046/// Return true if Val is already known to be live at the use site that we're
5047/// folding it into. If so, there is no cost to include it in the addressing
5048/// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
5049/// instruction already.
5050bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,
5051 Value *KnownLive1,
5052 Value *KnownLive2) {
5053 // If Val is either of the known-live values, we know it is live!
5054 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
5055 return true;
5056
5057 // All values other than instructions and arguments (e.g. constants) are live.
5058 if (!isa<Instruction>(Val) && !isa<Argument>(Val))
5059 return true;
5060
5061 // If Val is a constant sized alloca in the entry block, it is live, this is
5062 // true because it is just a reference to the stack/frame pointer, which is
5063 // live for the whole function.
5064 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
5065 if (AI->isStaticAlloca())
5066 return true;
5067
5068 // Check to see if this value is already used in the memory instruction's
5069 // block. If so, it's already live into the block at the very least, so we
5070 // can reasonably fold it.
5071 return Val->isUsedInBasicBlock(MemoryInst->getParent());
5072}
5073
5074/// It is possible for the addressing mode of the machine to fold the specified
5075/// instruction into a load or store that ultimately uses it.
5076/// However, the specified instruction has multiple uses.
5077/// Given this, it may actually increase register pressure to fold it
5078/// into the load. For example, consider this code:
5079///
5080/// X = ...
5081/// Y = X+1
5082/// use(Y) -> nonload/store
5083/// Z = Y+1
5084/// load Z
5085///
5086/// In this case, Y has multiple uses, and can be folded into the load of Z
5087/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
5088/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
5089/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
5090/// number of computations either.
5091///
5092/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
5093/// X was live across 'load Z' for other reasons, we actually *would* want to
5094/// fold the addressing mode in the Z case. This would make Y die earlier.
5095bool AddressingModeMatcher::isProfitableToFoldIntoAddressingMode(
5096 Instruction *I, ExtAddrMode &AMBefore, ExtAddrMode &AMAfter) {
5097 if (IgnoreProfitability)
5098 return true;
5099
5100 // AMBefore is the addressing mode before this instruction was folded into it,
5101 // and AMAfter is the addressing mode after the instruction was folded. Get
5102 // the set of registers referenced by AMAfter and subtract out those
5103 // referenced by AMBefore: this is the set of values which folding in this
5104 // address extends the lifetime of.
5105 //
5106 // Note that there are only two potential values being referenced here,
5107 // BaseReg and ScaleReg (global addresses are always available, as are any
5108 // folded immediates).
5109 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
5110
5111 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
5112 // lifetime wasn't extended by adding this instruction.
5113 if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
5114 BaseReg = nullptr;
5115 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
5116 ScaledReg = nullptr;
5117
5118 // If folding this instruction (and it's subexprs) didn't extend any live
5119 // ranges, we're ok with it.
5120 if (!BaseReg && !ScaledReg)
5121 return true;
5122
5123 // If all uses of this instruction can have the address mode sunk into them,
5124 // we can remove the addressing mode and effectively trade one live register
5125 // for another (at worst.) In this context, folding an addressing mode into
5126 // the use is just a particularly nice way of sinking it.
5127 SmallVector<std::pair<Value *, Type *>, 16> MemoryUses;
5128 SmallPtrSet<Instruction *, 16> ConsideredInsts;
5129 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI, TRI, OptSize, PSI,
5130 BFI))
5131 return false; // Has a non-memory, non-foldable use!
5132
5133 // Now that we know that all uses of this instruction are part of a chain of
5134 // computation involving only operations that could theoretically be folded
5135 // into a memory use, loop over each of these memory operation uses and see
5136 // if they could *actually* fold the instruction. The assumption is that
5137 // addressing modes are cheap and that duplicating the computation involved
5138 // many times is worthwhile, even on a fastpath. For sinking candidates
5139 // (i.e. cold call sites), this serves as a way to prevent excessive code
5140 // growth since most architectures have some reasonable small and fast way to
5141 // compute an effective address. (i.e LEA on x86)
5142 SmallVector<Instruction *, 32> MatchedAddrModeInsts;
5143 for (const std::pair<Value *, Type *> &Pair : MemoryUses) {
5144 Value *Address = Pair.first;
5145 Type *AddressAccessTy = Pair.second;
5146 unsigned AS = Address->getType()->getPointerAddressSpace();
5147
5148 // Do a match against the root of this address, ignoring profitability. This
5149 // will tell us if the addressing mode for the memory operation will
5150 // *actually* cover the shared instruction.
5151 ExtAddrMode Result;
5152 std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr,
5153 0);
5154 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5155 TPT.getRestorationPoint();
5156 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, TRI, LI, getDTFn,
5157 AddressAccessTy, AS, MemoryInst, Result,
5158 InsertedInsts, PromotedInsts, TPT,
5159 LargeOffsetGEP, OptSize, PSI, BFI);
5160 Matcher.IgnoreProfitability = true;
5161 bool Success = Matcher.matchAddr(Address, 0);
5162 (void)Success;
5163 assert(Success && "Couldn't select *anything*?")(static_cast <bool> (Success && "Couldn't select *anything*?"
) ? void (0) : __assert_fail ("Success && \"Couldn't select *anything*?\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 5163, __extension__ __PRETTY_FUNCTION__
))
;
5164
5165 // The match was to check the profitability, the changes made are not
5166 // part of the original matcher. Therefore, they should be dropped
5167 // otherwise the original matcher will not present the right state.
5168 TPT.rollback(LastKnownGood);
5169
5170 // If the match didn't cover I, then it won't be shared by it.
5171 if (!is_contained(MatchedAddrModeInsts, I))
5172 return false;
5173
5174 MatchedAddrModeInsts.clear();
5175 }
5176
5177 return true;
5178}
5179
5180/// Return true if the specified values are defined in a
5181/// different basic block than BB.
5182static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
5183 if (Instruction *I = dyn_cast<Instruction>(V))
5184 return I->getParent() != BB;
5185 return false;
5186}
5187
5188/// Sink addressing mode computation immediate before MemoryInst if doing so
5189/// can be done without increasing register pressure. The need for the
5190/// register pressure constraint means this can end up being an all or nothing
5191/// decision for all uses of the same addressing computation.
5192///
5193/// Load and Store Instructions often have addressing modes that can do
5194/// significant amounts of computation. As such, instruction selection will try
5195/// to get the load or store to do as much computation as possible for the
5196/// program. The problem is that isel can only see within a single block. As
5197/// such, we sink as much legal addressing mode work into the block as possible.
5198///
5199/// This method is used to optimize both load/store and inline asms with memory
5200/// operands. It's also used to sink addressing computations feeding into cold
5201/// call sites into their (cold) basic block.
5202///
5203/// The motivation for handling sinking into cold blocks is that doing so can
5204/// both enable other address mode sinking (by satisfying the register pressure
5205/// constraint above), and reduce register pressure globally (by removing the
5206/// addressing mode computation from the fast path entirely.).
5207bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
5208 Type *AccessTy, unsigned AddrSpace) {
5209 Value *Repl = Addr;
5210
5211 // Try to collapse single-value PHI nodes. This is necessary to undo
5212 // unprofitable PRE transformations.
5213 SmallVector<Value *, 8> worklist;
5214 SmallPtrSet<Value *, 16> Visited;
5215 worklist.push_back(Addr);
5216
5217 // Use a worklist to iteratively look through PHI and select nodes, and
5218 // ensure that the addressing mode obtained from the non-PHI/select roots of
5219 // the graph are compatible.
5220 bool PhiOrSelectSeen = false;
5221 SmallVector<Instruction *, 16> AddrModeInsts;
5222 const SimplifyQuery SQ(*DL, TLInfo);
5223 AddressingModeCombiner AddrModes(SQ, Addr);
5224 TypePromotionTransaction TPT(RemovedInsts);
5225 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5226 TPT.getRestorationPoint();
5227 while (!worklist.empty()) {
5228 Value *V = worklist.pop_back_val();
5229
5230 // We allow traversing cyclic Phi nodes.
5231 // In case of success after this loop we ensure that traversing through
5232 // Phi nodes ends up with all cases to compute address of the form
5233 // BaseGV + Base + Scale * Index + Offset
5234 // where Scale and Offset are constans and BaseGV, Base and Index
5235 // are exactly the same Values in all cases.
5236 // It means that BaseGV, Scale and Offset dominate our memory instruction
5237 // and have the same value as they had in address computation represented
5238 // as Phi. So we can safely sink address computation to memory instruction.
5239 if (!Visited.insert(V).second)
5240 continue;
5241
5242 // For a PHI node, push all of its incoming values.
5243 if (PHINode *P = dyn_cast<PHINode>(V)) {
5244 append_range(worklist, P->incoming_values());
5245 PhiOrSelectSeen = true;
5246 continue;
5247 }
5248 // Similar for select.
5249 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
5250 worklist.push_back(SI->getFalseValue());
5251 worklist.push_back(SI->getTrueValue());
5252 PhiOrSelectSeen = true;
5253 continue;
5254 }
5255
5256 // For non-PHIs, determine the addressing mode being computed. Note that
5257 // the result may differ depending on what other uses our candidate
5258 // addressing instructions might have.
5259 AddrModeInsts.clear();
5260 std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr,
5261 0);
5262 // Defer the query (and possible computation of) the dom tree to point of
5263 // actual use. It's expected that most address matches don't actually need
5264 // the domtree.
5265 auto getDTFn = [MemoryInst, this]() -> const DominatorTree & {
5266 Function *F = MemoryInst->getParent()->getParent();
5267 return this->getDT(*F);
5268 };
5269 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
5270 V, AccessTy, AddrSpace, MemoryInst, AddrModeInsts, *TLI, *LI, getDTFn,
5271 *TRI, InsertedInsts, PromotedInsts, TPT, LargeOffsetGEP, OptSize, PSI,
5272 BFI.get());
5273
5274 GetElementPtrInst *GEP = LargeOffsetGEP.first;
5275 if (GEP && !NewGEPBases.count(GEP)) {
5276 // If splitting the underlying data structure can reduce the offset of a
5277 // GEP, collect the GEP. Skip the GEPs that are the new bases of
5278 // previously split data structures.
5279 LargeOffsetGEPMap[GEP->getPointerOperand()].push_back(LargeOffsetGEP);
5280 LargeOffsetGEPID.insert(std::make_pair(GEP, LargeOffsetGEPID.size()));
5281 }
5282
5283 NewAddrMode.OriginalValue = V;
5284 if (!AddrModes.addNewAddrMode(NewAddrMode))
5285 break;
5286 }
5287
5288 // Try to combine the AddrModes we've collected. If we couldn't collect any,
5289 // or we have multiple but either couldn't combine them or combining them
5290 // wouldn't do anything useful, bail out now.
5291 if (!AddrModes.combineAddrModes()) {
5292 TPT.rollback(LastKnownGood);
5293 return false;
5294 }
5295 bool Modified = TPT.commit();
5296
5297 // Get the combined AddrMode (or the only AddrMode, if we only had one).
5298 ExtAddrMode AddrMode = AddrModes.getAddrMode();
5299
5300 // If all the instructions matched are already in this BB, don't do anything.
5301 // If we saw a Phi node then it is not local definitely, and if we saw a
5302 // select then we want to push the address calculation past it even if it's
5303 // already in this BB.
5304 if (!PhiOrSelectSeen && none_of(AddrModeInsts, [&](Value *V) {
5305 return IsNonLocalValue(V, MemoryInst->getParent());
5306 })) {
5307 LLVM_DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrModedo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "CGP: Found local addrmode: "
<< AddrMode << "\n"; } } while (false)
5308 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "CGP: Found local addrmode: "
<< AddrMode << "\n"; } } while (false)
;
5309 return Modified;
5310 }
5311
5312 // Insert this computation right after this user. Since our caller is
5313 // scanning from the top of the BB to the bottom, reuse of the expr are
5314 // guaranteed to happen later.
5315 IRBuilder<> Builder(MemoryInst);
5316
5317 // Now that we determined the addressing expression we want to use and know
5318 // that we have to sink it into this block. Check to see if we have already
5319 // done this for some other load/store instr in this block. If so, reuse
5320 // the computation. Before attempting reuse, check if the address is valid
5321 // as it may have been erased.
5322
5323 WeakTrackingVH SunkAddrVH = SunkAddrs[Addr];
5324
5325 Value *SunkAddr = SunkAddrVH.pointsToAliveValue() ? SunkAddrVH : nullptr;
5326 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
5327 if (SunkAddr) {
5328 LLVM_DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrModedo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "CGP: Reusing nonlocal addrmode: "
<< AddrMode << " for " << *MemoryInst <<
"\n"; } } while (false)
5329 << " for " << *MemoryInst << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "CGP: Reusing nonlocal addrmode: "
<< AddrMode << " for " << *MemoryInst <<
"\n"; } } while (false)
;
5330 if (SunkAddr->getType() != Addr->getType()) {
5331 if (SunkAddr->getType()->getPointerAddressSpace() !=
5332 Addr->getType()->getPointerAddressSpace() &&
5333 !DL->isNonIntegralPointerType(Addr->getType())) {
5334 // There are two reasons the address spaces might not match: a no-op
5335 // addrspacecast, or a ptrtoint/inttoptr pair. Either way, we emit a
5336 // ptrtoint/inttoptr pair to ensure we match the original semantics.
5337 // TODO: allow bitcast between different address space pointers with the
5338 // same size.
5339 SunkAddr = Builder.CreatePtrToInt(SunkAddr, IntPtrTy, "sunkaddr");
5340 SunkAddr =
5341 Builder.CreateIntToPtr(SunkAddr, Addr->getType(), "sunkaddr");
5342 } else
5343 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
5344 }
5345 } else if (AddrSinkUsingGEPs || (!AddrSinkUsingGEPs.getNumOccurrences() &&
5346 SubtargetInfo->addrSinkUsingGEPs())) {
5347 // By default, we use the GEP-based method when AA is used later. This
5348 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
5349 LLVM_DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrModedo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "CGP: SINKING nonlocal addrmode: "
<< AddrMode << " for " << *MemoryInst <<
"\n"; } } while (false)
5350 << " for " << *MemoryInst << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "CGP: SINKING nonlocal addrmode: "
<< AddrMode << " for " << *MemoryInst <<
"\n"; } } while (false)
;
5351 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
5352
5353 // First, find the pointer.
5354 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
5355 ResultPtr = AddrMode.BaseReg;
5356 AddrMode.BaseReg = nullptr;
5357 }
5358
5359 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
5360 // We can't add more than one pointer together, nor can we scale a
5361 // pointer (both of which seem meaningless).
5362 if (ResultPtr || AddrMode.Scale != 1)
5363 return Modified;
5364
5365 ResultPtr = AddrMode.ScaledReg;
5366 AddrMode.Scale = 0;
5367 }
5368
5369 // It is only safe to sign extend the BaseReg if we know that the math
5370 // required to create it did not overflow before we extend it. Since
5371 // the original IR value was tossed in favor of a constant back when
5372 // the AddrMode was created we need to bail out gracefully if widths
5373 // do not match instead of extending it.
5374 //
5375 // (See below for code to add the scale.)
5376 if (AddrMode.Scale) {
5377 Type *ScaledRegTy = AddrMode.ScaledReg->getType();
5378 if (cast<IntegerType>(IntPtrTy)->getBitWidth() >
5379 cast<IntegerType>(ScaledRegTy)->getBitWidth())
5380 return Modified;
5381 }
5382
5383 if (AddrMode.BaseGV) {
5384 if (ResultPtr)
5385 return Modified;
5386
5387 ResultPtr = AddrMode.BaseGV;
5388 }
5389
5390 // If the real base value actually came from an inttoptr, then the matcher
5391 // will look through it and provide only the integer value. In that case,
5392 // use it here.
5393 if (!DL->isNonIntegralPointerType(Addr->getType())) {
5394 if (!ResultPtr && AddrMode.BaseReg) {
5395 ResultPtr = Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(),
5396 "sunkaddr");
5397 AddrMode.BaseReg = nullptr;
5398 } else if (!ResultPtr && AddrMode.Scale == 1) {
5399 ResultPtr = Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(),
5400 "sunkaddr");
5401 AddrMode.Scale = 0;
5402 }
5403 }
5404
5405 if (!ResultPtr && !AddrMode.BaseReg && !AddrMode.Scale &&
5406 !AddrMode.BaseOffs) {
5407 SunkAddr = Constant::getNullValue(Addr->getType());
5408 } else if (!ResultPtr) {
5409 return Modified;
5410 } else {
5411 Type *I8PtrTy =
5412 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
5413 Type *I8Ty = Builder.getInt8Ty();
5414
5415 // Start with the base register. Do this first so that subsequent address
5416 // matching finds it last, which will prevent it from trying to match it
5417 // as the scaled value in case it happens to be a mul. That would be
5418 // problematic if we've sunk a different mul for the scale, because then
5419 // we'd end up sinking both muls.
5420 if (AddrMode.BaseReg) {
5421 Value *V = AddrMode.BaseReg;
5422 if (V->getType() != IntPtrTy)
5423 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
5424
5425 ResultIndex = V;
5426 }
5427
5428 // Add the scale value.
5429 if (AddrMode.Scale) {
5430 Value *V = AddrMode.ScaledReg;
5431 if (V->getType() == IntPtrTy) {
5432 // done.
5433 } else {
5434 assert(cast<IntegerType>(IntPtrTy)->getBitWidth() <(static_cast <bool> (cast<IntegerType>(IntPtrTy)->
getBitWidth() < cast<IntegerType>(V->getType())->
getBitWidth() && "We can't transform if ScaledReg is too narrow"
) ? void (0) : __assert_fail ("cast<IntegerType>(IntPtrTy)->getBitWidth() < cast<IntegerType>(V->getType())->getBitWidth() && \"We can't transform if ScaledReg is too narrow\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 5436, __extension__ __PRETTY_FUNCTION__
))
5435 cast<IntegerType>(V->getType())->getBitWidth() &&(static_cast <bool> (cast<IntegerType>(IntPtrTy)->
getBitWidth() < cast<IntegerType>(V->getType())->
getBitWidth() && "We can't transform if ScaledReg is too narrow"
) ? void (0) : __assert_fail ("cast<IntegerType>(IntPtrTy)->getBitWidth() < cast<IntegerType>(V->getType())->getBitWidth() && \"We can't transform if ScaledReg is too narrow\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 5436, __extension__ __PRETTY_FUNCTION__
))
5436 "We can't transform if ScaledReg is too narrow")(static_cast <bool> (cast<IntegerType>(IntPtrTy)->
getBitWidth() < cast<IntegerType>(V->getType())->
getBitWidth() && "We can't transform if ScaledReg is too narrow"
) ? void (0) : __assert_fail ("cast<IntegerType>(IntPtrTy)->getBitWidth() < cast<IntegerType>(V->getType())->getBitWidth() && \"We can't transform if ScaledReg is too narrow\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 5436, __extension__ __PRETTY_FUNCTION__
))
;
5437 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
5438 }
5439
5440 if (AddrMode.Scale != 1)
5441 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
5442 "sunkaddr");
5443 if (ResultIndex)
5444 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
5445 else
5446 ResultIndex = V;
5447 }
5448
5449 // Add in the Base Offset if present.
5450 if (AddrMode.BaseOffs) {
5451 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
5452 if (ResultIndex) {
5453 // We need to add this separately from the scale above to help with
5454 // SDAG consecutive load/store merging.
5455 if (ResultPtr->getType() != I8PtrTy)
5456 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
5457 ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex,
5458 "sunkaddr", AddrMode.InBounds);
5459 }
5460
5461 ResultIndex = V;
5462 }
5463
5464 if (!ResultIndex) {
5465 SunkAddr = ResultPtr;
5466 } else {
5467 if (ResultPtr->getType() != I8PtrTy)
5468 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
5469 SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr",
5470 AddrMode.InBounds);
5471 }
5472
5473 if (SunkAddr->getType() != Addr->getType()) {
5474 if (SunkAddr->getType()->getPointerAddressSpace() !=
5475 Addr->getType()->getPointerAddressSpace() &&
5476 !DL->isNonIntegralPointerType(Addr->getType())) {
5477 // There are two reasons the address spaces might not match: a no-op
5478 // addrspacecast, or a ptrtoint/inttoptr pair. Either way, we emit a
5479 // ptrtoint/inttoptr pair to ensure we match the original semantics.
5480 // TODO: allow bitcast between different address space pointers with
5481 // the same size.
5482 SunkAddr = Builder.CreatePtrToInt(SunkAddr, IntPtrTy, "sunkaddr");
5483 SunkAddr =
5484 Builder.CreateIntToPtr(SunkAddr, Addr->getType(), "sunkaddr");
5485 } else
5486 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
5487 }
5488 }
5489 } else {
5490 // We'd require a ptrtoint/inttoptr down the line, which we can't do for
5491 // non-integral pointers, so in that case bail out now.
5492 Type *BaseTy = AddrMode.BaseReg ? AddrMode.BaseReg->getType() : nullptr;
5493 Type *ScaleTy = AddrMode.Scale ? AddrMode.ScaledReg->getType() : nullptr;
5494 PointerType *BasePtrTy = dyn_cast_or_null<PointerType>(BaseTy);
5495 PointerType *ScalePtrTy = dyn_cast_or_null<PointerType>(ScaleTy);
5496 if (DL->isNonIntegralPointerType(Addr->getType()) ||
5497 (BasePtrTy && DL->isNonIntegralPointerType(BasePtrTy)) ||
5498 (ScalePtrTy && DL->isNonIntegralPointerType(ScalePtrTy)) ||
5499 (AddrMode.BaseGV &&
5500 DL->isNonIntegralPointerType(AddrMode.BaseGV->getType())))
5501 return Modified;
5502
5503 LLVM_DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrModedo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "CGP: SINKING nonlocal addrmode: "
<< AddrMode << " for " << *MemoryInst <<
"\n"; } } while (false)
5504 << " for " << *MemoryInst << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "CGP: SINKING nonlocal addrmode: "
<< AddrMode << " for " << *MemoryInst <<
"\n"; } } while (false)
;
5505 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
5506 Value *Result = nullptr;
5507
5508 // Start with the base register. Do this first so that subsequent address
5509 // matching finds it last, which will prevent it from trying to match it
5510 // as the scaled value in case it happens to be a mul. That would be
5511 // problematic if we've sunk a different mul for the scale, because then
5512 // we'd end up sinking both muls.
5513 if (AddrMode.BaseReg) {
5514 Value *V = AddrMode.BaseReg;
5515 if (V->getType()->isPointerTy())
5516 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
5517 if (V->getType() != IntPtrTy)
5518 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
5519 Result = V;
5520 }
5521
5522 // Add the scale value.
5523 if (AddrMode.Scale) {
5524 Value *V = AddrMode.ScaledReg;
5525 if (V->getType() == IntPtrTy) {
5526 // done.
5527 } else if (V->getType()->isPointerTy()) {
5528 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
5529 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
5530 cast<IntegerType>(V->getType())->getBitWidth()) {
5531 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
5532 } else {
5533 // It is only safe to sign extend the BaseReg if we know that the math
5534 // required to create it did not overflow before we extend it. Since
5535 // the original IR value was tossed in favor of a constant back when
5536 // the AddrMode was created we need to bail out gracefully if widths
5537 // do not match instead of extending it.
5538 Instruction *I = dyn_cast_or_null<Instruction>(Result);
5539 if (I && (Result != AddrMode.BaseReg))
5540 I->eraseFromParent();
5541 return Modified;
5542 }
5543 if (AddrMode.Scale != 1)
5544 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
5545 "sunkaddr");
5546 if (Result)
5547 Result = Builder.CreateAdd(Result, V, "sunkaddr");
5548 else
5549 Result = V;
5550 }
5551
5552 // Add in the BaseGV if present.
5553 if (AddrMode.BaseGV) {
5554 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
5555 if (Result)
5556 Result = Builder.CreateAdd(Result, V, "sunkaddr");
5557 else
5558 Result = V;
5559 }
5560
5561 // Add in the Base Offset if present.
5562 if (AddrMode.BaseOffs) {
5563 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
5564 if (Result)
5565 Result = Builder.CreateAdd(Result, V, "sunkaddr");
5566 else
5567 Result = V;
5568 }
5569
5570 if (!Result)
5571 SunkAddr = Constant::getNullValue(Addr->getType());
5572 else
5573 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
5574 }
5575
5576 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
5577 // Store the newly computed address into the cache. In the case we reused a
5578 // value, this should be idempotent.
5579 SunkAddrs[Addr] = WeakTrackingVH(SunkAddr);
5580
5581 // If we have no uses, recursively delete the value and all dead instructions
5582 // using it.
5583 if (Repl->use_empty()) {
5584 resetIteratorIfInvalidatedWhileCalling(CurInstIterator->getParent(), [&]() {
5585 RecursivelyDeleteTriviallyDeadInstructions(
5586 Repl, TLInfo, nullptr,
5587 [&](Value *V) { removeAllAssertingVHReferences(V); });
5588 });
5589 }
5590 ++NumMemoryInsts;
5591 return true;
5592}
5593
5594/// Rewrite GEP input to gather/scatter to enable SelectionDAGBuilder to find
5595/// a uniform base to use for ISD::MGATHER/MSCATTER. SelectionDAGBuilder can
5596/// only handle a 2 operand GEP in the same basic block or a splat constant
5597/// vector. The 2 operands to the GEP must have a scalar pointer and a vector
5598/// index.
5599///
5600/// If the existing GEP has a vector base pointer that is splat, we can look
5601/// through the splat to find the scalar pointer. If we can't find a scalar
5602/// pointer there's nothing we can do.
5603///
5604/// If we have a GEP with more than 2 indices where the middle indices are all
5605/// zeroes, we can replace it with 2 GEPs where the second has 2 operands.
5606///
5607/// If the final index isn't a vector or is a splat, we can emit a scalar GEP
5608/// followed by a GEP with an all zeroes vector index. This will enable
5609/// SelectionDAGBuilder to use the scalar GEP as the uniform base and have a
5610/// zero index.
5611bool CodeGenPrepare::optimizeGatherScatterInst(Instruction *MemoryInst,
5612 Value *Ptr) {
5613 Value *NewAddr;
5614
5615 if (const auto *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
5616 // Don't optimize GEPs that don't have indices.
5617 if (!GEP->hasIndices())
5618 return false;
5619
5620 // If the GEP and the gather/scatter aren't in the same BB, don't optimize.
5621 // FIXME: We should support this by sinking the GEP.
5622 if (MemoryInst->getParent() != GEP->getParent())
5623 return false;
5624
5625 SmallVector<Value *, 2> Ops(GEP->operands());
5626
5627 bool RewriteGEP = false;
5628
5629 if (Ops[0]->getType()->isVectorTy()) {
5630 Ops[0] = getSplatValue(Ops[0]);
5631 if (!Ops[0])
5632 return false;
5633 RewriteGEP = true;
5634 }
5635
5636 unsigned FinalIndex = Ops.size() - 1;
5637
5638 // Ensure all but the last index is 0.
5639 // FIXME: This isn't strictly required. All that's required is that they are
5640 // all scalars or splats.
5641 for (unsigned i = 1; i < FinalIndex; ++i) {
5642 auto *C = dyn_cast<Constant>(Ops[i]);
5643 if (!C)
5644 return false;
5645 if (isa<VectorType>(C->getType()))
5646 C = C->getSplatValue();
5647 auto *CI = dyn_cast_or_null<ConstantInt>(C);
5648 if (!CI || !CI->isZero())
5649 return false;
5650 // Scalarize the index if needed.
5651 Ops[i] = CI;
5652 }
5653
5654 // Try to scalarize the final index.
5655 if (Ops[FinalIndex]->getType()->isVectorTy()) {
5656 if (Value *V = getSplatValue(Ops[FinalIndex])) {
5657 auto *C = dyn_cast<ConstantInt>(V);
5658 // Don't scalarize all zeros vector.
5659 if (!C || !C->isZero()) {
5660 Ops[FinalIndex] = V;
5661 RewriteGEP = true;
5662 }
5663 }
5664 }
5665
5666 // If we made any changes or the we have extra operands, we need to generate
5667 // new instructions.
5668 if (!RewriteGEP && Ops.size() == 2)
5669 return false;
5670
5671 auto NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
5672
5673 IRBuilder<> Builder(MemoryInst);
5674
5675 Type *SourceTy = GEP->getSourceElementType();
5676 Type *ScalarIndexTy = DL->getIndexType(Ops[0]->getType()->getScalarType());
5677
5678 // If the final index isn't a vector, emit a scalar GEP containing all ops
5679 // and a vector GEP with all zeroes final index.
5680 if (!Ops[FinalIndex]->getType()->isVectorTy()) {
5681 NewAddr =
5682 Builder.CreateGEP(SourceTy, Ops[0], makeArrayRef(Ops).drop_front());
5683 auto *IndexTy = VectorType::get(ScalarIndexTy, NumElts);
5684 auto *SecondTy = GetElementPtrInst::getIndexedType(
5685 SourceTy, makeArrayRef(Ops).drop_front());
5686 NewAddr =
5687 Builder.CreateGEP(SecondTy, NewAddr, Constant::getNullValue(IndexTy));
5688 } else {
5689 Value *Base = Ops[0];
5690 Value *Index = Ops[FinalIndex];
5691
5692 // Create a scalar GEP if there are more than 2 operands.
5693 if (Ops.size() != 2) {
5694 // Replace the last index with 0.
5695 Ops[FinalIndex] = Constant::getNullValue(ScalarIndexTy);
5696 Base =
5697 Builder.CreateGEP(SourceTy, Base, makeArrayRef(Ops).drop_front());
5698 SourceTy = GetElementPtrInst::getIndexedType(
5699 SourceTy, makeArrayRef(Ops).drop_front());
5700 }
5701
5702 // Now create the GEP with scalar pointer and vector index.
5703 NewAddr = Builder.CreateGEP(SourceTy, Base, Index);
5704 }
5705 } else if (!isa<Constant>(Ptr)) {
5706 // Not a GEP, maybe its a splat and we can create a GEP to enable
5707 // SelectionDAGBuilder to use it as a uniform base.
5708 Value *V = getSplatValue(Ptr);
5709 if (!V)
5710 return false;
5711
5712 auto NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
5713
5714 IRBuilder<> Builder(MemoryInst);
5715
5716 // Emit a vector GEP with a scalar pointer and all 0s vector index.
5717 Type *ScalarIndexTy = DL->getIndexType(V->getType()->getScalarType());
5718 auto *IndexTy = VectorType::get(ScalarIndexTy, NumElts);
5719 Type *ScalarTy;
5720 if (cast<IntrinsicInst>(MemoryInst)->getIntrinsicID() ==
5721 Intrinsic::masked_gather) {
5722 ScalarTy = MemoryInst->getType()->getScalarType();
5723 } else {
5724 assert(cast<IntrinsicInst>(MemoryInst)->getIntrinsicID() ==(static_cast <bool> (cast<IntrinsicInst>(MemoryInst
)->getIntrinsicID() == Intrinsic::masked_scatter) ? void (
0) : __assert_fail ("cast<IntrinsicInst>(MemoryInst)->getIntrinsicID() == Intrinsic::masked_scatter"
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 5725, __extension__ __PRETTY_FUNCTION__
))
5725 Intrinsic::masked_scatter)(static_cast <bool> (cast<IntrinsicInst>(MemoryInst
)->getIntrinsicID() == Intrinsic::masked_scatter) ? void (
0) : __assert_fail ("cast<IntrinsicInst>(MemoryInst)->getIntrinsicID() == Intrinsic::masked_scatter"
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 5725, __extension__ __PRETTY_FUNCTION__
))
;
5726 ScalarTy = MemoryInst->getOperand(0)->getType()->getScalarType();
5727 }
5728 NewAddr = Builder.CreateGEP(ScalarTy, V, Constant::getNullValue(IndexTy));
5729 } else {
5730 // Constant, SelectionDAGBuilder knows to check if its a splat.
5731 return false;
5732 }
5733
5734 MemoryInst->replaceUsesOfWith(Ptr, NewAddr);
5735
5736 // If we have no uses, recursively delete the value and all dead instructions
5737 // using it.
5738 if (Ptr->use_empty())
5739 RecursivelyDeleteTriviallyDeadInstructions(