Bug Summary

File:build/source/llvm/lib/CodeGen/CodeGenPrepare.cpp
Warning:line 2474, column 10
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/source/build-llvm/tools/clang/stage2-bins -resource-dir /usr/lib/llvm-17/lib/clang/17 -D _DEBUG -D _GLIBCXX_ASSERTIONS -D _GNU_SOURCE -D _LIBCPP_ENABLE_ASSERTIONS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I lib/CodeGen -I /build/source/llvm/lib/CodeGen -I include -I /build/source/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-17/lib/clang/17/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/source/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fmacro-prefix-map=/build/source/= -fcoverage-prefix-map=/build/source/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fcoverage-prefix-map=/build/source/= -source-date-epoch 1683717183 -O2 -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/source/build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/source/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/source/= -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-2023-05-10-133810-16478-1 -x c++ /build/source/llvm/lib/CodeGen/CodeGenPrepare.cpp

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