Bug Summary

File:build/llvm-toolchain-snapshot-16~++20220828101037+f00f2b3e8d40/llvm/lib/CodeGen/CodeGenPrepare.cpp
Warning:line 1149, column 37
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name CodeGenPrepare.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-16~++20220828101037+f00f2b3e8d40/build-llvm -resource-dir /usr/lib/llvm-16/lib/clang/16.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I lib/CodeGen -I /build/llvm-toolchain-snapshot-16~++20220828101037+f00f2b3e8d40/llvm/lib/CodeGen -I include -I /build/llvm-toolchain-snapshot-16~++20220828101037+f00f2b3e8d40/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-16/lib/clang/16.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20220828101037+f00f2b3e8d40/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20220828101037+f00f2b3e8d40/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20220828101037+f00f2b3e8d40/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20220828101037+f00f2b3e8d40/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-16~++20220828101037+f00f2b3e8d40/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20220828101037+f00f2b3e8d40/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20220828101037+f00f2b3e8d40/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-08-29-020613-35344-1 -x c++ /build/llvm-toolchain-snapshot-16~++20220828101037+f00f2b3e8d40/llvm/lib/CodeGen/CodeGenPrepare.cpp
1//===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This pass munges the code in the input function to better prepare it for
10// SelectionDAG-based code generation. This works around limitations in it's
11// basic-block-at-a-time approach. It should eventually be removed.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/MapVector.h"
19#include "llvm/ADT/PointerIntPair.h"
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/SmallPtrSet.h"
22#include "llvm/ADT/SmallVector.h"
23#include "llvm/ADT/Statistic.h"
24#include "llvm/Analysis/BlockFrequencyInfo.h"
25#include "llvm/Analysis/BranchProbabilityInfo.h"
26#include "llvm/Analysis/InstructionSimplify.h"
27#include "llvm/Analysis/LoopInfo.h"
28#include "llvm/Analysis/ProfileSummaryInfo.h"
29#include "llvm/Analysis/TargetLibraryInfo.h"
30#include "llvm/Analysis/TargetTransformInfo.h"
31#include "llvm/Analysis/ValueTracking.h"
32#include "llvm/Analysis/VectorUtils.h"
33#include "llvm/CodeGen/Analysis.h"
34#include "llvm/CodeGen/BasicBlockSectionsProfileReader.h"
35#include "llvm/CodeGen/ISDOpcodes.h"
36#include "llvm/CodeGen/SelectionDAGNodes.h"
37#include "llvm/CodeGen/TargetLowering.h"
38#include "llvm/CodeGen/TargetPassConfig.h"
39#include "llvm/CodeGen/TargetSubtargetInfo.h"
40#include "llvm/CodeGen/ValueTypes.h"
41#include "llvm/Config/llvm-config.h"
42#include "llvm/IR/Argument.h"
43#include "llvm/IR/Attributes.h"
44#include "llvm/IR/BasicBlock.h"
45#include "llvm/IR/Constant.h"
46#include "llvm/IR/Constants.h"
47#include "llvm/IR/DataLayout.h"
48#include "llvm/IR/DebugInfo.h"
49#include "llvm/IR/DerivedTypes.h"
50#include "llvm/IR/Dominators.h"
51#include "llvm/IR/Function.h"
52#include "llvm/IR/GetElementPtrTypeIterator.h"
53#include "llvm/IR/GlobalValue.h"
54#include "llvm/IR/GlobalVariable.h"
55#include "llvm/IR/IRBuilder.h"
56#include "llvm/IR/InlineAsm.h"
57#include "llvm/IR/InstrTypes.h"
58#include "llvm/IR/Instruction.h"
59#include "llvm/IR/Instructions.h"
60#include "llvm/IR/IntrinsicInst.h"
61#include "llvm/IR/Intrinsics.h"
62#include "llvm/IR/IntrinsicsAArch64.h"
63#include "llvm/IR/LLVMContext.h"
64#include "llvm/IR/MDBuilder.h"
65#include "llvm/IR/Module.h"
66#include "llvm/IR/Operator.h"
67#include "llvm/IR/PatternMatch.h"
68#include "llvm/IR/ProfDataUtils.h"
69#include "llvm/IR/Statepoint.h"
70#include "llvm/IR/Type.h"
71#include "llvm/IR/Use.h"
72#include "llvm/IR/User.h"
73#include "llvm/IR/Value.h"
74#include "llvm/IR/ValueHandle.h"
75#include "llvm/IR/ValueMap.h"
76#include "llvm/InitializePasses.h"
77#include "llvm/Pass.h"
78#include "llvm/Support/BlockFrequency.h"
79#include "llvm/Support/BranchProbability.h"
80#include "llvm/Support/Casting.h"
81#include "llvm/Support/CommandLine.h"
82#include "llvm/Support/Compiler.h"
83#include "llvm/Support/Debug.h"
84#include "llvm/Support/ErrorHandling.h"
85#include "llvm/Support/MachineValueType.h"
86#include "llvm/Support/MathExtras.h"
87#include "llvm/Support/raw_ostream.h"
88#include "llvm/Target/TargetMachine.h"
89#include "llvm/Target/TargetOptions.h"
90#include "llvm/Transforms/Utils/BasicBlockUtils.h"
91#include "llvm/Transforms/Utils/BypassSlowDivision.h"
92#include "llvm/Transforms/Utils/Local.h"
93#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
94#include "llvm/Transforms/Utils/SizeOpts.h"
95#include <algorithm>
96#include <cassert>
97#include <cstdint>
98#include <iterator>
99#include <limits>
100#include <memory>
101#include <utility>
102#include <vector>
103
104using namespace llvm;
105using namespace llvm::PatternMatch;
106
107#define DEBUG_TYPE"codegenprepare" "codegenprepare"
108
109STATISTIC(NumBlocksElim, "Number of blocks eliminated")static llvm::Statistic NumBlocksElim = {"codegenprepare", "NumBlocksElim"
, "Number of blocks eliminated"}
;
110STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated")static llvm::Statistic NumPHIsElim = {"codegenprepare", "NumPHIsElim"
, "Number of trivial PHIs eliminated"}
;
111STATISTIC(NumGEPsElim, "Number of GEPs converted to casts")static llvm::Statistic NumGEPsElim = {"codegenprepare", "NumGEPsElim"
, "Number of GEPs converted to casts"}
;
112STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "static llvm::Statistic NumCmpUses = {"codegenprepare", "NumCmpUses"
, "Number of uses of Cmp expressions replaced with uses of " "sunken Cmps"
}
113 "sunken Cmps")static llvm::Statistic NumCmpUses = {"codegenprepare", "NumCmpUses"
, "Number of uses of Cmp expressions replaced with uses of " "sunken Cmps"
}
;
114STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "static llvm::Statistic NumCastUses = {"codegenprepare", "NumCastUses"
, "Number of uses of Cast expressions replaced with uses " "of sunken Casts"
}
115 "of sunken Casts")static llvm::Statistic NumCastUses = {"codegenprepare", "NumCastUses"
, "Number of uses of Cast expressions replaced with uses " "of sunken Casts"
}
;
116STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "static llvm::Statistic NumMemoryInsts = {"codegenprepare", "NumMemoryInsts"
, "Number of memory instructions whose address " "computations were sunk"
}
117 "computations were sunk")static llvm::Statistic NumMemoryInsts = {"codegenprepare", "NumMemoryInsts"
, "Number of memory instructions whose address " "computations were sunk"
}
;
118STATISTIC(NumMemoryInstsPhiCreated,static llvm::Statistic NumMemoryInstsPhiCreated = {"codegenprepare"
, "NumMemoryInstsPhiCreated", "Number of phis created when address "
"computations were sunk to memory instructions"}
119 "Number of phis created when address "static llvm::Statistic NumMemoryInstsPhiCreated = {"codegenprepare"
, "NumMemoryInstsPhiCreated", "Number of phis created when address "
"computations were sunk to memory instructions"}
120 "computations were sunk to memory instructions")static llvm::Statistic NumMemoryInstsPhiCreated = {"codegenprepare"
, "NumMemoryInstsPhiCreated", "Number of phis created when address "
"computations were sunk to memory instructions"}
;
121STATISTIC(NumMemoryInstsSelectCreated,static llvm::Statistic NumMemoryInstsSelectCreated = {"codegenprepare"
, "NumMemoryInstsSelectCreated", "Number of select created when address "
"computations were sunk to memory instructions"}
122 "Number of select created when address "static llvm::Statistic NumMemoryInstsSelectCreated = {"codegenprepare"
, "NumMemoryInstsSelectCreated", "Number of select created when address "
"computations were sunk to memory instructions"}
123 "computations were sunk to memory instructions")static llvm::Statistic NumMemoryInstsSelectCreated = {"codegenprepare"
, "NumMemoryInstsSelectCreated", "Number of select created when address "
"computations were sunk to memory instructions"}
;
124STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads")static llvm::Statistic NumExtsMoved = {"codegenprepare", "NumExtsMoved"
, "Number of [s|z]ext instructions combined with loads"}
;
125STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized")static llvm::Statistic NumExtUses = {"codegenprepare", "NumExtUses"
, "Number of uses of [s|z]ext instructions optimized"}
;
126STATISTIC(NumAndsAdded,static llvm::Statistic NumAndsAdded = {"codegenprepare", "NumAndsAdded"
, "Number of and mask instructions added to form ext loads"}
127 "Number of and mask instructions added to form ext loads")static llvm::Statistic NumAndsAdded = {"codegenprepare", "NumAndsAdded"
, "Number of and mask instructions added to form ext loads"}
;
128STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized")static llvm::Statistic NumAndUses = {"codegenprepare", "NumAndUses"
, "Number of uses of and mask instructions optimized"}
;
129STATISTIC(NumRetsDup, "Number of return instructions duplicated")static llvm::Statistic NumRetsDup = {"codegenprepare", "NumRetsDup"
, "Number of return instructions duplicated"}
;
130STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved")static llvm::Statistic NumDbgValueMoved = {"codegenprepare", "NumDbgValueMoved"
, "Number of debug value instructions moved"}
;
131STATISTIC(NumSelectsExpanded, "Number of selects turned into branches")static llvm::Statistic NumSelectsExpanded = {"codegenprepare"
, "NumSelectsExpanded", "Number of selects turned into branches"
}
;
132STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed")static llvm::Statistic NumStoreExtractExposed = {"codegenprepare"
, "NumStoreExtractExposed", "Number of store(extractelement) exposed"
}
;
133
134static cl::opt<bool> DisableBranchOpts(
135 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
136 cl::desc("Disable branch optimizations in CodeGenPrepare"));
137
138static cl::opt<bool>
139 DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
140 cl::desc("Disable GC optimizations in CodeGenPrepare"));
141
142static cl::opt<bool> DisableSelectToBranch(
143 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
144 cl::desc("Disable select to branch conversion."));
145
146static cl::opt<bool> AddrSinkUsingGEPs(
147 "addr-sink-using-gep", cl::Hidden, cl::init(true),
148 cl::desc("Address sinking in CGP using GEPs."));
149
150static cl::opt<bool> EnableAndCmpSinking(
151 "enable-andcmp-sinking", cl::Hidden, cl::init(true),
152 cl::desc("Enable sinkinig and/cmp into branches."));
153
154static cl::opt<bool> DisableStoreExtract(
155 "disable-cgp-store-extract", cl::Hidden, cl::init(false),
156 cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
157
158static cl::opt<bool> StressStoreExtract(
159 "stress-cgp-store-extract", cl::Hidden, cl::init(false),
160 cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
161
162static cl::opt<bool> DisableExtLdPromotion(
163 "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
164 cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
165 "CodeGenPrepare"));
166
167static cl::opt<bool> StressExtLdPromotion(
168 "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
169 cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
170 "optimization in CodeGenPrepare"));
171
172static cl::opt<bool> DisablePreheaderProtect(
173 "disable-preheader-prot", cl::Hidden, cl::init(false),
174 cl::desc("Disable protection against removing loop preheaders"));
175
176static cl::opt<bool> ProfileGuidedSectionPrefix(
177 "profile-guided-section-prefix", cl::Hidden, cl::init(true),
178 cl::desc("Use profile info to add section prefix for hot/cold functions"));
179
180static cl::opt<bool> ProfileUnknownInSpecialSection(
181 "profile-unknown-in-special-section", cl::Hidden,
182 cl::desc("In profiling mode like sampleFDO, if a function doesn't have "
183 "profile, we cannot tell the function is cold for sure because "
184 "it may be a function newly added without ever being sampled. "
185 "With the flag enabled, compiler can put such profile unknown "
186 "functions into a special section, so runtime system can choose "
187 "to handle it in a different way than .text section, to save "
188 "RAM for example. "));
189
190static cl::opt<bool> BBSectionsGuidedSectionPrefix(
191 "bbsections-guided-section-prefix", cl::Hidden, cl::init(true),
192 cl::desc("Use the basic-block-sections profile to determine the text "
193 "section prefix for hot functions. Functions with "
194 "basic-block-sections profile will be placed in `.text.hot` "
195 "regardless of their FDO profile info. Other functions won't be "
196 "impacted, i.e., their prefixes will be decided by FDO/sampleFDO "
197 "profiles."));
198
199static cl::opt<unsigned> FreqRatioToSkipMerge(
200 "cgp-freq-ratio-to-skip-merge", cl::Hidden, cl::init(2),
201 cl::desc("Skip merging empty blocks if (frequency of empty block) / "
202 "(frequency of destination block) is greater than this ratio"));
203
204static cl::opt<bool> ForceSplitStore(
205 "force-split-store", cl::Hidden, cl::init(false),
206 cl::desc("Force store splitting no matter what the target query says."));
207
208static cl::opt<bool>
209EnableTypePromotionMerge("cgp-type-promotion-merge", cl::Hidden,
210 cl::desc("Enable merging of redundant sexts when one is dominating"
211 " the other."), cl::init(true));
212
213static cl::opt<bool> DisableComplexAddrModes(
214 "disable-complex-addr-modes", cl::Hidden, cl::init(false),
215 cl::desc("Disables combining addressing modes with different parts "
216 "in optimizeMemoryInst."));
217
218static cl::opt<bool>
219AddrSinkNewPhis("addr-sink-new-phis", cl::Hidden, cl::init(false),
220 cl::desc("Allow creation of Phis in Address sinking."));
221
222static cl::opt<bool>
223AddrSinkNewSelects("addr-sink-new-select", cl::Hidden, cl::init(true),
224 cl::desc("Allow creation of selects in Address sinking."));
225
226static cl::opt<bool> AddrSinkCombineBaseReg(
227 "addr-sink-combine-base-reg", cl::Hidden, cl::init(true),
228 cl::desc("Allow combining of BaseReg field in Address sinking."));
229
230static cl::opt<bool> AddrSinkCombineBaseGV(
231 "addr-sink-combine-base-gv", cl::Hidden, cl::init(true),
232 cl::desc("Allow combining of BaseGV field in Address sinking."));
233
234static cl::opt<bool> AddrSinkCombineBaseOffs(
235 "addr-sink-combine-base-offs", cl::Hidden, cl::init(true),
236 cl::desc("Allow combining of BaseOffs field in Address sinking."));
237
238static cl::opt<bool> AddrSinkCombineScaledReg(
239 "addr-sink-combine-scaled-reg", cl::Hidden, cl::init(true),
240 cl::desc("Allow combining of ScaledReg field in Address sinking."));
241
242static cl::opt<bool>
243 EnableGEPOffsetSplit("cgp-split-large-offset-gep", cl::Hidden,
244 cl::init(true),
245 cl::desc("Enable splitting large offset of GEP."));
246
247static cl::opt<bool> EnableICMP_EQToICMP_ST(
248 "cgp-icmp-eq2icmp-st", cl::Hidden, cl::init(false),
249 cl::desc("Enable ICMP_EQ to ICMP_S(L|G)T conversion."));
250
251static cl::opt<bool>
252 VerifyBFIUpdates("cgp-verify-bfi-updates", cl::Hidden, cl::init(false),
253 cl::desc("Enable BFI update verification for "
254 "CodeGenPrepare."));
255
256static cl::opt<bool> OptimizePhiTypes(
257 "cgp-optimize-phi-types", cl::Hidden, cl::init(false),
258 cl::desc("Enable converting phi types in CodeGenPrepare"));
259
260namespace {
261
262enum ExtType {
263 ZeroExtension, // Zero extension has been seen.
264 SignExtension, // Sign extension has been seen.
265 BothExtension // This extension type is used if we saw sext after
266 // ZeroExtension had been set, or if we saw zext after
267 // SignExtension had been set. It makes the type
268 // information of a promoted instruction invalid.
269};
270
271using SetOfInstrs = SmallPtrSet<Instruction *, 16>;
272using TypeIsSExt = PointerIntPair<Type *, 2, ExtType>;
273using InstrToOrigTy = DenseMap<Instruction *, TypeIsSExt>;
274using SExts = SmallVector<Instruction *, 16>;
275using ValueToSExts = DenseMap<Value *, SExts>;
276
277class TypePromotionTransaction;
278
279 class CodeGenPrepare : public FunctionPass {
280 const TargetMachine *TM = nullptr;
281 const TargetSubtargetInfo *SubtargetInfo;
282 const TargetLowering *TLI = nullptr;
283 const TargetRegisterInfo *TRI;
284 const TargetTransformInfo *TTI = nullptr;
285 const BasicBlockSectionsProfileReader *BBSectionsProfileReader = nullptr;
286 const TargetLibraryInfo *TLInfo;
287 const LoopInfo *LI;
288 std::unique_ptr<BlockFrequencyInfo> BFI;
289 std::unique_ptr<BranchProbabilityInfo> BPI;
290 ProfileSummaryInfo *PSI;
291
292 /// As we scan instructions optimizing them, this is the next instruction
293 /// to optimize. Transforms that can invalidate this should update it.
294 BasicBlock::iterator CurInstIterator;
295
296 /// Keeps track of non-local addresses that have been sunk into a block.
297 /// This allows us to avoid inserting duplicate code for blocks with
298 /// multiple load/stores of the same address. The usage of WeakTrackingVH
299 /// enables SunkAddrs to be treated as a cache whose entries can be
300 /// invalidated if a sunken address computation has been erased.
301 ValueMap<Value*, WeakTrackingVH> SunkAddrs;
302
303 /// Keeps track of all instructions inserted for the current function.
304 SetOfInstrs InsertedInsts;
305
306 /// Keeps track of the type of the related instruction before their
307 /// promotion for the current function.
308 InstrToOrigTy PromotedInsts;
309
310 /// Keep track of instructions removed during promotion.
311 SetOfInstrs RemovedInsts;
312
313 /// Keep track of sext chains based on their initial value.
314 DenseMap<Value *, Instruction *> SeenChainsForSExt;
315
316 /// Keep track of GEPs accessing the same data structures such as structs or
317 /// arrays that are candidates to be split later because of their large
318 /// size.
319 MapVector<
320 AssertingVH<Value>,
321 SmallVector<std::pair<AssertingVH<GetElementPtrInst>, int64_t>, 32>>
322 LargeOffsetGEPMap;
323
324 /// Keep track of new GEP base after splitting the GEPs having large offset.
325 SmallSet<AssertingVH<Value>, 2> NewGEPBases;
326
327 /// Map serial numbers to Large offset GEPs.
328 DenseMap<AssertingVH<GetElementPtrInst>, int> LargeOffsetGEPID;
329
330 /// Keep track of SExt promoted.
331 ValueToSExts ValToSExtendedUses;
332
333 /// True if the function has the OptSize attribute.
334 bool OptSize;
335
336 /// DataLayout for the Function being processed.
337 const DataLayout *DL = nullptr;
338
339 /// Building the dominator tree can be expensive, so we only build it
340 /// lazily and update it when required.
341 std::unique_ptr<DominatorTree> DT;
342
343 public:
344 static char ID; // Pass identification, replacement for typeid
345
346 CodeGenPrepare() : FunctionPass(ID) {
347 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
348 }
349
350 bool runOnFunction(Function &F) override;
351
352 StringRef getPassName() const override { return "CodeGen Prepare"; }
353
354 void getAnalysisUsage(AnalysisUsage &AU) const override {
355 // FIXME: When we can selectively preserve passes, preserve the domtree.
356 AU.addRequired<ProfileSummaryInfoWrapperPass>();
357 AU.addRequired<TargetLibraryInfoWrapperPass>();
358 AU.addRequired<TargetPassConfig>();
359 AU.addRequired<TargetTransformInfoWrapperPass>();
360 AU.addRequired<LoopInfoWrapperPass>();
361 AU.addUsedIfAvailable<BasicBlockSectionsProfileReader>();
362 }
363
364 private:
365 template <typename F>
366 void resetIteratorIfInvalidatedWhileCalling(BasicBlock *BB, F f) {
367 // Substituting can cause recursive simplifications, which can invalidate
368 // our iterator. Use a WeakTrackingVH to hold onto it in case this
369 // happens.
370 Value *CurValue = &*CurInstIterator;
371 WeakTrackingVH IterHandle(CurValue);
372
373 f();
374
375 // If the iterator instruction was recursively deleted, start over at the
376 // start of the block.
377 if (IterHandle != CurValue) {
378 CurInstIterator = BB->begin();
379 SunkAddrs.clear();
380 }
381 }
382
383 // Get the DominatorTree, building if necessary.
384 DominatorTree &getDT(Function &F) {
385 if (!DT)
386 DT = std::make_unique<DominatorTree>(F);
387 return *DT;
388 }
389
390 void removeAllAssertingVHReferences(Value *V);
391 bool eliminateAssumptions(Function &F);
392 bool eliminateFallThrough(Function &F);
393 bool eliminateMostlyEmptyBlocks(Function &F);
394 BasicBlock *findDestBlockOfMergeableEmptyBlock(BasicBlock *BB);
395 bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
396 void eliminateMostlyEmptyBlock(BasicBlock *BB);
397 bool isMergingEmptyBlockProfitable(BasicBlock *BB, BasicBlock *DestBB,
398 bool isPreheader);
399 bool makeBitReverse(Instruction &I);
400 bool optimizeBlock(BasicBlock &BB, bool &ModifiedDT);
401 bool optimizeInst(Instruction *I, bool &ModifiedDT);
402 bool optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
403 Type *AccessTy, unsigned AddrSpace);
404 bool optimizeGatherScatterInst(Instruction *MemoryInst, Value *Ptr);
405 bool optimizeInlineAsmInst(CallInst *CS);
406 bool optimizeCallInst(CallInst *CI, bool &ModifiedDT);
407 bool optimizeExt(Instruction *&I);
408 bool optimizeExtUses(Instruction *I);
409 bool optimizeLoadExt(LoadInst *Load);
410 bool optimizeShiftInst(BinaryOperator *BO);
411 bool optimizeFunnelShift(IntrinsicInst *Fsh);
412 bool optimizeSelectInst(SelectInst *SI);
413 bool optimizeShuffleVectorInst(ShuffleVectorInst *SVI);
414 bool optimizeSwitchType(SwitchInst *SI);
415 bool optimizeSwitchPhiConstants(SwitchInst *SI);
416 bool optimizeSwitchInst(SwitchInst *SI);
417 bool optimizeExtractElementInst(Instruction *Inst);
418 bool dupRetToEnableTailCallOpts(BasicBlock *BB, bool &ModifiedDT);
419 bool fixupDbgValue(Instruction *I);
420 bool placeDbgValues(Function &F);
421 bool placePseudoProbes(Function &F);
422 bool canFormExtLd(const SmallVectorImpl<Instruction *> &MovedExts,
423 LoadInst *&LI, Instruction *&Inst, bool HasPromoted);
424 bool tryToPromoteExts(TypePromotionTransaction &TPT,
425 const SmallVectorImpl<Instruction *> &Exts,
426 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
427 unsigned CreatedInstsCost = 0);
428 bool mergeSExts(Function &F);
429 bool splitLargeGEPOffsets();
430 bool optimizePhiType(PHINode *Inst, SmallPtrSetImpl<PHINode *> &Visited,
431 SmallPtrSetImpl<Instruction *> &DeletedInstrs);
432 bool optimizePhiTypes(Function &F);
433 bool performAddressTypePromotion(
434 Instruction *&Inst,
435 bool AllowPromotionWithoutCommonHeader,
436 bool HasPromoted, TypePromotionTransaction &TPT,
437 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts);
438 bool splitBranchCondition(Function &F, bool &ModifiedDT);
439 bool simplifyOffsetableRelocate(GCStatepointInst &I);
440
441 bool tryToSinkFreeOperands(Instruction *I);
442 bool replaceMathCmpWithIntrinsic(BinaryOperator *BO, Value *Arg0,
443 Value *Arg1, CmpInst *Cmp,
444 Intrinsic::ID IID);
445 bool optimizeCmp(CmpInst *Cmp, bool &ModifiedDT);
446 bool combineToUSubWithOverflow(CmpInst *Cmp, bool &ModifiedDT);
447 bool combineToUAddWithOverflow(CmpInst *Cmp, bool &ModifiedDT);
448 void verifyBFIUpdates(Function &F);
449 };
450
451} // end anonymous namespace
452
453char CodeGenPrepare::ID = 0;
454
455INITIALIZE_PASS_BEGIN(CodeGenPrepare, DEBUG_TYPE,static void *initializeCodeGenPreparePassOnce(PassRegistry &
Registry) {
456 "Optimize for code generation", false, false)static void *initializeCodeGenPreparePassOnce(PassRegistry &
Registry) {
457INITIALIZE_PASS_DEPENDENCY(BasicBlockSectionsProfileReader)initializeBasicBlockSectionsProfileReaderPass(Registry);
458INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)initializeLoopInfoWrapperPassPass(Registry);
459INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)initializeProfileSummaryInfoWrapperPassPass(Registry);
460INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)initializeTargetLibraryInfoWrapperPassPass(Registry);
461INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)initializeTargetPassConfigPass(Registry);
462INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)initializeTargetTransformInfoWrapperPassPass(Registry);
463INITIALIZE_PASS_END(CodeGenPrepare, DEBUG_TYPE,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)); }
464 "Optimize for code generation", 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)); }
465
466FunctionPass *llvm::createCodeGenPreparePass() { return new CodeGenPrepare(); }
467
468bool CodeGenPrepare::runOnFunction(Function &F) {
469 if (skipFunction(F))
470 return false;
471
472 DL = &F.getParent()->getDataLayout();
473
474 bool EverMadeChange = false;
475 // Clear per function information.
476 InsertedInsts.clear();
477 PromotedInsts.clear();
478
479 TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
480 SubtargetInfo = TM->getSubtargetImpl(F);
481 TLI = SubtargetInfo->getTargetLowering();
482 TRI = SubtargetInfo->getRegisterInfo();
483 TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
484 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
485 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
486 BPI.reset(new BranchProbabilityInfo(F, *LI));
487 BFI.reset(new BlockFrequencyInfo(F, *BPI, *LI));
488 PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
489 BBSectionsProfileReader =
490 getAnalysisIfAvailable<BasicBlockSectionsProfileReader>();
491 OptSize = F.hasOptSize();
492 // Use the basic-block-sections profile to promote hot functions to .text.hot if requested.
493 if (BBSectionsGuidedSectionPrefix && BBSectionsProfileReader &&
494 BBSectionsProfileReader->isFunctionHot(F.getName())) {
495 F.setSectionPrefix("hot");
496 } else if (ProfileGuidedSectionPrefix) {
497 // The hot attribute overwrites profile count based hotness while profile
498 // counts based hotness overwrite the cold attribute.
499 // This is a conservative behabvior.
500 if (F.hasFnAttribute(Attribute::Hot) ||
501 PSI->isFunctionHotInCallGraph(&F, *BFI))
502 F.setSectionPrefix("hot");
503 // If PSI shows this function is not hot, we will placed the function
504 // into unlikely section if (1) PSI shows this is a cold function, or
505 // (2) the function has a attribute of cold.
506 else if (PSI->isFunctionColdInCallGraph(&F, *BFI) ||
507 F.hasFnAttribute(Attribute::Cold))
508 F.setSectionPrefix("unlikely");
509 else if (ProfileUnknownInSpecialSection && PSI->hasPartialSampleProfile() &&
510 PSI->isFunctionHotnessUnknown(F))
511 F.setSectionPrefix("unknown");
512 }
513
514 /// This optimization identifies DIV instructions that can be
515 /// profitably bypassed and carried out with a shorter, faster divide.
516 if (!OptSize && !PSI->hasHugeWorkingSetSize() && TLI->isSlowDivBypassed()) {
517 const DenseMap<unsigned int, unsigned int> &BypassWidths =
518 TLI->getBypassSlowDivWidths();
519 BasicBlock* BB = &*F.begin();
520 while (BB != nullptr) {
521 // bypassSlowDivision may create new BBs, but we don't want to reapply the
522 // optimization to those blocks.
523 BasicBlock* Next = BB->getNextNode();
524 // F.hasOptSize is already checked in the outer if statement.
525 if (!llvm::shouldOptimizeForSize(BB, PSI, BFI.get()))
526 EverMadeChange |= bypassSlowDivision(BB, BypassWidths);
527 BB = Next;
528 }
529 }
530
531 // Get rid of @llvm.assume builtins before attempting to eliminate empty
532 // blocks, since there might be blocks that only contain @llvm.assume calls
533 // (plus arguments that we can get rid of).
534 EverMadeChange |= eliminateAssumptions(F);
535
536 // Eliminate blocks that contain only PHI nodes and an
537 // unconditional branch.
538 EverMadeChange |= eliminateMostlyEmptyBlocks(F);
539
540 bool ModifiedDT = false;
541 if (!DisableBranchOpts)
542 EverMadeChange |= splitBranchCondition(F, ModifiedDT);
543
544 // Split some critical edges where one of the sources is an indirect branch,
545 // to help generate sane code for PHIs involving such edges.
546 EverMadeChange |=
547 SplitIndirectBrCriticalEdges(F, /*IgnoreBlocksWithoutPHI=*/true);
548
549 bool MadeChange = true;
550 while (MadeChange) {
551 MadeChange = false;
552 DT.reset();
553 for (BasicBlock &BB : llvm::make_early_inc_range(F)) {
554 bool ModifiedDTOnIteration = false;
555 MadeChange |= optimizeBlock(BB, ModifiedDTOnIteration);
556
557 // Restart BB iteration if the dominator tree of the Function was changed
558 if (ModifiedDTOnIteration)
559 break;
560 }
561 if (EnableTypePromotionMerge && !ValToSExtendedUses.empty())
562 MadeChange |= mergeSExts(F);
563 if (!LargeOffsetGEPMap.empty())
564 MadeChange |= splitLargeGEPOffsets();
565 MadeChange |= optimizePhiTypes(F);
566
567 if (MadeChange)
568 eliminateFallThrough(F);
569
570 // Really free removed instructions during promotion.
571 for (Instruction *I : RemovedInsts)
572 I->deleteValue();
573
574 EverMadeChange |= MadeChange;
575 SeenChainsForSExt.clear();
576 ValToSExtendedUses.clear();
577 RemovedInsts.clear();
578 LargeOffsetGEPMap.clear();
579 LargeOffsetGEPID.clear();
580 }
581
582 NewGEPBases.clear();
583 SunkAddrs.clear();
584
585 if (!DisableBranchOpts) {
586 MadeChange = false;
587 // Use a set vector to get deterministic iteration order. The order the
588 // blocks are removed may affect whether or not PHI nodes in successors
589 // are removed.
590 SmallSetVector<BasicBlock*, 8> WorkList;
591 for (BasicBlock &BB : F) {
592 SmallVector<BasicBlock *, 2> Successors(successors(&BB));
593 MadeChange |= ConstantFoldTerminator(&BB, true);
594 if (!MadeChange) continue;
595
596 for (BasicBlock *Succ : Successors)
597 if (pred_empty(Succ))
598 WorkList.insert(Succ);
599 }
600
601 // Delete the dead blocks and any of their dead successors.
602 MadeChange |= !WorkList.empty();
603 while (!WorkList.empty()) {
604 BasicBlock *BB = WorkList.pop_back_val();
605 SmallVector<BasicBlock*, 2> Successors(successors(BB));
606
607 DeleteDeadBlock(BB);
608
609 for (BasicBlock *Succ : Successors)
610 if (pred_empty(Succ))
611 WorkList.insert(Succ);
612 }
613
614 // Merge pairs of basic blocks with unconditional branches, connected by
615 // a single edge.
616 if (EverMadeChange || MadeChange)
617 MadeChange |= eliminateFallThrough(F);
618
619 EverMadeChange |= MadeChange;
620 }
621
622 if (!DisableGCOpts) {
623 SmallVector<GCStatepointInst *, 2> Statepoints;
624 for (BasicBlock &BB : F)
625 for (Instruction &I : BB)
626 if (auto *SP = dyn_cast<GCStatepointInst>(&I))
627 Statepoints.push_back(SP);
628 for (auto &I : Statepoints)
629 EverMadeChange |= simplifyOffsetableRelocate(*I);
630 }
631
632 // Do this last to clean up use-before-def scenarios introduced by other
633 // preparatory transforms.
634 EverMadeChange |= placeDbgValues(F);
635 EverMadeChange |= placePseudoProbes(F);
636
637#ifndef NDEBUG
638 if (VerifyBFIUpdates)
639 verifyBFIUpdates(F);
640#endif
641
642 return EverMadeChange;
643}
644
645bool CodeGenPrepare::eliminateAssumptions(Function &F) {
646 bool MadeChange = false;
647 for (BasicBlock &BB : F) {
648 CurInstIterator = BB.begin();
649 while (CurInstIterator != BB.end()) {
650 Instruction *I = &*(CurInstIterator++);
651 if (auto *Assume = dyn_cast<AssumeInst>(I)) {
652 MadeChange = true;
653 Value *Operand = Assume->getOperand(0);
654 Assume->eraseFromParent();
655
656 resetIteratorIfInvalidatedWhileCalling(&BB, [&]() {
657 RecursivelyDeleteTriviallyDeadInstructions(Operand, TLInfo, nullptr);
658 });
659 }
660 }
661 }
662 return MadeChange;
663}
664
665/// An instruction is about to be deleted, so remove all references to it in our
666/// GEP-tracking data strcutures.
667void CodeGenPrepare::removeAllAssertingVHReferences(Value *V) {
668 LargeOffsetGEPMap.erase(V);
669 NewGEPBases.erase(V);
670
671 auto GEP = dyn_cast<GetElementPtrInst>(V);
672 if (!GEP)
673 return;
674
675 LargeOffsetGEPID.erase(GEP);
676
677 auto VecI = LargeOffsetGEPMap.find(GEP->getPointerOperand());
678 if (VecI == LargeOffsetGEPMap.end())
679 return;
680
681 auto &GEPVector = VecI->second;
682 llvm::erase_if(GEPVector, [=](auto &Elt) { return Elt.first == GEP; });
683
684 if (GEPVector.empty())
685 LargeOffsetGEPMap.erase(VecI);
686}
687
688// Verify BFI has been updated correctly by recomputing BFI and comparing them.
689void LLVM_ATTRIBUTE_UNUSED__attribute__((__unused__)) CodeGenPrepare::verifyBFIUpdates(Function &F) {
690 DominatorTree NewDT(F);
691 LoopInfo NewLI(NewDT);
692 BranchProbabilityInfo NewBPI(F, NewLI, TLInfo);
693 BlockFrequencyInfo NewBFI(F, NewBPI, NewLI);
694 NewBFI.verifyMatch(*BFI);
695}
696
697/// Merge basic blocks which are connected by a single edge, where one of the
698/// basic blocks has a single successor pointing to the other basic block,
699/// which has a single predecessor.
700bool CodeGenPrepare::eliminateFallThrough(Function &F) {
701 bool Changed = false;
702 // Scan all of the blocks in the function, except for the entry block.
703 // Use a temporary array to avoid iterator being invalidated when
704 // deleting blocks.
705 SmallVector<WeakTrackingVH, 16> Blocks;
706 for (auto &Block : llvm::drop_begin(F))
707 Blocks.push_back(&Block);
708
709 SmallSet<WeakTrackingVH, 16> Preds;
710 for (auto &Block : Blocks) {
711 auto *BB = cast_or_null<BasicBlock>(Block);
712 if (!BB)
713 continue;
714 // If the destination block has a single pred, then this is a trivial
715 // edge, just collapse it.
716 BasicBlock *SinglePred = BB->getSinglePredecessor();
717
718 // Don't merge if BB's address is taken.
719 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
720
721 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
722 if (Term && !Term->isConditional()) {
723 Changed = true;
724 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)
;
725
726 // Merge BB into SinglePred and delete it.
727 MergeBlockIntoPredecessor(BB);
728 Preds.insert(SinglePred);
729 }
730 }
731
732 // (Repeatedly) merging blocks into their predecessors can create redundant
733 // debug intrinsics.
734 for (const auto &Pred : Preds)
735 if (auto *BB = cast_or_null<BasicBlock>(Pred))
736 RemoveRedundantDbgInstrs(BB);
737
738 return Changed;
739}
740
741/// Find a destination block from BB if BB is mergeable empty block.
742BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) {
743 // If this block doesn't end with an uncond branch, ignore it.
744 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
745 if (!BI || !BI->isUnconditional())
746 return nullptr;
747
748 // If the instruction before the branch (skipping debug info) isn't a phi
749 // node, then other stuff is happening here.
750 BasicBlock::iterator BBI = BI->getIterator();
751 if (BBI != BB->begin()) {
752 --BBI;
753 while (isa<DbgInfoIntrinsic>(BBI)) {
754 if (BBI == BB->begin())
755 break;
756 --BBI;
757 }
758 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
759 return nullptr;
760 }
761
762 // Do not break infinite loops.
763 BasicBlock *DestBB = BI->getSuccessor(0);
764 if (DestBB == BB)
765 return nullptr;
766
767 if (!canMergeBlocks(BB, DestBB))
768 DestBB = nullptr;
769
770 return DestBB;
771}
772
773/// Eliminate blocks that contain only PHI nodes, debug info directives, and an
774/// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
775/// edges in ways that are non-optimal for isel. Start by eliminating these
776/// blocks so we can split them the way we want them.
777bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
778 SmallPtrSet<BasicBlock *, 16> Preheaders;
779 SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end());
780 while (!LoopList.empty()) {
781 Loop *L = LoopList.pop_back_val();
782 llvm::append_range(LoopList, *L);
783 if (BasicBlock *Preheader = L->getLoopPreheader())
784 Preheaders.insert(Preheader);
785 }
786
787 bool MadeChange = false;
788 // Copy blocks into a temporary array to avoid iterator invalidation issues
789 // as we remove them.
790 // Note that this intentionally skips the entry block.
791 SmallVector<WeakTrackingVH, 16> Blocks;
792 for (auto &Block : llvm::drop_begin(F))
793 Blocks.push_back(&Block);
794
795 for (auto &Block : Blocks) {
796 BasicBlock *BB = cast_or_null<BasicBlock>(Block);
797 if (!BB)
798 continue;
799 BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB);
800 if (!DestBB ||
801 !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.count(BB)))
802 continue;
803
804 eliminateMostlyEmptyBlock(BB);
805 MadeChange = true;
806 }
807 return MadeChange;
808}
809
810bool CodeGenPrepare::isMergingEmptyBlockProfitable(BasicBlock *BB,
811 BasicBlock *DestBB,
812 bool isPreheader) {
813 // Do not delete loop preheaders if doing so would create a critical edge.
814 // Loop preheaders can be good locations to spill registers. If the
815 // preheader is deleted and we create a critical edge, registers may be
816 // spilled in the loop body instead.
817 if (!DisablePreheaderProtect && isPreheader &&
818 !(BB->getSinglePredecessor() &&
819 BB->getSinglePredecessor()->getSingleSuccessor()))
820 return false;
821
822 // Skip merging if the block's successor is also a successor to any callbr
823 // that leads to this block.
824 // FIXME: Is this really needed? Is this a correctness issue?
825 for (BasicBlock *Pred : predecessors(BB)) {
826 if (auto *CBI = dyn_cast<CallBrInst>((Pred)->getTerminator()))
827 for (unsigned i = 0, e = CBI->getNumSuccessors(); i != e; ++i)
828 if (DestBB == CBI->getSuccessor(i))
829 return false;
830 }
831
832 // Try to skip merging if the unique predecessor of BB is terminated by a
833 // switch or indirect branch instruction, and BB is used as an incoming block
834 // of PHIs in DestBB. In such case, merging BB and DestBB would cause ISel to
835 // add COPY instructions in the predecessor of BB instead of BB (if it is not
836 // merged). Note that the critical edge created by merging such blocks wont be
837 // split in MachineSink because the jump table is not analyzable. By keeping
838 // such empty block (BB), ISel will place COPY instructions in BB, not in the
839 // predecessor of BB.
840 BasicBlock *Pred = BB->getUniquePredecessor();
841 if (!Pred ||
842 !(isa<SwitchInst>(Pred->getTerminator()) ||
843 isa<IndirectBrInst>(Pred->getTerminator())))
844 return true;
845
846 if (BB->getTerminator() != BB->getFirstNonPHIOrDbg())
847 return true;
848
849 // We use a simple cost heuristic which determine skipping merging is
850 // profitable if the cost of skipping merging is less than the cost of
851 // merging : Cost(skipping merging) < Cost(merging BB), where the
852 // Cost(skipping merging) is Freq(BB) * (Cost(Copy) + Cost(Branch)), and
853 // the Cost(merging BB) is Freq(Pred) * Cost(Copy).
854 // Assuming Cost(Copy) == Cost(Branch), we could simplify it to :
855 // Freq(Pred) / Freq(BB) > 2.
856 // Note that if there are multiple empty blocks sharing the same incoming
857 // value for the PHIs in the DestBB, we consider them together. In such
858 // case, Cost(merging BB) will be the sum of their frequencies.
859
860 if (!isa<PHINode>(DestBB->begin()))
861 return true;
862
863 SmallPtrSet<BasicBlock *, 16> SameIncomingValueBBs;
864
865 // Find all other incoming blocks from which incoming values of all PHIs in
866 // DestBB are the same as the ones from BB.
867 for (BasicBlock *DestBBPred : predecessors(DestBB)) {
868 if (DestBBPred == BB)
869 continue;
870
871 if (llvm::all_of(DestBB->phis(), [&](const PHINode &DestPN) {
872 return DestPN.getIncomingValueForBlock(BB) ==
873 DestPN.getIncomingValueForBlock(DestBBPred);
874 }))
875 SameIncomingValueBBs.insert(DestBBPred);
876 }
877
878 // See if all BB's incoming values are same as the value from Pred. In this
879 // case, no reason to skip merging because COPYs are expected to be place in
880 // Pred already.
881 if (SameIncomingValueBBs.count(Pred))
882 return true;
883
884 BlockFrequency PredFreq = BFI->getBlockFreq(Pred);
885 BlockFrequency BBFreq = BFI->getBlockFreq(BB);
886
887 for (auto *SameValueBB : SameIncomingValueBBs)
888 if (SameValueBB->getUniquePredecessor() == Pred &&
889 DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB))
890 BBFreq += BFI->getBlockFreq(SameValueBB);
891
892 return PredFreq.getFrequency() <=
893 BBFreq.getFrequency() * FreqRatioToSkipMerge;
894}
895
896/// Return true if we can merge BB into DestBB if there is a single
897/// unconditional branch between them, and BB contains no other non-phi
898/// instructions.
899bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
900 const BasicBlock *DestBB) const {
901 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
902 // the successor. If there are more complex condition (e.g. preheaders),
903 // don't mess around with them.
904 for (const PHINode &PN : BB->phis()) {
905 for (const User *U : PN.users()) {
906 const Instruction *UI = cast<Instruction>(U);
907 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
908 return false;
909 // If User is inside DestBB block and it is a PHINode then check
910 // incoming value. If incoming value is not from BB then this is
911 // a complex condition (e.g. preheaders) we want to avoid here.
912 if (UI->getParent() == DestBB) {
913 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
914 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
915 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
916 if (Insn && Insn->getParent() == BB &&
917 Insn->getParent() != UPN->getIncomingBlock(I))
918 return false;
919 }
920 }
921 }
922 }
923
924 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
925 // and DestBB may have conflicting incoming values for the block. If so, we
926 // can't merge the block.
927 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
928 if (!DestBBPN) return true; // no conflict.
929
930 // Collect the preds of BB.
931 SmallPtrSet<const BasicBlock*, 16> BBPreds;
932 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
933 // It is faster to get preds from a PHI than with pred_iterator.
934 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
935 BBPreds.insert(BBPN->getIncomingBlock(i));
936 } else {
937 BBPreds.insert(pred_begin(BB), pred_end(BB));
938 }
939
940 // Walk the preds of DestBB.
941 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
942 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
943 if (BBPreds.count(Pred)) { // Common predecessor?
944 for (const PHINode &PN : DestBB->phis()) {
945 const Value *V1 = PN.getIncomingValueForBlock(Pred);
946 const Value *V2 = PN.getIncomingValueForBlock(BB);
947
948 // If V2 is a phi node in BB, look up what the mapped value will be.
949 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
950 if (V2PN->getParent() == BB)
951 V2 = V2PN->getIncomingValueForBlock(Pred);
952
953 // If there is a conflict, bail out.
954 if (V1 != V2) return false;
955 }
956 }
957 }
958
959 return true;
960}
961
962/// Eliminate a basic block that has only phi's and an unconditional branch in
963/// it.
964void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
965 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
966 BasicBlock *DestBB = BI->getSuccessor(0);
967
968 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)
969 << *BB << *DestBB)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n"
<< *BB << *DestBB; } } while (false)
;
970
971 // If the destination block has a single pred, then this is a trivial edge,
972 // just collapse it.
973 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
974 if (SinglePred != DestBB) {
975 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", 976, __extension__ __PRETTY_FUNCTION__
))
976 "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", 976, __extension__ __PRETTY_FUNCTION__
))
;
977 // Merge DestBB into SinglePred/BB and delete it.
978 MergeBlockIntoPredecessor(DestBB);
979 // Note: BB(=SinglePred) will not be deleted on this path.
980 // DestBB(=its single successor) is the one that was deleted.
981 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)
;
982 return;
983 }
984 }
985
986 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
987 // to handle the new incoming edges it is about to have.
988 for (PHINode &PN : DestBB->phis()) {
989 // Remove the incoming value for BB, and remember it.
990 Value *InVal = PN.removeIncomingValue(BB, false);
991
992 // Two options: either the InVal is a phi node defined in BB or it is some
993 // value that dominates BB.
994 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
995 if (InValPhi && InValPhi->getParent() == BB) {
996 // Add all of the input values of the input PHI as inputs of this phi.
997 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
998 PN.addIncoming(InValPhi->getIncomingValue(i),
999 InValPhi->getIncomingBlock(i));
1000 } else {
1001 // Otherwise, add one instance of the dominating value for each edge that
1002 // we will be adding.
1003 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
1004 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
1005 PN.addIncoming(InVal, BBPN->getIncomingBlock(i));
1006 } else {
1007 for (BasicBlock *Pred : predecessors(BB))
1008 PN.addIncoming(InVal, Pred);
1009 }
1010 }
1011 }
1012
1013 // The PHIs are now updated, change everything that refers to BB to use
1014 // DestBB and remove BB.
1015 BB->replaceAllUsesWith(DestBB);
1016 BB->eraseFromParent();
1017 ++NumBlocksElim;
1018
1019 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)
;
1020}
1021
1022// Computes a map of base pointer relocation instructions to corresponding
1023// derived pointer relocation instructions given a vector of all relocate calls
1024static void computeBaseDerivedRelocateMap(
1025 const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
1026 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>>
1027 &RelocateInstMap) {
1028 // Collect information in two maps: one primarily for locating the base object
1029 // while filling the second map; the second map is the final structure holding
1030 // a mapping between Base and corresponding Derived relocate calls
1031 DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap;
1032 for (auto *ThisRelocate : AllRelocateCalls) {
1033 auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
1034 ThisRelocate->getDerivedPtrIndex());
1035 RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
1036 }
1037 for (auto &Item : RelocateIdxMap) {
1038 std::pair<unsigned, unsigned> Key = Item.first;
1039 if (Key.first == Key.second)
1040 // Base relocation: nothing to insert
1041 continue;
1042
1043 GCRelocateInst *I = Item.second;
1044 auto BaseKey = std::make_pair(Key.first, Key.first);
1045
1046 // We're iterating over RelocateIdxMap so we cannot modify it.
1047 auto MaybeBase = RelocateIdxMap.find(BaseKey);
1048 if (MaybeBase == RelocateIdxMap.end())
1049 // TODO: We might want to insert a new base object relocate and gep off
1050 // that, if there are enough derived object relocates.
1051 continue;
1052
1053 RelocateInstMap[MaybeBase->second].push_back(I);
1054 }
1055}
1056
1057// Accepts a GEP and extracts the operands into a vector provided they're all
1058// small integer constants
1059static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
1060 SmallVectorImpl<Value *> &OffsetV) {
1061 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
1062 // Only accept small constant integer operands
1063 auto *Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
1064 if (!Op || Op->getZExtValue() > 20)
1065 return false;
1066 }
1067
1068 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
1069 OffsetV.push_back(GEP->getOperand(i));
1070 return true;
1071}
1072
1073// Takes a RelocatedBase (base pointer relocation instruction) and Targets to
1074// replace, computes a replacement, and affects it.
1075static bool
1076simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase,
1077 const SmallVectorImpl<GCRelocateInst *> &Targets) {
1078 bool MadeChange = false;
1079 // We must ensure the relocation of derived pointer is defined after
1080 // relocation of base pointer. If we find a relocation corresponding to base
1081 // defined earlier than relocation of base then we move relocation of base
1082 // right before found relocation. We consider only relocation in the same
1083 // basic block as relocation of base. Relocations from other basic block will
1084 // be skipped by optimization and we do not care about them.
1085 for (auto R = RelocatedBase->getParent()->getFirstInsertionPt();
7
Loop condition is false. Execution continues on line 1094
1086 &*R != RelocatedBase; ++R)
6
Assuming the condition is false
1087 if (auto *RI = dyn_cast<GCRelocateInst>(R))
1088 if (RI->getStatepoint() == RelocatedBase->getStatepoint())
1089 if (RI->getBasePtrIndex() == RelocatedBase->getBasePtrIndex()) {
1090 RelocatedBase->moveBefore(RI);
1091 break;
1092 }
1093
1094 for (GCRelocateInst *ToReplace : Targets) {
8
Assuming '__begin1' is not equal to '__end1'
1095 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", 1096, __extension__ __PRETTY_FUNCTION__
))
9
Assuming the condition is true
10
'?' condition is true
1096 "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", 1096, __extension__ __PRETTY_FUNCTION__
))
;
1097 if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
11
Assuming the condition is false
12
Taking false branch
1098 // A duplicate relocate call. TODO: coalesce duplicates.
1099 continue;
1100 }
1101
1102 if (RelocatedBase->getParent() != ToReplace->getParent()) {
13
Assuming the condition is false
14
Taking false branch
1103 // Base and derived relocates are in different basic blocks.
1104 // In this case transform is only valid when base dominates derived
1105 // relocate. However it would be too expensive to check dominance
1106 // for each such relocate, so we skip the whole transformation.
1107 continue;
1108 }
1109
1110 Value *Base = ToReplace->getBasePtr();
15
'Base' initialized here
1111 auto *Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
16
Assuming the object is a 'CastReturnType'
1112 if (!Derived
16.1
'Derived' is non-null
|| Derived->getPointerOperand() != Base)
17
Assuming pointer value is null
18
Taking false branch
1113 continue;
1114
1115 SmallVector<Value *, 2> OffsetV;
1116 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
1117 continue;
1118
1119 // Create a Builder and replace the target callsite with a gep
1120 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", 1121, __extension__ __PRETTY_FUNCTION__
))
19
Taking false branch
20
Assuming the condition is true
21
'?' condition is true
1121 "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", 1121, __extension__ __PRETTY_FUNCTION__
))
;
1122
1123 // Insert after RelocatedBase
1124 IRBuilder<> Builder(RelocatedBase->getNextNode());
1125 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
1126
1127 // If gc_relocate does not match the actual type, cast it to the right type.
1128 // In theory, there must be a bitcast after gc_relocate if the type does not
1129 // match, and we should reuse it to get the derived pointer. But it could be
1130 // cases like this:
1131 // bb1:
1132 // ...
1133 // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
1134 // br label %merge
1135 //
1136 // bb2:
1137 // ...
1138 // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
1139 // br label %merge
1140 //
1141 // merge:
1142 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
1143 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
1144 //
1145 // In this case, we can not find the bitcast any more. So we insert a new bitcast
1146 // no matter there is already one or not. In this way, we can handle all cases, and
1147 // the extra bitcast should be optimized away in later passes.
1148 Value *ActualRelocatedBase = RelocatedBase;
1149 if (RelocatedBase->getType() != Base->getType()) {
22
Called C++ object pointer is null
1150 ActualRelocatedBase =
1151 Builder.CreateBitCast(RelocatedBase, Base->getType());
1152 }
1153 Value *Replacement = Builder.CreateGEP(
1154 Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
1155 Replacement->takeName(ToReplace);
1156 // If the newly generated derived pointer's type does not match the original derived
1157 // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
1158 Value *ActualReplacement = Replacement;
1159 if (Replacement->getType() != ToReplace->getType()) {
1160 ActualReplacement =
1161 Builder.CreateBitCast(Replacement, ToReplace->getType());
1162 }
1163 ToReplace->replaceAllUsesWith(ActualReplacement);
1164 ToReplace->eraseFromParent();
1165
1166 MadeChange = true;
1167 }
1168 return MadeChange;
1169}
1170
1171// Turns this:
1172//
1173// %base = ...
1174// %ptr = gep %base + 15
1175// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1176// %base' = relocate(%tok, i32 4, i32 4)
1177// %ptr' = relocate(%tok, i32 4, i32 5)
1178// %val = load %ptr'
1179//
1180// into this:
1181//
1182// %base = ...
1183// %ptr = gep %base + 15
1184// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1185// %base' = gc.relocate(%tok, i32 4, i32 4)
1186// %ptr' = gep %base' + 15
1187// %val = load %ptr'
1188bool CodeGenPrepare::simplifyOffsetableRelocate(GCStatepointInst &I) {
1189 bool MadeChange = false;
1190 SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
1191 for (auto *U : I.users())
1192 if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
1193 // Collect all the relocate calls associated with a statepoint
1194 AllRelocateCalls.push_back(Relocate);
1195
1196 // We need at least one base pointer relocation + one derived pointer
1197 // relocation to mangle
1198 if (AllRelocateCalls.size() < 2)
1
Assuming the condition is false
2
Taking false branch
1199 return false;
1200
1201 // RelocateInstMap is a mapping from the base relocate instruction to the
1202 // corresponding derived relocate instructions
1203 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap;
1204 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
1205 if (RelocateInstMap.empty())
3
Assuming the condition is false
4
Taking false branch
1206 return false;
1207
1208 for (auto &Item : RelocateInstMap)
1209 // Item.first is the RelocatedBase to offset against
1210 // Item.second is the vector of Targets to replace
1211 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
5
Calling 'simplifyRelocatesOffABase'
1212 return MadeChange;
1213}
1214
1215/// Sink the specified cast instruction into its user blocks.
1216static bool SinkCast(CastInst *CI) {
1217 BasicBlock *DefBB = CI->getParent();
1218
1219 /// InsertedCasts - Only insert a cast in each block once.
1220 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
1221
1222 bool MadeChange = false;
1223 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
1224 UI != E; ) {
1225 Use &TheUse = UI.getUse();
1226 Instruction *User = cast<Instruction>(*UI);
1227
1228 // Figure out which BB this cast is used in. For PHI's this is the
1229 // appropriate predecessor block.
1230 BasicBlock *UserBB = User->getParent();
1231 if (PHINode *PN = dyn_cast<PHINode>(User)) {
1232 UserBB = PN->getIncomingBlock(TheUse);
1233 }
1234
1235 // Preincrement use iterator so we don't invalidate it.
1236 ++UI;
1237
1238 // The first insertion point of a block containing an EH pad is after the
1239 // pad. If the pad is the user, we cannot sink the cast past the pad.
1240 if (User->isEHPad())
1241 continue;
1242
1243 // If the block selected to receive the cast is an EH pad that does not
1244 // allow non-PHI instructions before the terminator, we can't sink the
1245 // cast.
1246 if (UserBB->getTerminator()->isEHPad())
1247 continue;
1248
1249 // If this user is in the same block as the cast, don't change the cast.
1250 if (UserBB == DefBB) continue;
1251
1252 // If we have already inserted a cast into this block, use it.
1253 CastInst *&InsertedCast = InsertedCasts[UserBB];
1254
1255 if (!InsertedCast) {
1256 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1257 assert(InsertPt != UserBB->end())(static_cast <bool> (InsertPt != UserBB->end()) ? void
(0) : __assert_fail ("InsertPt != UserBB->end()", "llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 1257, __extension__ __PRETTY_FUNCTION__))
;
1258 InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
1259 CI->getType(), "", &*InsertPt);
1260 InsertedCast->setDebugLoc(CI->getDebugLoc());
1261 }
1262
1263 // Replace a use of the cast with a use of the new cast.
1264 TheUse = InsertedCast;
1265 MadeChange = true;
1266 ++NumCastUses;
1267 }
1268
1269 // If we removed all uses, nuke the cast.
1270 if (CI->use_empty()) {
1271 salvageDebugInfo(*CI);
1272 CI->eraseFromParent();
1273 MadeChange = true;
1274 }
1275
1276 return MadeChange;
1277}
1278
1279/// If the specified cast instruction is a noop copy (e.g. it's casting from
1280/// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
1281/// reduce the number of virtual registers that must be created and coalesced.
1282///
1283/// Return true if any changes are made.
1284static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
1285 const DataLayout &DL) {
1286 // Sink only "cheap" (or nop) address-space casts. This is a weaker condition
1287 // than sinking only nop casts, but is helpful on some platforms.
1288 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(CI)) {
1289 if (!TLI.isFreeAddrSpaceCast(ASC->getSrcAddressSpace(),
1290 ASC->getDestAddressSpace()))
1291 return false;
1292 }
1293
1294 // If this is a noop copy,
1295 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
1296 EVT DstVT = TLI.getValueType(DL, CI->getType());
1297
1298 // This is an fp<->int conversion?
1299 if (SrcVT.isInteger() != DstVT.isInteger())
1300 return false;
1301
1302 // If this is an extension, it will be a zero or sign extension, which
1303 // isn't a noop.
1304 if (SrcVT.bitsLT(DstVT)) return false;
1305
1306 // If these values will be promoted, find out what they will be promoted
1307 // to. This helps us consider truncates on PPC as noop copies when they
1308 // are.
1309 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
1310 TargetLowering::TypePromoteInteger)
1311 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
1312 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
1313 TargetLowering::TypePromoteInteger)
1314 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
1315
1316 // If, after promotion, these are the same types, this is a noop copy.
1317 if (SrcVT != DstVT)
1318 return false;
1319
1320 return SinkCast(CI);
1321}
1322
1323// Match a simple increment by constant operation. Note that if a sub is
1324// matched, the step is negated (as if the step had been canonicalized to
1325// an add, even though we leave the instruction alone.)
1326bool matchIncrement(const Instruction* IVInc, Instruction *&LHS,
1327 Constant *&Step) {
1328 if (match(IVInc, m_Add(m_Instruction(LHS), m_Constant(Step))) ||
1329 match(IVInc, m_ExtractValue<0>(m_Intrinsic<Intrinsic::uadd_with_overflow>(
1330 m_Instruction(LHS), m_Constant(Step)))))
1331 return true;
1332 if (match(IVInc, m_Sub(m_Instruction(LHS), m_Constant(Step))) ||
1333 match(IVInc, m_ExtractValue<0>(m_Intrinsic<Intrinsic::usub_with_overflow>(
1334 m_Instruction(LHS), m_Constant(Step))))) {
1335 Step = ConstantExpr::getNeg(Step);
1336 return true;
1337 }
1338 return false;
1339}
1340
1341/// If given \p PN is an inductive variable with value IVInc coming from the
1342/// backedge, and on each iteration it gets increased by Step, return pair
1343/// <IVInc, Step>. Otherwise, return None.
1344static Optional<std::pair<Instruction *, Constant *> >
1345getIVIncrement(const PHINode *PN, const LoopInfo *LI) {
1346 const Loop *L = LI->getLoopFor(PN->getParent());
1347 if (!L || L->getHeader() != PN->getParent() || !L->getLoopLatch())
1348 return None;
1349 auto *IVInc =
1350 dyn_cast<Instruction>(PN->getIncomingValueForBlock(L->getLoopLatch()));
1351 if (!IVInc || LI->getLoopFor(IVInc->getParent()) != L)
1352 return None;
1353 Instruction *LHS = nullptr;
1354 Constant *Step = nullptr;
1355 if (matchIncrement(IVInc, LHS, Step) && LHS == PN)
1356 return std::make_pair(IVInc, Step);
1357 return None;
1358}
1359
1360static bool isIVIncrement(const Value *V, const LoopInfo *LI) {
1361 auto *I = dyn_cast<Instruction>(V);
1362 if (!I)
1363 return false;
1364 Instruction *LHS = nullptr;
1365 Constant *Step = nullptr;
1366 if (!matchIncrement(I, LHS, Step))
1367 return false;
1368 if (auto *PN = dyn_cast<PHINode>(LHS))
1369 if (auto IVInc = getIVIncrement(PN, LI))
1370 return IVInc->first == I;
1371 return false;
1372}
1373
1374bool CodeGenPrepare::replaceMathCmpWithIntrinsic(BinaryOperator *BO,
1375 Value *Arg0, Value *Arg1,
1376 CmpInst *Cmp,
1377 Intrinsic::ID IID) {
1378 auto IsReplacableIVIncrement = [this, &Cmp](BinaryOperator *BO) {
1379 if (!isIVIncrement(BO, LI))
1380 return false;
1381 const Loop *L = LI->getLoopFor(BO->getParent());
1382 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", 1382, __extension__ __PRETTY_FUNCTION__
))
;
1383 // Do not risk on moving increment into a child loop.
1384 if (LI->getLoopFor(Cmp->getParent()) != L)
1385 return false;
1386
1387 // Finally, we need to ensure that the insert point will dominate all
1388 // existing uses of the increment.
1389
1390 auto &DT = getDT(*BO->getParent()->getParent());
1391 if (DT.dominates(Cmp->getParent(), BO->getParent()))
1392 // If we're moving up the dom tree, all uses are trivially dominated.
1393 // (This is the common case for code produced by LSR.)
1394 return true;
1395
1396 // Otherwise, special case the single use in the phi recurrence.
1397 return BO->hasOneUse() && DT.dominates(Cmp->getParent(), L->getLoopLatch());
1398 };
1399 if (BO->getParent() != Cmp->getParent() && !IsReplacableIVIncrement(BO)) {
1400 // We used to use a dominator tree here to allow multi-block optimization.
1401 // But that was problematic because:
1402 // 1. It could cause a perf regression by hoisting the math op into the
1403 // critical path.
1404 // 2. It could cause a perf regression by creating a value that was live
1405 // across multiple blocks and increasing register pressure.
1406 // 3. Use of a dominator tree could cause large compile-time regression.
1407 // This is because we recompute the DT on every change in the main CGP
1408 // run-loop. The recomputing is probably unnecessary in many cases, so if
1409 // that was fixed, using a DT here would be ok.
1410 //
1411 // There is one important particular case we still want to handle: if BO is
1412 // the IV increment. Important properties that make it profitable:
1413 // - We can speculate IV increment anywhere in the loop (as long as the
1414 // indvar Phi is its only user);
1415 // - Upon computing Cmp, we effectively compute something equivalent to the
1416 // IV increment (despite it loops differently in the IR). So moving it up
1417 // to the cmp point does not really increase register pressure.
1418 return false;
1419 }
1420
1421 // We allow matching the canonical IR (add X, C) back to (usubo X, -C).
1422 if (BO->getOpcode() == Instruction::Add &&
1423 IID == Intrinsic::usub_with_overflow) {
1424 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", 1424, __extension__ __PRETTY_FUNCTION__
))
;
1425 Arg1 = ConstantExpr::getNeg(cast<Constant>(Arg1));
1426 }
1427
1428 // Insert at the first instruction of the pair.
1429 Instruction *InsertPt = nullptr;
1430 for (Instruction &Iter : *Cmp->getParent()) {
1431 // If BO is an XOR, it is not guaranteed that it comes after both inputs to
1432 // the overflow intrinsic are defined.
1433 if ((BO->getOpcode() != Instruction::Xor && &Iter == BO) || &Iter == Cmp) {
1434 InsertPt = &Iter;
1435 break;
1436 }
1437 }
1438 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", 1438, __extension__ __PRETTY_FUNCTION__
))
;
1439
1440 IRBuilder<> Builder(InsertPt);
1441 Value *MathOV = Builder.CreateBinaryIntrinsic(IID, Arg0, Arg1);
1442 if (BO->getOpcode() != Instruction::Xor) {
1443 Value *Math = Builder.CreateExtractValue(MathOV, 0, "math");
1444 BO->replaceAllUsesWith(Math);
1445 } else
1446 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", 1447, __extension__ __PRETTY_FUNCTION__
))
1447 "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", 1447, __extension__ __PRETTY_FUNCTION__
))
;
1448 Value *OV = Builder.CreateExtractValue(MathOV, 1, "ov");
1449 Cmp->replaceAllUsesWith(OV);
1450 Cmp->eraseFromParent();
1451 BO->eraseFromParent();
1452 return true;
1453}
1454
1455/// Match special-case patterns that check for unsigned add overflow.
1456static bool matchUAddWithOverflowConstantEdgeCases(CmpInst *Cmp,
1457 BinaryOperator *&Add) {
1458 // Add = add A, 1; Cmp = icmp eq A,-1 (overflow if A is max val)
1459 // Add = add A,-1; Cmp = icmp ne A, 0 (overflow if A is non-zero)
1460 Value *A = Cmp->getOperand(0), *B = Cmp->getOperand(1);
1461
1462 // We are not expecting non-canonical/degenerate code. Just bail out.
1463 if (isa<Constant>(A))
1464 return false;
1465
1466 ICmpInst::Predicate Pred = Cmp->getPredicate();
1467 if (Pred == ICmpInst::ICMP_EQ && match(B, m_AllOnes()))
1468 B = ConstantInt::get(B->getType(), 1);
1469 else if (Pred == ICmpInst::ICMP_NE && match(B, m_ZeroInt()))
1470 B = ConstantInt::get(B->getType(), -1);
1471 else
1472 return false;
1473
1474 // Check the users of the variable operand of the compare looking for an add
1475 // with the adjusted constant.
1476 for (User *U : A->users()) {
1477 if (match(U, m_Add(m_Specific(A), m_Specific(B)))) {
1478 Add = cast<BinaryOperator>(U);
1479 return true;
1480 }
1481 }
1482 return false;
1483}
1484
1485/// Try to combine the compare into a call to the llvm.uadd.with.overflow
1486/// intrinsic. Return true if any changes were made.
1487bool CodeGenPrepare::combineToUAddWithOverflow(CmpInst *Cmp,
1488 bool &ModifiedDT) {
1489 Value *A, *B;
1490 BinaryOperator *Add;
1491 if (!match(Cmp, m_UAddWithOverflow(m_Value(A), m_Value(B), m_BinOp(Add)))) {
1492 if (!matchUAddWithOverflowConstantEdgeCases(Cmp, Add))
1493 return false;
1494 // Set A and B in case we match matchUAddWithOverflowConstantEdgeCases.
1495 A = Add->getOperand(0);
1496 B = Add->getOperand(1);
1497 }
1498
1499 if (!TLI->shouldFormOverflowOp(ISD::UADDO,
1500 TLI->getValueType(*DL, Add->getType()),
1501 Add->hasNUsesOrMore(2)))
1502 return false;
1503
1504 // We don't want to move around uses of condition values this late, so we
1505 // check if it is legal to create the call to the intrinsic in the basic
1506 // block containing the icmp.
1507 if (Add->getParent() != Cmp->getParent() && !Add->hasOneUse())
1508 return false;
1509
1510 if (!replaceMathCmpWithIntrinsic(Add, A, B, Cmp,
1511 Intrinsic::uadd_with_overflow))
1512 return false;
1513
1514 // Reset callers - do not crash by iterating over a dead instruction.
1515 ModifiedDT = true;
1516 return true;
1517}
1518
1519bool CodeGenPrepare::combineToUSubWithOverflow(CmpInst *Cmp,
1520 bool &ModifiedDT) {
1521 // We are not expecting non-canonical/degenerate code. Just bail out.
1522 Value *A = Cmp->getOperand(0), *B = Cmp->getOperand(1);
1523 if (isa<Constant>(A) && isa<Constant>(B))
1524 return false;
1525
1526 // Convert (A u> B) to (A u< B) to simplify pattern matching.
1527 ICmpInst::Predicate Pred = Cmp->getPredicate();
1528 if (Pred == ICmpInst::ICMP_UGT) {
1529 std::swap(A, B);
1530 Pred = ICmpInst::ICMP_ULT;
1531 }
1532 // Convert special-case: (A == 0) is the same as (A u< 1).
1533 if (Pred == ICmpInst::ICMP_EQ && match(B, m_ZeroInt())) {
1534 B = ConstantInt::get(B->getType(), 1);
1535 Pred = ICmpInst::ICMP_ULT;
1536 }
1537 // Convert special-case: (A != 0) is the same as (0 u< A).
1538 if (Pred == ICmpInst::ICMP_NE && match(B, m_ZeroInt())) {
1539 std::swap(A, B);
1540 Pred = ICmpInst::ICMP_ULT;
1541 }
1542 if (Pred != ICmpInst::ICMP_ULT)
1543 return false;
1544
1545 // Walk the users of a variable operand of a compare looking for a subtract or
1546 // add with that same operand. Also match the 2nd operand of the compare to
1547 // the add/sub, but that may be a negated constant operand of an add.
1548 Value *CmpVariableOperand = isa<Constant>(A) ? B : A;
1549 BinaryOperator *Sub = nullptr;
1550 for (User *U : CmpVariableOperand->users()) {
1551 // A - B, A u< B --> usubo(A, B)
1552 if (match(U, m_Sub(m_Specific(A), m_Specific(B)))) {
1553 Sub = cast<BinaryOperator>(U);
1554 break;
1555 }
1556
1557 // A + (-C), A u< C (canonicalized form of (sub A, C))
1558 const APInt *CmpC, *AddC;
1559 if (match(U, m_Add(m_Specific(A), m_APInt(AddC))) &&
1560 match(B, m_APInt(CmpC)) && *AddC == -(*CmpC)) {
1561 Sub = cast<BinaryOperator>(U);
1562 break;
1563 }
1564 }
1565 if (!Sub)
1566 return false;
1567
1568 if (!TLI->shouldFormOverflowOp(ISD::USUBO,
1569 TLI->getValueType(*DL, Sub->getType()),
1570 Sub->hasNUsesOrMore(2)))
1571 return false;
1572
1573 if (!replaceMathCmpWithIntrinsic(Sub, Sub->getOperand(0), Sub->getOperand(1),
1574 Cmp, Intrinsic::usub_with_overflow))
1575 return false;
1576
1577 // Reset callers - do not crash by iterating over a dead instruction.
1578 ModifiedDT = true;
1579 return true;
1580}
1581
1582/// Sink the given CmpInst into user blocks to reduce the number of virtual
1583/// registers that must be created and coalesced. This is a clear win except on
1584/// targets with multiple condition code registers (PowerPC), where it might
1585/// lose; some adjustment may be wanted there.
1586///
1587/// Return true if any changes are made.
1588static bool sinkCmpExpression(CmpInst *Cmp, const TargetLowering &TLI) {
1589 if (TLI.hasMultipleConditionRegisters())
1590 return false;
1591
1592 // Avoid sinking soft-FP comparisons, since this can move them into a loop.
1593 if (TLI.useSoftFloat() && isa<FCmpInst>(Cmp))
1594 return false;
1595
1596 // Only insert a cmp in each block once.
1597 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
1598
1599 bool MadeChange = false;
1600 for (Value::user_iterator UI = Cmp->user_begin(), E = Cmp->user_end();
1601 UI != E; ) {
1602 Use &TheUse = UI.getUse();
1603 Instruction *User = cast<Instruction>(*UI);
1604
1605 // Preincrement use iterator so we don't invalidate it.
1606 ++UI;
1607
1608 // Don't bother for PHI nodes.
1609 if (isa<PHINode>(User))
1610 continue;
1611
1612 // Figure out which BB this cmp is used in.
1613 BasicBlock *UserBB = User->getParent();
1614 BasicBlock *DefBB = Cmp->getParent();
1615
1616 // If this user is in the same block as the cmp, don't change the cmp.
1617 if (UserBB == DefBB) continue;
1618
1619 // If we have already inserted a cmp into this block, use it.
1620 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
1621
1622 if (!InsertedCmp) {
1623 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1624 assert(InsertPt != UserBB->end())(static_cast <bool> (InsertPt != UserBB->end()) ? void
(0) : __assert_fail ("InsertPt != UserBB->end()", "llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 1624, __extension__ __PRETTY_FUNCTION__))
;
1625 InsertedCmp =
1626 CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(),
1627 Cmp->getOperand(0), Cmp->getOperand(1), "",
1628 &*InsertPt);
1629 // Propagate the debug info.
1630 InsertedCmp->setDebugLoc(Cmp->getDebugLoc());
1631 }
1632
1633 // Replace a use of the cmp with a use of the new cmp.
1634 TheUse = InsertedCmp;
1635 MadeChange = true;
1636 ++NumCmpUses;
1637 }
1638
1639 // If we removed all uses, nuke the cmp.
1640 if (Cmp->use_empty()) {
1641 Cmp->eraseFromParent();
1642 MadeChange = true;
1643 }
1644
1645 return MadeChange;
1646}
1647
1648/// For pattern like:
1649///
1650/// DomCond = icmp sgt/slt CmpOp0, CmpOp1 (might not be in DomBB)
1651/// ...
1652/// DomBB:
1653/// ...
1654/// br DomCond, TrueBB, CmpBB
1655/// CmpBB: (with DomBB being the single predecessor)
1656/// ...
1657/// Cmp = icmp eq CmpOp0, CmpOp1
1658/// ...
1659///
1660/// It would use two comparison on targets that lowering of icmp sgt/slt is
1661/// different from lowering of icmp eq (PowerPC). This function try to convert
1662/// 'Cmp = icmp eq CmpOp0, CmpOp1' to ' Cmp = icmp slt/sgt CmpOp0, CmpOp1'.
1663/// After that, DomCond and Cmp can use the same comparison so reduce one
1664/// comparison.
1665///
1666/// Return true if any changes are made.
1667static bool foldICmpWithDominatingICmp(CmpInst *Cmp,
1668 const TargetLowering &TLI) {
1669 if (!EnableICMP_EQToICMP_ST && TLI.isEqualityCmpFoldedWithSignedCmp())
1670 return false;
1671
1672 ICmpInst::Predicate Pred = Cmp->getPredicate();
1673 if (Pred != ICmpInst::ICMP_EQ)
1674 return false;
1675
1676 // If icmp eq has users other than BranchInst and SelectInst, converting it to
1677 // icmp slt/sgt would introduce more redundant LLVM IR.
1678 for (User *U : Cmp->users()) {
1679 if (isa<BranchInst>(U))
1680 continue;
1681 if (isa<SelectInst>(U) && cast<SelectInst>(U)->getCondition() == Cmp)
1682 continue;
1683 return false;
1684 }
1685
1686 // This is a cheap/incomplete check for dominance - just match a single
1687 // predecessor with a conditional branch.
1688 BasicBlock *CmpBB = Cmp->getParent();
1689 BasicBlock *DomBB = CmpBB->getSinglePredecessor();
1690 if (!DomBB)
1691 return false;
1692
1693 // We want to ensure that the only way control gets to the comparison of
1694 // interest is that a less/greater than comparison on the same operands is
1695 // false.
1696 Value *DomCond;
1697 BasicBlock *TrueBB, *FalseBB;
1698 if (!match(DomBB->getTerminator(), m_Br(m_Value(DomCond), TrueBB, FalseBB)))
1699 return false;
1700 if (CmpBB != FalseBB)
1701 return false;
1702
1703 Value *CmpOp0 = Cmp->getOperand(0), *CmpOp1 = Cmp->getOperand(1);
1704 ICmpInst::Predicate DomPred;
1705 if (!match(DomCond, m_ICmp(DomPred, m_Specific(CmpOp0), m_Specific(CmpOp1))))
1706 return false;
1707 if (DomPred != ICmpInst::ICMP_SGT && DomPred != ICmpInst::ICMP_SLT)
1708 return false;
1709
1710 // Convert the equality comparison to the opposite of the dominating
1711 // comparison and swap the direction for all branch/select users.
1712 // We have conceptually converted:
1713 // Res = (a < b) ? <LT_RES> : (a == b) ? <EQ_RES> : <GT_RES>;
1714 // to
1715 // Res = (a < b) ? <LT_RES> : (a > b) ? <GT_RES> : <EQ_RES>;
1716 // And similarly for branches.
1717 for (User *U : Cmp->users()) {
1718 if (auto *BI = dyn_cast<BranchInst>(U)) {
1719 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", 1719, __extension__ __PRETTY_FUNCTION__
))
;
1720 BI->swapSuccessors();
1721 continue;
1722 }
1723 if (auto *SI = dyn_cast<SelectInst>(U)) {
1724 // Swap operands
1725 SI->swapValues();
1726 SI->swapProfMetadata();
1727 continue;
1728 }
1729 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", 1729)
;
1730 }
1731 Cmp->setPredicate(CmpInst::getSwappedPredicate(DomPred));
1732 return true;
1733}
1734
1735bool CodeGenPrepare::optimizeCmp(CmpInst *Cmp, bool &ModifiedDT) {
1736 if (sinkCmpExpression(Cmp, *TLI))
1737 return true;
1738
1739 if (combineToUAddWithOverflow(Cmp, ModifiedDT))
1740 return true;
1741
1742 if (combineToUSubWithOverflow(Cmp, ModifiedDT))
1743 return true;
1744
1745 if (foldICmpWithDominatingICmp(Cmp, *TLI))
1746 return true;
1747
1748 return false;
1749}
1750
1751/// Duplicate and sink the given 'and' instruction into user blocks where it is
1752/// used in a compare to allow isel to generate better code for targets where
1753/// this operation can be combined.
1754///
1755/// Return true if any changes are made.
1756static bool sinkAndCmp0Expression(Instruction *AndI,
1757 const TargetLowering &TLI,
1758 SetOfInstrs &InsertedInsts) {
1759 // Double-check that we're not trying to optimize an instruction that was
1760 // already optimized by some other part of this pass.
1761 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", 1762, __extension__ __PRETTY_FUNCTION__
))
1762 "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", 1762, __extension__ __PRETTY_FUNCTION__
))
;
1763 (void) InsertedInsts;
1764
1765 // Nothing to do for single use in same basic block.
1766 if (AndI->hasOneUse() &&
1767 AndI->getParent() == cast<Instruction>(*AndI->user_begin())->getParent())
1768 return false;
1769
1770 // Try to avoid cases where sinking/duplicating is likely to increase register
1771 // pressure.
1772 if (!isa<ConstantInt>(AndI->getOperand(0)) &&
1773 !isa<ConstantInt>(AndI->getOperand(1)) &&
1774 AndI->getOperand(0)->hasOneUse() && AndI->getOperand(1)->hasOneUse())
1775 return false;
1776
1777 for (auto *U : AndI->users()) {
1778 Instruction *User = cast<Instruction>(U);
1779
1780 // Only sink 'and' feeding icmp with 0.
1781 if (!isa<ICmpInst>(User))
1782 return false;
1783
1784 auto *CmpC = dyn_cast<ConstantInt>(User->getOperand(1));
1785 if (!CmpC || !CmpC->isZero())
1786 return false;
1787 }
1788
1789 if (!TLI.isMaskAndCmp0FoldingBeneficial(*AndI))
1790 return false;
1791
1792 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)
;
1793 LLVM_DEBUG(AndI->getParent()->dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { AndI->getParent()->dump(); } } while
(false)
;
1794
1795 // Push the 'and' into the same block as the icmp 0. There should only be
1796 // one (icmp (and, 0)) in each block, since CSE/GVN should have removed any
1797 // others, so we don't need to keep track of which BBs we insert into.
1798 for (Value::user_iterator UI = AndI->user_begin(), E = AndI->user_end();
1799 UI != E; ) {
1800 Use &TheUse = UI.getUse();
1801 Instruction *User = cast<Instruction>(*UI);
1802
1803 // Preincrement use iterator so we don't invalidate it.
1804 ++UI;
1805
1806 LLVM_DEBUG(dbgs() << "sinking 'and' use: " << *User << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "sinking 'and' use: " <<
*User << "\n"; } } while (false)
;
1807
1808 // Keep the 'and' in the same place if the use is already in the same block.
1809 Instruction *InsertPt =
1810 User->getParent() == AndI->getParent() ? AndI : User;
1811 Instruction *InsertedAnd =
1812 BinaryOperator::Create(Instruction::And, AndI->getOperand(0),
1813 AndI->getOperand(1), "", InsertPt);
1814 // Propagate the debug info.
1815 InsertedAnd->setDebugLoc(AndI->getDebugLoc());
1816
1817 // Replace a use of the 'and' with a use of the new 'and'.
1818 TheUse = InsertedAnd;
1819 ++NumAndUses;
1820 LLVM_DEBUG(User->getParent()->dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { User->getParent()->dump(); } } while
(false)
;
1821 }
1822
1823 // We removed all uses, nuke the and.
1824 AndI->eraseFromParent();
1825 return true;
1826}
1827
1828/// Check if the candidates could be combined with a shift instruction, which
1829/// includes:
1830/// 1. Truncate instruction
1831/// 2. And instruction and the imm is a mask of the low bits:
1832/// imm & (imm+1) == 0
1833static bool isExtractBitsCandidateUse(Instruction *User) {
1834 if (!isa<TruncInst>(User)) {
1835 if (User->getOpcode() != Instruction::And ||
1836 !isa<ConstantInt>(User->getOperand(1)))
1837 return false;
1838
1839 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
1840
1841 if ((Cimm & (Cimm + 1)).getBoolValue())
1842 return false;
1843 }
1844 return true;
1845}
1846
1847/// Sink both shift and truncate instruction to the use of truncate's BB.
1848static bool
1849SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
1850 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
1851 const TargetLowering &TLI, const DataLayout &DL) {
1852 BasicBlock *UserBB = User->getParent();
1853 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
1854 auto *TruncI = cast<TruncInst>(User);
1855 bool MadeChange = false;
1856
1857 for (Value::user_iterator TruncUI = TruncI->user_begin(),
1858 TruncE = TruncI->user_end();
1859 TruncUI != TruncE;) {
1860
1861 Use &TruncTheUse = TruncUI.getUse();
1862 Instruction *TruncUser = cast<Instruction>(*TruncUI);
1863 // Preincrement use iterator so we don't invalidate it.
1864
1865 ++TruncUI;
1866
1867 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
1868 if (!ISDOpcode)
1869 continue;
1870
1871 // If the use is actually a legal node, there will not be an
1872 // implicit truncate.
1873 // FIXME: always querying the result type is just an
1874 // approximation; some nodes' legality is determined by the
1875 // operand or other means. There's no good way to find out though.
1876 if (TLI.isOperationLegalOrCustom(
1877 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
1878 continue;
1879
1880 // Don't bother for PHI nodes.
1881 if (isa<PHINode>(TruncUser))
1882 continue;
1883
1884 BasicBlock *TruncUserBB = TruncUser->getParent();
1885
1886 if (UserBB == TruncUserBB)
1887 continue;
1888
1889 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
1890 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
1891
1892 if (!InsertedShift && !InsertedTrunc) {
1893 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
1894 assert(InsertPt != TruncUserBB->end())(static_cast <bool> (InsertPt != TruncUserBB->end())
? void (0) : __assert_fail ("InsertPt != TruncUserBB->end()"
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 1894, __extension__ __PRETTY_FUNCTION__
))
;
1895 // Sink the shift
1896 if (ShiftI->getOpcode() == Instruction::AShr)
1897 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1898 "", &*InsertPt);
1899 else
1900 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1901 "", &*InsertPt);
1902 InsertedShift->setDebugLoc(ShiftI->getDebugLoc());
1903
1904 // Sink the trunc
1905 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
1906 TruncInsertPt++;
1907 assert(TruncInsertPt != TruncUserBB->end())(static_cast <bool> (TruncInsertPt != TruncUserBB->end
()) ? void (0) : __assert_fail ("TruncInsertPt != TruncUserBB->end()"
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 1907, __extension__ __PRETTY_FUNCTION__
))
;
1908
1909 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
1910 TruncI->getType(), "", &*TruncInsertPt);
1911 InsertedTrunc->setDebugLoc(TruncI->getDebugLoc());
1912
1913 MadeChange = true;
1914
1915 TruncTheUse = InsertedTrunc;
1916 }
1917 }
1918 return MadeChange;
1919}
1920
1921/// Sink the shift *right* instruction into user blocks if the uses could
1922/// potentially be combined with this shift instruction and generate BitExtract
1923/// instruction. It will only be applied if the architecture supports BitExtract
1924/// instruction. Here is an example:
1925/// BB1:
1926/// %x.extract.shift = lshr i64 %arg1, 32
1927/// BB2:
1928/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
1929/// ==>
1930///
1931/// BB2:
1932/// %x.extract.shift.1 = lshr i64 %arg1, 32
1933/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
1934///
1935/// CodeGen will recognize the pattern in BB2 and generate BitExtract
1936/// instruction.
1937/// Return true if any changes are made.
1938static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
1939 const TargetLowering &TLI,
1940 const DataLayout &DL) {
1941 BasicBlock *DefBB = ShiftI->getParent();
1942
1943 /// Only insert instructions in each block once.
1944 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
1945
1946 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
1947
1948 bool MadeChange = false;
1949 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
1950 UI != E;) {
1951 Use &TheUse = UI.getUse();
1952 Instruction *User = cast<Instruction>(*UI);
1953 // Preincrement use iterator so we don't invalidate it.
1954 ++UI;
1955
1956 // Don't bother for PHI nodes.
1957 if (isa<PHINode>(User))
1958 continue;
1959
1960 if (!isExtractBitsCandidateUse(User))
1961 continue;
1962
1963 BasicBlock *UserBB = User->getParent();
1964
1965 if (UserBB == DefBB) {
1966 // If the shift and truncate instruction are in the same BB. The use of
1967 // the truncate(TruncUse) may still introduce another truncate if not
1968 // legal. In this case, we would like to sink both shift and truncate
1969 // instruction to the BB of TruncUse.
1970 // for example:
1971 // BB1:
1972 // i64 shift.result = lshr i64 opnd, imm
1973 // trunc.result = trunc shift.result to i16
1974 //
1975 // BB2:
1976 // ----> We will have an implicit truncate here if the architecture does
1977 // not have i16 compare.
1978 // cmp i16 trunc.result, opnd2
1979 //
1980 if (isa<TruncInst>(User) && shiftIsLegal
1981 // If the type of the truncate is legal, no truncate will be
1982 // introduced in other basic blocks.
1983 &&
1984 (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
1985 MadeChange =
1986 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
1987
1988 continue;
1989 }
1990 // If we have already inserted a shift into this block, use it.
1991 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
1992
1993 if (!InsertedShift) {
1994 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1995 assert(InsertPt != UserBB->end())(static_cast <bool> (InsertPt != UserBB->end()) ? void
(0) : __assert_fail ("InsertPt != UserBB->end()", "llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 1995, __extension__ __PRETTY_FUNCTION__))
;
1996
1997 if (ShiftI->getOpcode() == Instruction::AShr)
1998 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1999 "", &*InsertPt);
2000 else
2001 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
2002 "", &*InsertPt);
2003 InsertedShift->setDebugLoc(ShiftI->getDebugLoc());
2004
2005 MadeChange = true;
2006 }
2007
2008 // Replace a use of the shift with a use of the new shift.
2009 TheUse = InsertedShift;
2010 }
2011
2012 // If we removed all uses, or there are none, nuke the shift.
2013 if (ShiftI->use_empty()) {
2014 salvageDebugInfo(*ShiftI);
2015 ShiftI->eraseFromParent();
2016 MadeChange = true;
2017 }
2018
2019 return MadeChange;
2020}
2021
2022/// If counting leading or trailing zeros is an expensive operation and a zero
2023/// input is defined, add a check for zero to avoid calling the intrinsic.
2024///
2025/// We want to transform:
2026/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
2027///
2028/// into:
2029/// entry:
2030/// %cmpz = icmp eq i64 %A, 0
2031/// br i1 %cmpz, label %cond.end, label %cond.false
2032/// cond.false:
2033/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
2034/// br label %cond.end
2035/// cond.end:
2036/// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
2037///
2038/// If the transform is performed, return true and set ModifiedDT to true.
2039static bool despeculateCountZeros(IntrinsicInst *CountZeros,
2040 const TargetLowering *TLI,
2041 const DataLayout *DL,
2042 bool &ModifiedDT) {
2043 // If a zero input is undefined, it doesn't make sense to despeculate that.
2044 if (match(CountZeros->getOperand(1), m_One()))
2045 return false;
2046
2047 // If it's cheap to speculate, there's nothing to do.
2048 Type *Ty = CountZeros->getType();
2049 auto IntrinsicID = CountZeros->getIntrinsicID();
2050 if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz(Ty)) ||
2051 (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz(Ty)))
2052 return false;
2053
2054 // Only handle legal scalar cases. Anything else requires too much work.
2055 unsigned SizeInBits = Ty->getScalarSizeInBits();
2056 if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSizeInBits())
2057 return false;
2058
2059 // Bail if the value is never zero.
2060 Use &Op = CountZeros->getOperandUse(0);
2061 if (isKnownNonZero(Op, *DL))
2062 return false;
2063
2064 // The intrinsic will be sunk behind a compare against zero and branch.
2065 BasicBlock *StartBlock = CountZeros->getParent();
2066 BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
2067
2068 // Create another block after the count zero intrinsic. A PHI will be added
2069 // in this block to select the result of the intrinsic or the bit-width
2070 // constant if the input to the intrinsic is zero.
2071 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
2072 BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
2073
2074 // Set up a builder to create a compare, conditional branch, and PHI.
2075 IRBuilder<> Builder(CountZeros->getContext());
2076 Builder.SetInsertPoint(StartBlock->getTerminator());
2077 Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
2078
2079 // Replace the unconditional branch that was created by the first split with
2080 // a compare against zero and a conditional branch.
2081 Value *Zero = Constant::getNullValue(Ty);
2082 // Avoid introducing branch on poison. This also replaces the ctz operand.
2083 if (!isGuaranteedNotToBeUndefOrPoison(Op))
2084 Op = Builder.CreateFreeze(Op, Op->getName() + ".fr");
2085 Value *Cmp = Builder.CreateICmpEQ(Op, Zero, "cmpz");
2086 Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
2087 StartBlock->getTerminator()->eraseFromParent();
2088
2089 // Create a PHI in the end block to select either the output of the intrinsic
2090 // or the bit width of the operand.
2091 Builder.SetInsertPoint(&EndBlock->front());
2092 PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
2093 CountZeros->replaceAllUsesWith(PN);
2094 Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
2095 PN->addIncoming(BitWidth, StartBlock);
2096 PN->addIncoming(CountZeros, CallBlock);
2097
2098 // We are explicitly handling the zero case, so we can set the intrinsic's
2099 // undefined zero argument to 'true'. This will also prevent reprocessing the
2100 // intrinsic; we only despeculate when a zero input is defined.
2101 CountZeros->setArgOperand(1, Builder.getTrue());
2102 ModifiedDT = true;
2103 return true;
2104}
2105
2106bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool &ModifiedDT) {
2107 BasicBlock *BB = CI->getParent();
2108
2109 // Lower inline assembly if we can.
2110 // If we found an inline asm expession, and if the target knows how to
2111 // lower it to normal LLVM code, do so now.
2112 if (CI->isInlineAsm()) {
2113 if (TLI->ExpandInlineAsm(CI)) {
2114 // Avoid invalidating the iterator.
2115 CurInstIterator = BB->begin();
2116 // Avoid processing instructions out of order, which could cause
2117 // reuse before a value is defined.
2118 SunkAddrs.clear();
2119 return true;
2120 }
2121 // Sink address computing for memory operands into the block.
2122 if (optimizeInlineAsmInst(CI))
2123 return true;
2124 }
2125
2126 // Align the pointer arguments to this call if the target thinks it's a good
2127 // idea
2128 unsigned MinSize;
2129 Align PrefAlign;
2130 if (TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
2131 for (auto &Arg : CI->args()) {
2132 // We want to align both objects whose address is used directly and
2133 // objects whose address is used in casts and GEPs, though it only makes
2134 // sense for GEPs if the offset is a multiple of the desired alignment and
2135 // if size - offset meets the size threshold.
2136 if (!Arg->getType()->isPointerTy())
2137 continue;
2138 APInt Offset(DL->getIndexSizeInBits(
2139 cast<PointerType>(Arg->getType())->getAddressSpace()),
2140 0);
2141 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
2142 uint64_t Offset2 = Offset.getLimitedValue();
2143 if (!isAligned(PrefAlign, Offset2))
2144 continue;
2145 AllocaInst *AI;
2146 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlign() < PrefAlign &&
2147 DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
2148 AI->setAlignment(PrefAlign);
2149 // Global variables can only be aligned if they are defined in this
2150 // object (i.e. they are uniquely initialized in this object), and
2151 // over-aligning global variables that have an explicit section is
2152 // forbidden.
2153 GlobalVariable *GV;
2154 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
2155 GV->getPointerAlignment(*DL) < PrefAlign &&
2156 DL->getTypeAllocSize(GV->getValueType()) >=
2157 MinSize + Offset2)
2158 GV->setAlignment(PrefAlign);
2159 }
2160 // If this is a memcpy (or similar) then we may be able to improve the
2161 // alignment
2162 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
2163 Align DestAlign = getKnownAlignment(MI->getDest(), *DL);
2164 MaybeAlign MIDestAlign = MI->getDestAlign();
2165 if (!MIDestAlign || DestAlign > *MIDestAlign)
2166 MI->setDestAlignment(DestAlign);
2167 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
2168 MaybeAlign MTISrcAlign = MTI->getSourceAlign();
2169 Align SrcAlign = getKnownAlignment(MTI->getSource(), *DL);
2170 if (!MTISrcAlign || SrcAlign > *MTISrcAlign)
2171 MTI->setSourceAlignment(SrcAlign);
2172 }
2173 }
2174 }
2175
2176 // If we have a cold call site, try to sink addressing computation into the
2177 // cold block. This interacts with our handling for loads and stores to
2178 // ensure that we can fold all uses of a potential addressing computation
2179 // into their uses. TODO: generalize this to work over profiling data
2180 if (CI->hasFnAttr(Attribute::Cold) &&
2181 !OptSize && !llvm::shouldOptimizeForSize(BB, PSI, BFI.get()))
2182 for (auto &Arg : CI->args()) {
2183 if (!Arg->getType()->isPointerTy())
2184 continue;
2185 unsigned AS = Arg->getType()->getPointerAddressSpace();
2186 return optimizeMemoryInst(CI, Arg, Arg->getType(), AS);
2187 }
2188
2189 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
2190 if (II) {
2191 switch (II->getIntrinsicID()) {
2192 default: break;
2193 case Intrinsic::assume:
2194 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", 2194)
;
2195 case Intrinsic::experimental_widenable_condition: {
2196 // Give up on future widening oppurtunties so that we can fold away dead
2197 // paths and merge blocks before going into block-local instruction
2198 // selection.
2199 if (II->use_empty()) {
2200 II->eraseFromParent();
2201 return true;
2202 }
2203 Constant *RetVal = ConstantInt::getTrue(II->getContext());
2204 resetIteratorIfInvalidatedWhileCalling(BB, [&]() {
2205 replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
2206 });
2207 return true;
2208 }
2209 case Intrinsic::objectsize:
2210 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", 2210)
;
2211 case Intrinsic::is_constant:
2212 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", 2212)
;
2213 case Intrinsic::aarch64_stlxr:
2214 case Intrinsic::aarch64_stxr: {
2215 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
2216 if (!ExtVal || !ExtVal->hasOneUse() ||
2217 ExtVal->getParent() == CI->getParent())
2218 return false;
2219 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
2220 ExtVal->moveBefore(CI);
2221 // Mark this instruction as "inserted by CGP", so that other
2222 // optimizations don't touch it.
2223 InsertedInsts.insert(ExtVal);
2224 return true;
2225 }
2226
2227 case Intrinsic::launder_invariant_group:
2228 case Intrinsic::strip_invariant_group: {
2229 Value *ArgVal = II->getArgOperand(0);
2230 auto it = LargeOffsetGEPMap.find(II);
2231 if (it != LargeOffsetGEPMap.end()) {
2232 // Merge entries in LargeOffsetGEPMap to reflect the RAUW.
2233 // Make sure not to have to deal with iterator invalidation
2234 // after possibly adding ArgVal to LargeOffsetGEPMap.
2235 auto GEPs = std::move(it->second);
2236 LargeOffsetGEPMap[ArgVal].append(GEPs.begin(), GEPs.end());
2237 LargeOffsetGEPMap.erase(II);
2238 }
2239
2240 II->replaceAllUsesWith(ArgVal);
2241 II->eraseFromParent();
2242 return true;
2243 }
2244 case Intrinsic::cttz:
2245 case Intrinsic::ctlz:
2246 // If counting zeros is expensive, try to avoid it.
2247 return despeculateCountZeros(II, TLI, DL, ModifiedDT);
2248 case Intrinsic::fshl:
2249 case Intrinsic::fshr:
2250 return optimizeFunnelShift(II);
2251 case Intrinsic::dbg_value:
2252 return fixupDbgValue(II);
2253 case Intrinsic::vscale: {
2254 // If datalayout has no special restrictions on vector data layout,
2255 // replace `llvm.vscale` by an equivalent constant expression
2256 // to benefit from cheap constant propagation.
2257 Type *ScalableVectorTy =
2258 VectorType::get(Type::getInt8Ty(II->getContext()), 1, true);
2259 if (DL->getTypeAllocSize(ScalableVectorTy).getKnownMinSize() == 8) {
2260 auto *Null = Constant::getNullValue(ScalableVectorTy->getPointerTo());
2261 auto *One = ConstantInt::getSigned(II->getType(), 1);
2262 auto *CGep =
2263 ConstantExpr::getGetElementPtr(ScalableVectorTy, Null, One);
2264 II->replaceAllUsesWith(ConstantExpr::getPtrToInt(CGep, II->getType()));
2265 II->eraseFromParent();
2266 return true;
2267 }
2268 break;
2269 }
2270 case Intrinsic::masked_gather:
2271 return optimizeGatherScatterInst(II, II->getArgOperand(0));
2272 case Intrinsic::masked_scatter:
2273 return optimizeGatherScatterInst(II, II->getArgOperand(1));
2274 }
2275
2276 SmallVector<Value *, 2> PtrOps;
2277 Type *AccessTy;
2278 if (TLI->getAddrModeArguments(II, PtrOps, AccessTy))
2279 while (!PtrOps.empty()) {
2280 Value *PtrVal = PtrOps.pop_back_val();
2281 unsigned AS = PtrVal->getType()->getPointerAddressSpace();
2282 if (optimizeMemoryInst(II, PtrVal, AccessTy, AS))
2283 return true;
2284 }
2285 }
2286
2287 // From here on out we're working with named functions.
2288 if (!CI->getCalledFunction()) return false;
2289
2290 // Lower all default uses of _chk calls. This is very similar
2291 // to what InstCombineCalls does, but here we are only lowering calls
2292 // to fortified library functions (e.g. __memcpy_chk) that have the default
2293 // "don't know" as the objectsize. Anything else should be left alone.
2294 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
2295 IRBuilder<> Builder(CI);
2296 if (Value *V = Simplifier.optimizeCall(CI, Builder)) {
2297 CI->replaceAllUsesWith(V);
2298 CI->eraseFromParent();
2299 return true;
2300 }
2301
2302 return false;
2303}
2304
2305/// Look for opportunities to duplicate return instructions to the predecessor
2306/// to enable tail call optimizations. The case it is currently looking for is:
2307/// @code
2308/// bb0:
2309/// %tmp0 = tail call i32 @f0()
2310/// br label %return
2311/// bb1:
2312/// %tmp1 = tail call i32 @f1()
2313/// br label %return
2314/// bb2:
2315/// %tmp2 = tail call i32 @f2()
2316/// br label %return
2317/// return:
2318/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
2319/// ret i32 %retval
2320/// @endcode
2321///
2322/// =>
2323///
2324/// @code
2325/// bb0:
2326/// %tmp0 = tail call i32 @f0()
2327/// ret i32 %tmp0
2328/// bb1:
2329/// %tmp1 = tail call i32 @f1()
2330/// ret i32 %tmp1
2331/// bb2:
2332/// %tmp2 = tail call i32 @f2()
2333/// ret i32 %tmp2
2334/// @endcode
2335bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB, bool &ModifiedDT) {
2336 ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator());
2337 if (!RetI)
2338 return false;
2339
2340 PHINode *PN = nullptr;
2341 ExtractValueInst *EVI = nullptr;
2342 BitCastInst *BCI = nullptr;
2343 Value *V = RetI->getReturnValue();
2344 if (V) {
2345 BCI = dyn_cast<BitCastInst>(V);
2346 if (BCI)
2347 V = BCI->getOperand(0);
2348
2349 EVI = dyn_cast<ExtractValueInst>(V);
2350 if (EVI) {
2351 V = EVI->getOperand(0);
2352 if (!llvm::all_of(EVI->indices(), [](unsigned idx) { return idx == 0; }))
2353 return false;
2354 }
2355
2356 PN = dyn_cast<PHINode>(V);
2357 if (!PN)
2358 return false;
2359 }
2360
2361 if (PN && PN->getParent() != BB)
2362 return false;
2363
2364 auto isLifetimeEndOrBitCastFor = [](const Instruction *Inst) {
2365 const BitCastInst *BC = dyn_cast<BitCastInst>(Inst);
2366 if (BC && BC->hasOneUse())
2367 Inst = BC->user_back();
2368
2369 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst))
2370 return II->getIntrinsicID() == Intrinsic::lifetime_end;
2371 return false;
2372 };
2373
2374 // Make sure there are no instructions between the first instruction
2375 // and return.
2376 const Instruction *BI = BB->getFirstNonPHI();
2377 // Skip over debug and the bitcast.
2378 while (isa<DbgInfoIntrinsic>(BI) || BI == BCI || BI == EVI ||
2379 isa<PseudoProbeInst>(BI) || isLifetimeEndOrBitCastFor(BI))
2380 BI = BI->getNextNode();
2381 if (BI != RetI)
2382 return false;
2383
2384 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
2385 /// call.
2386 const Function *F = BB->getParent();
2387 SmallVector<BasicBlock*, 4> TailCallBBs;
2388 if (PN) {
2389 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
2390 // Look through bitcasts.
2391 Value *IncomingVal = PN->getIncomingValue(I)->stripPointerCasts();
2392 CallInst *CI = dyn_cast<CallInst>(IncomingVal);
2393 BasicBlock *PredBB = PN->getIncomingBlock(I);
2394 // Make sure the phi value is indeed produced by the tail call.
2395 if (CI && CI->hasOneUse() && CI->getParent() == PredBB &&
2396 TLI->mayBeEmittedAsTailCall(CI) &&
2397 attributesPermitTailCall(F, CI, RetI, *TLI))
2398 TailCallBBs.push_back(PredBB);
2399 }
2400 } else {
2401 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
2402 for (BasicBlock *Pred : predecessors(BB)) {
2403 if (!VisitedBBs.insert(Pred).second)
2404 continue;
2405 if (Instruction *I = Pred->rbegin()->getPrevNonDebugInstruction(true)) {
2406 CallInst *CI = dyn_cast<CallInst>(I);
2407 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI) &&
2408 attributesPermitTailCall(F, CI, RetI, *TLI))
2409 TailCallBBs.push_back(Pred);
2410 }
2411 }
2412 }
2413
2414 bool Changed = false;
2415 for (auto const &TailCallBB : TailCallBBs) {
2416 // Make sure the call instruction is followed by an unconditional branch to
2417 // the return block.
2418 BranchInst *BI = dyn_cast<BranchInst>(TailCallBB->getTerminator());
2419 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
2420 continue;
2421
2422 // Duplicate the return into TailCallBB.
2423 (void)FoldReturnIntoUncondBranch(RetI, BB, TailCallBB);
2424 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", 2425, __extension__ __PRETTY_FUNCTION__
))
2425 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", 2425, __extension__ __PRETTY_FUNCTION__
))
;
2426 BFI->setBlockFreq(
2427 BB,
2428 (BFI->getBlockFreq(BB) - BFI->getBlockFreq(TailCallBB)).getFrequency());
2429 ModifiedDT = Changed = true;
2430 ++NumRetsDup;
2431 }
2432
2433 // If we eliminated all predecessors of the block, delete the block now.
2434 if (Changed && !BB->hasAddressTaken() && pred_empty(BB))
2435 BB->eraseFromParent();
2436
2437 return Changed;
2438}
2439
2440//===----------------------------------------------------------------------===//
2441// Memory Optimization
2442//===----------------------------------------------------------------------===//
2443
2444namespace {
2445
2446/// This is an extended version of TargetLowering::AddrMode
2447/// which holds actual Value*'s for register values.
2448struct ExtAddrMode : public TargetLowering::AddrMode {
2449 Value *BaseReg = nullptr;
2450 Value *ScaledReg = nullptr;
2451 Value *OriginalValue = nullptr;
2452 bool InBounds = true;
2453
2454 enum FieldName {
2455 NoField = 0x00,
2456 BaseRegField = 0x01,
2457 BaseGVField = 0x02,
2458 BaseOffsField = 0x04,
2459 ScaledRegField = 0x08,
2460 ScaleField = 0x10,
2461 MultipleFields = 0xff
2462 };
2463
2464
2465 ExtAddrMode() = default;
2466
2467 void print(raw_ostream &OS) const;
2468 void dump() const;
2469
2470 FieldName compare(const ExtAddrMode &other) {
2471 // First check that the types are the same on each field, as differing types
2472 // is something we can't cope with later on.
2473 if (BaseReg && other.BaseReg &&
2474 BaseReg->getType() != other.BaseReg->getType())
2475 return MultipleFields;
2476 if (BaseGV && other.BaseGV &&
2477 BaseGV->getType() != other.BaseGV->getType())
2478 return MultipleFields;
2479 if (ScaledReg && other.ScaledReg &&
2480 ScaledReg->getType() != other.ScaledReg->getType())
2481 return MultipleFields;
2482
2483 // Conservatively reject 'inbounds' mismatches.
2484 if (InBounds != other.InBounds)
2485 return MultipleFields;
2486
2487 // Check each field to see if it differs.
2488 unsigned Result = NoField;
2489 if (BaseReg != other.BaseReg)
2490 Result |= BaseRegField;
2491 if (BaseGV != other.BaseGV)
2492 Result |= BaseGVField;
2493 if (BaseOffs != other.BaseOffs)
2494 Result |= BaseOffsField;
2495 if (ScaledReg != other.ScaledReg)
2496 Result |= ScaledRegField;
2497 // Don't count 0 as being a different scale, because that actually means
2498 // unscaled (which will already be counted by having no ScaledReg).
2499 if (Scale && other.Scale && Scale != other.Scale)
2500 Result |= ScaleField;
2501
2502 if (countPopulation(Result) > 1)
2503 return MultipleFields;
2504 else
2505 return static_cast<FieldName>(Result);
2506 }
2507
2508 // An AddrMode is trivial if it involves no calculation i.e. it is just a base
2509 // with no offset.
2510 bool isTrivial() {
2511 // An AddrMode is (BaseGV + BaseReg + BaseOffs + ScaleReg * Scale) so it is
2512 // trivial if at most one of these terms is nonzero, except that BaseGV and
2513 // BaseReg both being zero actually means a null pointer value, which we
2514 // consider to be 'non-zero' here.
2515 return !BaseOffs && !Scale && !(BaseGV && BaseReg);
2516 }
2517
2518 Value *GetFieldAsValue(FieldName Field, Type *IntPtrTy) {
2519 switch (Field) {
2520 default:
2521 return nullptr;
2522 case BaseRegField:
2523 return BaseReg;
2524 case BaseGVField:
2525 return BaseGV;
2526 case ScaledRegField:
2527 return ScaledReg;
2528 case BaseOffsField:
2529 return ConstantInt::get(IntPtrTy, BaseOffs);
2530 }
2531 }
2532
2533 void SetCombinedField(FieldName Field, Value *V,
2534 const SmallVectorImpl<ExtAddrMode> &AddrModes) {
2535 switch (Field) {
2536 default:
2537 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", 2537)
;
2538 break;
2539 case ExtAddrMode::BaseRegField:
2540 BaseReg = V;
2541 break;
2542 case ExtAddrMode::BaseGVField:
2543 // A combined BaseGV is an Instruction, not a GlobalValue, so it goes
2544 // in the BaseReg field.
2545 assert(BaseReg == nullptr)(static_cast <bool> (BaseReg == nullptr) ? void (0) : __assert_fail
("BaseReg == nullptr", "llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 2545, __extension__ __PRETTY_FUNCTION__))
;
2546 BaseReg = V;
2547 BaseGV = nullptr;
2548 break;
2549 case ExtAddrMode::ScaledRegField:
2550 ScaledReg = V;
2551 // If we have a mix of scaled and unscaled addrmodes then we want scale
2552 // to be the scale and not zero.
2553 if (!Scale)
2554 for (const ExtAddrMode &AM : AddrModes)
2555 if (AM.Scale) {
2556 Scale = AM.Scale;
2557 break;
2558 }
2559 break;
2560 case ExtAddrMode::BaseOffsField:
2561 // The offset is no longer a constant, so it goes in ScaledReg with a
2562 // scale of 1.
2563 assert(ScaledReg == nullptr)(static_cast <bool> (ScaledReg == nullptr) ? void (0) :
__assert_fail ("ScaledReg == nullptr", "llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 2563, __extension__ __PRETTY_FUNCTION__))
;
2564 ScaledReg = V;
2565 Scale = 1;
2566 BaseOffs = 0;
2567 break;
2568 }
2569 }
2570};
2571
2572#ifndef NDEBUG
2573static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
2574 AM.print(OS);
2575 return OS;
2576}
2577#endif
2578
2579#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2580void ExtAddrMode::print(raw_ostream &OS) const {
2581 bool NeedPlus = false;
2582 OS << "[";
2583 if (InBounds)
2584 OS << "inbounds ";
2585 if (BaseGV) {
2586 OS << (NeedPlus ? " + " : "")
2587 << "GV:";
2588 BaseGV->printAsOperand(OS, /*PrintType=*/false);
2589 NeedPlus = true;
2590 }
2591
2592 if (BaseOffs) {
2593 OS << (NeedPlus ? " + " : "")
2594 << BaseOffs;
2595 NeedPlus = true;
2596 }
2597
2598 if (BaseReg) {
2599 OS << (NeedPlus ? " + " : "")
2600 << "Base:";
2601 BaseReg->printAsOperand(OS, /*PrintType=*/false);
2602 NeedPlus = true;
2603 }
2604 if (Scale) {
2605 OS << (NeedPlus ? " + " : "")
2606 << Scale << "*";
2607 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
2608 }
2609
2610 OS << ']';
2611}
2612
2613LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void ExtAddrMode::dump() const {
2614 print(dbgs());
2615 dbgs() << '\n';
2616}
2617#endif
2618
2619} // end anonymous namespace
2620
2621namespace {
2622
2623/// This class provides transaction based operation on the IR.
2624/// Every change made through this class is recorded in the internal state and
2625/// can be undone (rollback) until commit is called.
2626/// CGP does not check if instructions could be speculatively executed when
2627/// moved. Preserving the original location would pessimize the debugging
2628/// experience, as well as negatively impact the quality of sample PGO.
2629class TypePromotionTransaction {
2630 /// This represents the common interface of the individual transaction.
2631 /// Each class implements the logic for doing one specific modification on
2632 /// the IR via the TypePromotionTransaction.
2633 class TypePromotionAction {
2634 protected:
2635 /// The Instruction modified.
2636 Instruction *Inst;
2637
2638 public:
2639 /// Constructor of the action.
2640 /// The constructor performs the related action on the IR.
2641 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
2642
2643 virtual ~TypePromotionAction() = default;
2644
2645 /// Undo the modification done by this action.
2646 /// When this method is called, the IR must be in the same state as it was
2647 /// before this action was applied.
2648 /// \pre Undoing the action works if and only if the IR is in the exact same
2649 /// state as it was directly after this action was applied.
2650 virtual void undo() = 0;
2651
2652 /// Advocate every change made by this action.
2653 /// When the results on the IR of the action are to be kept, it is important
2654 /// to call this function, otherwise hidden information may be kept forever.
2655 virtual void commit() {
2656 // Nothing to be done, this action is not doing anything.
2657 }
2658 };
2659
2660 /// Utility to remember the position of an instruction.
2661 class InsertionHandler {
2662 /// Position of an instruction.
2663 /// Either an instruction:
2664 /// - Is the first in a basic block: BB is used.
2665 /// - Has a previous instruction: PrevInst is used.
2666 union {
2667 Instruction *PrevInst;
2668 BasicBlock *BB;
2669 } Point;
2670
2671 /// Remember whether or not the instruction had a previous instruction.
2672 bool HasPrevInstruction;
2673
2674 public:
2675 /// Record the position of \p Inst.
2676 InsertionHandler(Instruction *Inst) {
2677 BasicBlock::iterator It = Inst->getIterator();
2678 HasPrevInstruction = (It != (Inst->getParent()->begin()));
2679 if (HasPrevInstruction)
2680 Point.PrevInst = &*--It;
2681 else
2682 Point.BB = Inst->getParent();
2683 }
2684
2685 /// Insert \p Inst at the recorded position.
2686 void insert(Instruction *Inst) {
2687 if (HasPrevInstruction) {
2688 if (Inst->getParent())
2689 Inst->removeFromParent();
2690 Inst->insertAfter(Point.PrevInst);
2691 } else {
2692 Instruction *Position = &*Point.BB->getFirstInsertionPt();
2693 if (Inst->getParent())
2694 Inst->moveBefore(Position);
2695 else
2696 Inst->insertBefore(Position);
2697 }
2698 }
2699 };
2700
2701 /// Move an instruction before another.
2702 class InstructionMoveBefore : public TypePromotionAction {
2703 /// Original position of the instruction.
2704 InsertionHandler Position;
2705
2706 public:
2707 /// Move \p Inst before \p Before.
2708 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
2709 : TypePromotionAction(Inst), Position(Inst) {
2710 LLVM_DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Beforedo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Do: move: " << *
Inst << "\nbefore: " << *Before << "\n"; } }
while (false)
2711 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Do: move: " << *
Inst << "\nbefore: " << *Before << "\n"; } }
while (false)
;
2712 Inst->moveBefore(Before);
2713 }
2714
2715 /// Move the instruction back to its original position.
2716 void undo() override {
2717 LLVM_DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Undo: moveBefore: " <<
*Inst << "\n"; } } while (false)
;
2718 Position.insert(Inst);
2719 }
2720 };
2721
2722 /// Set the operand of an instruction with a new value.
2723 class OperandSetter : public TypePromotionAction {
2724 /// Original operand of the instruction.
2725 Value *Origin;
2726
2727 /// Index of the modified instruction.
2728 unsigned Idx;
2729
2730 public:
2731 /// Set \p Idx operand of \p Inst with \p NewVal.
2732 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
2733 : TypePromotionAction(Inst), Idx(Idx) {
2734 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)
2735 << "for:" << *Inst << "\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Do: setOperand: " <<
Idx << "\n" << "for:" << *Inst << "\n"
<< "with:" << *NewVal << "\n"; } } while (
false)
2736 << "with:" << *NewVal << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Do: setOperand: " <<
Idx << "\n" << "for:" << *Inst << "\n"
<< "with:" << *NewVal << "\n"; } } while (
false)
;
2737 Origin = Inst->getOperand(Idx);
2738 Inst->setOperand(Idx, NewVal);
2739 }
2740
2741 /// Restore the original value of the instruction.
2742 void undo() override {
2743 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)
2744 << "for: " << *Inst << "\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Undo: setOperand:" <<
Idx << "\n" << "for: " << *Inst << "\n"
<< "with: " << *Origin << "\n"; } } while (
false)
2745 << "with: " << *Origin << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Undo: setOperand:" <<
Idx << "\n" << "for: " << *Inst << "\n"
<< "with: " << *Origin << "\n"; } } while (
false)
;
2746 Inst->setOperand(Idx, Origin);
2747 }
2748 };
2749
2750 /// Hide the operands of an instruction.
2751 /// Do as if this instruction was not using any of its operands.
2752 class OperandsHider : public TypePromotionAction {
2753 /// The list of original operands.
2754 SmallVector<Value *, 4> OriginalValues;
2755
2756 public:
2757 /// Remove \p Inst from the uses of the operands of \p Inst.
2758 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
2759 LLVM_DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Do: OperandsHider: " <<
*Inst << "\n"; } } while (false)
;
2760 unsigned NumOpnds = Inst->getNumOperands();
2761 OriginalValues.reserve(NumOpnds);
2762 for (unsigned It = 0; It < NumOpnds; ++It) {
2763 // Save the current operand.
2764 Value *Val = Inst->getOperand(It);
2765 OriginalValues.push_back(Val);
2766 // Set a dummy one.
2767 // We could use OperandSetter here, but that would imply an overhead
2768 // that we are not willing to pay.
2769 Inst->setOperand(It, UndefValue::get(Val->getType()));
2770 }
2771 }
2772
2773 /// Restore the original list of uses.
2774 void undo() override {
2775 LLVM_DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Undo: OperandsHider: "
<< *Inst << "\n"; } } while (false)
;
2776 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
2777 Inst->setOperand(It, OriginalValues[It]);
2778 }
2779 };
2780
2781 /// Build a truncate instruction.
2782 class TruncBuilder : public TypePromotionAction {
2783 Value *Val;
2784
2785 public:
2786 /// Build a truncate instruction of \p Opnd producing a \p Ty
2787 /// result.
2788 /// trunc Opnd to Ty.
2789 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
2790 IRBuilder<> Builder(Opnd);
2791 Builder.SetCurrentDebugLocation(DebugLoc());
2792 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
2793 LLVM_DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Do: TruncBuilder: " <<
*Val << "\n"; } } while (false)
;
2794 }
2795
2796 /// Get the built value.
2797 Value *getBuiltValue() { return Val; }
2798
2799 /// Remove the built instruction.
2800 void undo() override {
2801 LLVM_DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Undo: TruncBuilder: " <<
*Val << "\n"; } } while (false)
;
2802 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2803 IVal->eraseFromParent();
2804 }
2805 };
2806
2807 /// Build a sign extension instruction.
2808 class SExtBuilder : public TypePromotionAction {
2809 Value *Val;
2810
2811 public:
2812 /// Build a sign extension instruction of \p Opnd producing a \p Ty
2813 /// result.
2814 /// sext Opnd to Ty.
2815 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
2816 : TypePromotionAction(InsertPt) {
2817 IRBuilder<> Builder(InsertPt);
2818 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
2819 LLVM_DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Do: SExtBuilder: " <<
*Val << "\n"; } } while (false)
;
2820 }
2821
2822 /// Get the built value.
2823 Value *getBuiltValue() { return Val; }
2824
2825 /// Remove the built instruction.
2826 void undo() override {
2827 LLVM_DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Undo: SExtBuilder: " <<
*Val << "\n"; } } while (false)
;
2828 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2829 IVal->eraseFromParent();
2830 }
2831 };
2832
2833 /// Build a zero extension instruction.
2834 class ZExtBuilder : public TypePromotionAction {
2835 Value *Val;
2836
2837 public:
2838 /// Build a zero extension instruction of \p Opnd producing a \p Ty
2839 /// result.
2840 /// zext Opnd to Ty.
2841 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
2842 : TypePromotionAction(InsertPt) {
2843 IRBuilder<> Builder(InsertPt);
2844 Builder.SetCurrentDebugLocation(DebugLoc());
2845 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
2846 LLVM_DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Do: ZExtBuilder: " <<
*Val << "\n"; } } while (false)
;
2847 }
2848
2849 /// Get the built value.
2850 Value *getBuiltValue() { return Val; }
2851
2852 /// Remove the built instruction.
2853 void undo() override {
2854 LLVM_DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Undo: ZExtBuilder: " <<
*Val << "\n"; } } while (false)
;
2855 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2856 IVal->eraseFromParent();
2857 }
2858 };
2859
2860 /// Mutate an instruction to another type.
2861 class TypeMutator : public TypePromotionAction {
2862 /// Record the original type.
2863 Type *OrigTy;
2864
2865 public:
2866 /// Mutate the type of \p Inst into \p NewTy.
2867 TypeMutator(Instruction *Inst, Type *NewTy)
2868 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
2869 LLVM_DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTydo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Do: MutateType: " <<
*Inst << " with " << *NewTy << "\n"; } } while
(false)
2870 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Do: MutateType: " <<
*Inst << " with " << *NewTy << "\n"; } } while
(false)
;
2871 Inst->mutateType(NewTy);
2872 }
2873
2874 /// Mutate the instruction back to its original type.
2875 void undo() override {
2876 LLVM_DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTydo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Undo: MutateType: " <<
*Inst << " with " << *OrigTy << "\n"; } } while
(false)
2877 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Undo: MutateType: " <<
*Inst << " with " << *OrigTy << "\n"; } } while
(false)
;
2878 Inst->mutateType(OrigTy);
2879 }
2880 };
2881
2882 /// Replace the uses of an instruction by another instruction.
2883 class UsesReplacer : public TypePromotionAction {
2884 /// Helper structure to keep track of the replaced uses.
2885 struct InstructionAndIdx {
2886 /// The instruction using the instruction.
2887 Instruction *Inst;
2888
2889 /// The index where this instruction is used for Inst.
2890 unsigned Idx;
2891
2892 InstructionAndIdx(Instruction *Inst, unsigned Idx)
2893 : Inst(Inst), Idx(Idx) {}
2894 };
2895
2896 /// Keep track of the original uses (pair Instruction, Index).
2897 SmallVector<InstructionAndIdx, 4> OriginalUses;
2898 /// Keep track of the debug users.
2899 SmallVector<DbgValueInst *, 1> DbgValues;
2900
2901 /// Keep track of the new value so that we can undo it by replacing
2902 /// instances of the new value with the original value.
2903 Value *New;
2904
2905 using use_iterator = SmallVectorImpl<InstructionAndIdx>::iterator;
2906
2907 public:
2908 /// Replace all the use of \p Inst by \p New.
2909 UsesReplacer(Instruction *Inst, Value *New)
2910 : TypePromotionAction(Inst), New(New) {
2911 LLVM_DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *Newdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Do: UsersReplacer: " <<
*Inst << " with " << *New << "\n"; } } while
(false)
2912 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Do: UsersReplacer: " <<
*Inst << " with " << *New << "\n"; } } while
(false)
;
2913 // Record the original uses.
2914 for (Use &U : Inst->uses()) {
2915 Instruction *UserI = cast<Instruction>(U.getUser());
2916 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
2917 }
2918 // Record the debug uses separately. They are not in the instruction's
2919 // use list, but they are replaced by RAUW.
2920 findDbgValues(DbgValues, Inst);
2921
2922 // Now, we can replace the uses.
2923 Inst->replaceAllUsesWith(New);
2924 }
2925
2926 /// Reassign the original uses of Inst to Inst.
2927 void undo() override {
2928 LLVM_DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Undo: UsersReplacer: "
<< *Inst << "\n"; } } while (false)
;
2929 for (InstructionAndIdx &Use : OriginalUses)
2930 Use.Inst->setOperand(Use.Idx, Inst);
2931 // RAUW has replaced all original uses with references to the new value,
2932 // including the debug uses. Since we are undoing the replacements,
2933 // the original debug uses must also be reinstated to maintain the
2934 // correctness and utility of debug value instructions.
2935 for (auto *DVI : DbgValues)
2936 DVI->replaceVariableLocationOp(New, Inst);
2937 }
2938 };
2939
2940 /// Remove an instruction from the IR.
2941 class InstructionRemover : public TypePromotionAction {
2942 /// Original position of the instruction.
2943 InsertionHandler Inserter;
2944
2945 /// Helper structure to hide all the link to the instruction. In other
2946 /// words, this helps to do as if the instruction was removed.
2947 OperandsHider Hider;
2948
2949 /// Keep track of the uses replaced, if any.
2950 UsesReplacer *Replacer = nullptr;
2951
2952 /// Keep track of instructions removed.
2953 SetOfInstrs &RemovedInsts;
2954
2955 public:
2956 /// Remove all reference of \p Inst and optionally replace all its
2957 /// uses with New.
2958 /// \p RemovedInsts Keep track of the instructions removed by this Action.
2959 /// \pre If !Inst->use_empty(), then New != nullptr
2960 InstructionRemover(Instruction *Inst, SetOfInstrs &RemovedInsts,
2961 Value *New = nullptr)
2962 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
2963 RemovedInsts(RemovedInsts) {
2964 if (New)
2965 Replacer = new UsesReplacer(Inst, New);
2966 LLVM_DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Do: InstructionRemover: "
<< *Inst << "\n"; } } while (false)
;
2967 RemovedInsts.insert(Inst);
2968 /// The instructions removed here will be freed after completing
2969 /// optimizeBlock() for all blocks as we need to keep track of the
2970 /// removed instructions during promotion.
2971 Inst->removeFromParent();
2972 }
2973
2974 ~InstructionRemover() override { delete Replacer; }
2975
2976 /// Resurrect the instruction and reassign it to the proper uses if
2977 /// new value was provided when build this action.
2978 void undo() override {
2979 LLVM_DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Undo: InstructionRemover: "
<< *Inst << "\n"; } } while (false)
;
2980 Inserter.insert(Inst);
2981 if (Replacer)
2982 Replacer->undo();
2983 Hider.undo();
2984 RemovedInsts.erase(Inst);
2985 }
2986 };
2987
2988public:
2989 /// Restoration point.
2990 /// The restoration point is a pointer to an action instead of an iterator
2991 /// because the iterator may be invalidated but not the pointer.
2992 using ConstRestorationPt = const TypePromotionAction *;
2993
2994 TypePromotionTransaction(SetOfInstrs &RemovedInsts)
2995 : RemovedInsts(RemovedInsts) {}
2996
2997 /// Advocate every changes made in that transaction. Return true if any change
2998 /// happen.
2999 bool commit();
3000
3001 /// Undo all the changes made after the given point.
3002 void rollback(ConstRestorationPt Point);
3003
3004 /// Get the current restoration point.
3005 ConstRestorationPt getRestorationPoint() const;
3006
3007 /// \name API for IR modification with state keeping to support rollback.
3008 /// @{
3009 /// Same as Instruction::setOperand.
3010 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
3011
3012 /// Same as Instruction::eraseFromParent.
3013 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
3014
3015 /// Same as Value::replaceAllUsesWith.
3016 void replaceAllUsesWith(Instruction *Inst, Value *New);
3017
3018 /// Same as Value::mutateType.
3019 void mutateType(Instruction *Inst, Type *NewTy);
3020
3021 /// Same as IRBuilder::createTrunc.
3022 Value *createTrunc(Instruction *Opnd, Type *Ty);
3023
3024 /// Same as IRBuilder::createSExt.
3025 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
3026
3027 /// Same as IRBuilder::createZExt.
3028 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
3029
3030 /// Same as Instruction::moveBefore.
3031 void moveBefore(Instruction *Inst, Instruction *Before);
3032 /// @}
3033
3034private:
3035 /// The ordered list of actions made so far.
3036 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
3037
3038 using CommitPt = SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator;
3039
3040 SetOfInstrs &RemovedInsts;
3041};
3042
3043} // end anonymous namespace
3044
3045void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
3046 Value *NewVal) {
3047 Actions.push_back(std::make_unique<TypePromotionTransaction::OperandSetter>(
3048 Inst, Idx, NewVal));
3049}
3050
3051void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
3052 Value *NewVal) {
3053 Actions.push_back(
3054 std::make_unique<TypePromotionTransaction::InstructionRemover>(
3055 Inst, RemovedInsts, NewVal));
3056}
3057
3058void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
3059 Value *New) {
3060 Actions.push_back(
3061 std::make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
3062}
3063
3064void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
3065 Actions.push_back(
3066 std::make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
3067}
3068
3069Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
3070 Type *Ty) {
3071 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
3072 Value *Val = Ptr->getBuiltValue();
3073 Actions.push_back(std::move(Ptr));
3074 return Val;
3075}
3076
3077Value *TypePromotionTransaction::createSExt(Instruction *Inst,
3078 Value *Opnd, Type *Ty) {
3079 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
3080 Value *Val = Ptr->getBuiltValue();
3081 Actions.push_back(std::move(Ptr));
3082 return Val;
3083}
3084
3085Value *TypePromotionTransaction::createZExt(Instruction *Inst,
3086 Value *Opnd, Type *Ty) {
3087 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
3088 Value *Val = Ptr->getBuiltValue();
3089 Actions.push_back(std::move(Ptr));
3090 return Val;
3091}
3092
3093void TypePromotionTransaction::moveBefore(Instruction *Inst,
3094 Instruction *Before) {
3095 Actions.push_back(
3096 std::make_unique<TypePromotionTransaction::InstructionMoveBefore>(
3097 Inst, Before));
3098}
3099
3100TypePromotionTransaction::ConstRestorationPt
3101TypePromotionTransaction::getRestorationPoint() const {
3102 return !Actions.empty() ? Actions.back().get() : nullptr;
3103}
3104
3105bool TypePromotionTransaction::commit() {
3106 for (std::unique_ptr<TypePromotionAction> &Action : Actions)
3107 Action->commit();
3108 bool Modified = !Actions.empty();
3109 Actions.clear();
3110 return Modified;
3111}
3112
3113void TypePromotionTransaction::rollback(
3114 TypePromotionTransaction::ConstRestorationPt Point) {
3115 while (!Actions.empty() && Point != Actions.back().get()) {
3116 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
3117 Curr->undo();
3118 }
3119}
3120
3121namespace {
3122
3123/// A helper class for matching addressing modes.
3124///
3125/// This encapsulates the logic for matching the target-legal addressing modes.
3126class AddressingModeMatcher {
3127 SmallVectorImpl<Instruction*> &AddrModeInsts;
3128 const TargetLowering &TLI;
3129 const TargetRegisterInfo &TRI;
3130 const DataLayout &DL;
3131 const LoopInfo &LI;
3132 const std::function<const DominatorTree &()> getDTFn;
3133
3134 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
3135 /// the memory instruction that we're computing this address for.
3136 Type *AccessTy;
3137 unsigned AddrSpace;
3138 Instruction *MemoryInst;
3139
3140 /// This is the addressing mode that we're building up. This is
3141 /// part of the return value of this addressing mode matching stuff.
3142 ExtAddrMode &AddrMode;
3143
3144 /// The instructions inserted by other CodeGenPrepare optimizations.
3145 const SetOfInstrs &InsertedInsts;
3146
3147 /// A map from the instructions to their type before promotion.
3148 InstrToOrigTy &PromotedInsts;
3149
3150 /// The ongoing transaction where every action should be registered.
3151 TypePromotionTransaction &TPT;
3152
3153 // A GEP which has too large offset to be folded into the addressing mode.
3154 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP;
3155
3156 /// This is set to true when we should not do profitability checks.
3157 /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
3158 bool IgnoreProfitability;
3159
3160 /// True if we are optimizing for size.
3161 bool OptSize;
3162
3163 ProfileSummaryInfo *PSI;
3164 BlockFrequencyInfo *BFI;
3165
3166 AddressingModeMatcher(
3167 SmallVectorImpl<Instruction *> &AMI, const TargetLowering &TLI,
3168 const TargetRegisterInfo &TRI, const LoopInfo &LI,
3169 const std::function<const DominatorTree &()> getDTFn,
3170 Type *AT, unsigned AS, Instruction *MI, ExtAddrMode &AM,
3171 const SetOfInstrs &InsertedInsts, InstrToOrigTy &PromotedInsts,
3172 TypePromotionTransaction &TPT,
3173 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP,
3174 bool OptSize, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI)
3175 : AddrModeInsts(AMI), TLI(TLI), TRI(TRI),
3176 DL(MI->getModule()->getDataLayout()), LI(LI), getDTFn(getDTFn),
3177 AccessTy(AT), AddrSpace(AS), MemoryInst(MI), AddrMode(AM),
3178 InsertedInsts(InsertedInsts), PromotedInsts(PromotedInsts), TPT(TPT),
3179 LargeOffsetGEP(LargeOffsetGEP), OptSize(OptSize), PSI(PSI), BFI(BFI) {
3180 IgnoreProfitability = false;
3181 }
3182
3183public:
3184 /// Find the maximal addressing mode that a load/store of V can fold,
3185 /// give an access type of AccessTy. This returns a list of involved
3186 /// instructions in AddrModeInsts.
3187 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
3188 /// optimizations.
3189 /// \p PromotedInsts maps the instructions to their type before promotion.
3190 /// \p The ongoing transaction where every action should be registered.
3191 static ExtAddrMode
3192 Match(Value *V, Type *AccessTy, unsigned AS, Instruction *MemoryInst,
3193 SmallVectorImpl<Instruction *> &AddrModeInsts,
3194 const TargetLowering &TLI, const LoopInfo &LI,
3195 const std::function<const DominatorTree &()> getDTFn,
3196 const TargetRegisterInfo &TRI, const SetOfInstrs &InsertedInsts,
3197 InstrToOrigTy &PromotedInsts, TypePromotionTransaction &TPT,
3198 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP,
3199 bool OptSize, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI) {
3200 ExtAddrMode Result;
3201
3202 bool Success = AddressingModeMatcher(
3203 AddrModeInsts, TLI, TRI, LI, getDTFn, AccessTy, AS, MemoryInst, Result,
3204 InsertedInsts, PromotedInsts, TPT, LargeOffsetGEP, OptSize, PSI,
3205 BFI).matchAddr(V, 0);
3206 (void)Success; 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", 3206, __extension__ __PRETTY_FUNCTION__
))
;
3207 return Result;
3208 }
3209
3210private:
3211 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
3212 bool matchAddr(Value *Addr, unsigned Depth);
3213 bool matchOperationAddr(User *AddrInst, unsigned Opcode, unsigned Depth,
3214 bool *MovedAway = nullptr);
3215 bool isProfitableToFoldIntoAddressingMode(Instruction *I,
3216 ExtAddrMode &AMBefore,
3217 ExtAddrMode &AMAfter);
3218 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
3219 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
3220 Value *PromotedOperand) const;
3221};
3222
3223class PhiNodeSet;
3224
3225/// An iterator for PhiNodeSet.
3226class PhiNodeSetIterator {
3227 PhiNodeSet * const Set;
3228 size_t CurrentIndex = 0;
3229
3230public:
3231 /// The constructor. Start should point to either a valid element, or be equal
3232 /// to the size of the underlying SmallVector of the PhiNodeSet.
3233 PhiNodeSetIterator(PhiNodeSet * const Set, size_t Start);
3234 PHINode * operator*() const;
3235 PhiNodeSetIterator& operator++();
3236 bool operator==(const PhiNodeSetIterator &RHS) const;
3237 bool operator!=(const PhiNodeSetIterator &RHS) const;
3238};
3239
3240/// Keeps a set of PHINodes.
3241///
3242/// This is a minimal set implementation for a specific use case:
3243/// It is very fast when there are very few elements, but also provides good
3244/// performance when there are many. It is similar to SmallPtrSet, but also
3245/// provides iteration by insertion order, which is deterministic and stable
3246/// across runs. It is also similar to SmallSetVector, but provides removing
3247/// elements in O(1) time. This is achieved by not actually removing the element
3248/// from the underlying vector, so comes at the cost of using more memory, but
3249/// that is fine, since PhiNodeSets are used as short lived objects.
3250class PhiNodeSet {
3251 friend class PhiNodeSetIterator;
3252
3253 using MapType = SmallDenseMap<PHINode *, size_t, 32>;
3254 using iterator = PhiNodeSetIterator;
3255
3256 /// Keeps the elements in the order of their insertion in the underlying
3257 /// vector. To achieve constant time removal, it never deletes any element.
3258 SmallVector<PHINode *, 32> NodeList;
3259
3260 /// Keeps the elements in the underlying set implementation. This (and not the
3261 /// NodeList defined above) is the source of truth on whether an element
3262 /// is actually in the collection.
3263 MapType NodeMap;
3264
3265 /// Points to the first valid (not deleted) element when the set is not empty
3266 /// and the value is not zero. Equals to the size of the underlying vector
3267 /// when the set is empty. When the value is 0, as in the beginning, the
3268 /// first element may or may not be valid.
3269 size_t FirstValidElement = 0;
3270
3271public:
3272 /// Inserts a new element to the collection.
3273 /// \returns true if the element is actually added, i.e. was not in the
3274 /// collection before the operation.
3275 bool insert(PHINode *Ptr) {
3276 if (NodeMap.insert(std::make_pair(Ptr, NodeList.size())).second) {
3277 NodeList.push_back(Ptr);
3278 return true;
3279 }
3280 return false;
3281 }
3282
3283 /// Removes the element from the collection.
3284 /// \returns whether the element is actually removed, i.e. was in the
3285 /// collection before the operation.
3286 bool erase(PHINode *Ptr) {
3287 if (NodeMap.erase(Ptr)) {
3288 SkipRemovedElements(FirstValidElement);
3289 return true;
3290 }
3291 return false;
3292 }
3293
3294 /// Removes all elements and clears the collection.
3295 void clear() {
3296 NodeMap.clear();
3297 NodeList.clear();
3298 FirstValidElement = 0;
3299 }
3300
3301 /// \returns an iterator that will iterate the elements in the order of
3302 /// insertion.
3303 iterator begin() {
3304 if (FirstValidElement == 0)
3305 SkipRemovedElements(FirstValidElement);
3306 return PhiNodeSetIterator(this, FirstValidElement);
3307 }
3308
3309 /// \returns an iterator that points to the end of the collection.
3310 iterator end() { return PhiNodeSetIterator(this, NodeList.size()); }
3311
3312 /// Returns the number of elements in the collection.
3313 size_t size() const {
3314 return NodeMap.size();
3315 }
3316
3317 /// \returns 1 if the given element is in the collection, and 0 if otherwise.
3318 size_t count(PHINode *Ptr) const {
3319 return NodeMap.count(Ptr);
3320 }
3321
3322private:
3323 /// Updates the CurrentIndex so that it will point to a valid element.
3324 ///
3325 /// If the element of NodeList at CurrentIndex is valid, it does not
3326 /// change it. If there are no more valid elements, it updates CurrentIndex
3327 /// to point to the end of the NodeList.
3328 void SkipRemovedElements(size_t &CurrentIndex) {
3329 while (CurrentIndex < NodeList.size()) {
3330 auto it = NodeMap.find(NodeList[CurrentIndex]);
3331 // If the element has been deleted and added again later, NodeMap will
3332 // point to a different index, so CurrentIndex will still be invalid.
3333 if (it != NodeMap.end() && it->second == CurrentIndex)
3334 break;
3335 ++CurrentIndex;
3336 }
3337 }
3338};
3339
3340PhiNodeSetIterator::PhiNodeSetIterator(PhiNodeSet *const Set, size_t Start)
3341 : Set(Set), CurrentIndex(Start) {}
3342
3343PHINode * PhiNodeSetIterator::operator*() const {
3344 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", 3345, __extension__ __PRETTY_FUNCTION__
))
3345 "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", 3345, __extension__ __PRETTY_FUNCTION__
))
;
3346 return Set->NodeList[CurrentIndex];
3347}
3348
3349PhiNodeSetIterator& PhiNodeSetIterator::operator++() {
3350 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", 3351, __extension__ __PRETTY_FUNCTION__
))
3351 "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", 3351, __extension__ __PRETTY_FUNCTION__
))
;
3352 ++CurrentIndex;
3353 Set->SkipRemovedElements(CurrentIndex);
3354 return *this;
3355}
3356
3357bool PhiNodeSetIterator::operator==(const PhiNodeSetIterator &RHS) const {
3358 return CurrentIndex == RHS.CurrentIndex;
3359}
3360
3361bool PhiNodeSetIterator::operator!=(const PhiNodeSetIterator &RHS) const {
3362 return !((*this) == RHS);
3363}
3364
3365/// Keep track of simplification of Phi nodes.
3366/// Accept the set of all phi nodes and erase phi node from this set
3367/// if it is simplified.
3368class SimplificationTracker {
3369 DenseMap<Value *, Value *> Storage;
3370 const SimplifyQuery &SQ;
3371 // Tracks newly created Phi nodes. The elements are iterated by insertion
3372 // order.
3373 PhiNodeSet AllPhiNodes;
3374 // Tracks newly created Select nodes.
3375 SmallPtrSet<SelectInst *, 32> AllSelectNodes;
3376
3377public:
3378 SimplificationTracker(const SimplifyQuery &sq)
3379 : SQ(sq) {}
3380
3381 Value *Get(Value *V) {
3382 do {
3383 auto SV = Storage.find(V);
3384 if (SV == Storage.end())
3385 return V;
3386 V = SV->second;
3387 } while (true);
3388 }
3389
3390 Value *Simplify(Value *Val) {
3391 SmallVector<Value *, 32> WorkList;
3392 SmallPtrSet<Value *, 32> Visited;
3393 WorkList.push_back(Val);
3394 while (!WorkList.empty()) {
3395 auto *P = WorkList.pop_back_val();
3396 if (!Visited.insert(P).second)
3397 continue;
3398 if (auto *PI = dyn_cast<Instruction>(P))
3399 if (Value *V = simplifyInstruction(cast<Instruction>(PI), SQ)) {
3400 for (auto *U : PI->users())
3401 WorkList.push_back(cast<Value>(U));
3402 Put(PI, V);
3403 PI->replaceAllUsesWith(V);
3404 if (auto *PHI = dyn_cast<PHINode>(PI))
3405 AllPhiNodes.erase(PHI);
3406 if (auto *Select = dyn_cast<SelectInst>(PI))
3407 AllSelectNodes.erase(Select);
3408 PI->eraseFromParent();
3409 }
3410 }
3411 return Get(Val);
3412 }
3413
3414 void Put(Value *From, Value *To) {
3415 Storage.insert({ From, To });
3416 }
3417
3418 void ReplacePhi(PHINode *From, PHINode *To) {
3419 Value* OldReplacement = Get(From);
3420 while (OldReplacement != From) {
3421 From = To;
3422 To = dyn_cast<PHINode>(OldReplacement);
3423 OldReplacement = Get(From);
3424 }
3425 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", 3425, __extension__ __PRETTY_FUNCTION__
))
;
3426 Put(From, To);
3427 From->replaceAllUsesWith(To);
3428 AllPhiNodes.erase(From);
3429 From->eraseFromParent();
3430 }
3431
3432 PhiNodeSet& newPhiNodes() { return AllPhiNodes; }
3433
3434 void insertNewPhi(PHINode *PN) { AllPhiNodes.insert(PN); }
3435
3436 void insertNewSelect(SelectInst *SI) { AllSelectNodes.insert(SI); }
3437
3438 unsigned countNewPhiNodes() const { return AllPhiNodes.size(); }
3439
3440 unsigned countNewSelectNodes() const { return AllSelectNodes.size(); }
3441
3442 void destroyNewNodes(Type *CommonType) {
3443 // For safe erasing, replace the uses with dummy value first.
3444 auto *Dummy = PoisonValue::get(CommonType);
3445 for (auto *I : AllPhiNodes) {
3446 I->replaceAllUsesWith(Dummy);
3447 I->eraseFromParent();
3448 }
3449 AllPhiNodes.clear();
3450 for (auto *I : AllSelectNodes) {
3451 I->replaceAllUsesWith(Dummy);
3452 I->eraseFromParent();
3453 }
3454 AllSelectNodes.clear();
3455 }
3456};
3457
3458/// A helper class for combining addressing modes.
3459class AddressingModeCombiner {
3460 typedef DenseMap<Value *, Value *> FoldAddrToValueMapping;
3461 typedef std::pair<PHINode *, PHINode *> PHIPair;
3462
3463private:
3464 /// The addressing modes we've collected.
3465 SmallVector<ExtAddrMode, 16> AddrModes;
3466
3467 /// The field in which the AddrModes differ, when we have more than one.
3468 ExtAddrMode::FieldName DifferentField = ExtAddrMode::NoField;
3469
3470 /// Are the AddrModes that we have all just equal to their original values?
3471 bool AllAddrModesTrivial = true;
3472
3473 /// Common Type for all different fields in addressing modes.
3474 Type *CommonType = nullptr;
3475
3476 /// SimplifyQuery for simplifyInstruction utility.
3477 const SimplifyQuery &SQ;
3478
3479 /// Original Address.
3480 Value *Original;
3481
3482public:
3483 AddressingModeCombiner(const SimplifyQuery &_SQ, Value *OriginalValue)
3484 : SQ(_SQ), Original(OriginalValue) {}
3485
3486 /// Get the combined AddrMode
3487 const ExtAddrMode &getAddrMode() const {
3488 return AddrModes[0];
3489 }
3490
3491 /// Add a new AddrMode if it's compatible with the AddrModes we already
3492 /// have.
3493 /// \return True iff we succeeded in doing so.
3494 bool addNewAddrMode(ExtAddrMode &NewAddrMode) {
3495 // Take note of if we have any non-trivial AddrModes, as we need to detect
3496 // when all AddrModes are trivial as then we would introduce a phi or select
3497 // which just duplicates what's already there.
3498 AllAddrModesTrivial = AllAddrModesTrivial && NewAddrMode.isTrivial();
3499
3500 // If this is the first addrmode then everything is fine.
3501 if (AddrModes.empty()) {
3502 AddrModes.emplace_back(NewAddrMode);
3503 return true;
3504 }
3505
3506 // Figure out how different this is from the other address modes, which we
3507 // can do just by comparing against the first one given that we only care
3508 // about the cumulative difference.
3509 ExtAddrMode::FieldName ThisDifferentField =
3510 AddrModes[0].compare(NewAddrMode);
3511 if (DifferentField == ExtAddrMode::NoField)
3512 DifferentField = ThisDifferentField;
3513 else if (DifferentField != ThisDifferentField)
3514 DifferentField = ExtAddrMode::MultipleFields;
3515
3516 // If NewAddrMode differs in more than one dimension we cannot handle it.
3517 bool CanHandle = DifferentField != ExtAddrMode::MultipleFields;
3518
3519 // If Scale Field is different then we reject.
3520 CanHandle = CanHandle && DifferentField != ExtAddrMode::ScaleField;
3521
3522 // We also must reject the case when base offset is different and
3523 // scale reg is not null, we cannot handle this case due to merge of
3524 // different offsets will be used as ScaleReg.
3525 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseOffsField ||
3526 !NewAddrMode.ScaledReg);
3527
3528 // We also must reject the case when GV is different and BaseReg installed
3529 // due to we want to use base reg as a merge of GV values.
3530 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseGVField ||
3531 !NewAddrMode.HasBaseReg);
3532
3533 // Even if NewAddMode is the same we still need to collect it due to
3534 // original value is different. And later we will need all original values
3535 // as anchors during finding the common Phi node.
3536 if (CanHandle)
3537 AddrModes.emplace_back(NewAddrMode);
3538 else
3539 AddrModes.clear();
3540
3541 return CanHandle;
3542 }
3543
3544 /// Combine the addressing modes we've collected into a single
3545 /// addressing mode.
3546 /// \return True iff we successfully combined them or we only had one so
3547 /// didn't need to combine them anyway.
3548 bool combineAddrModes() {
3549 // If we have no AddrModes then they can't be combined.
3550 if (AddrModes.size() == 0)
3551 return false;
3552
3553 // A single AddrMode can trivially be combined.
3554 if (AddrModes.size() == 1 || DifferentField == ExtAddrMode::NoField)
3555 return true;
3556
3557 // If the AddrModes we collected are all just equal to the value they are
3558 // derived from then combining them wouldn't do anything useful.
3559 if (AllAddrModesTrivial)
3560 return false;
3561
3562 if (!addrModeCombiningAllowed())
3563 return false;
3564
3565 // Build a map between <original value, basic block where we saw it> to
3566 // value of base register.
3567 // Bail out if there is no common type.
3568 FoldAddrToValueMapping Map;
3569 if (!initializeMap(Map))
3570 return false;
3571
3572 Value *CommonValue = findCommon(Map);
3573 if (CommonValue)
3574 AddrModes[0].SetCombinedField(DifferentField, CommonValue, AddrModes);
3575 return CommonValue != nullptr;
3576 }
3577
3578private:
3579 /// Initialize Map with anchor values. For address seen
3580 /// we set the value of different field saw in this address.
3581 /// At the same time we find a common type for different field we will
3582 /// use to create new Phi/Select nodes. Keep it in CommonType field.
3583 /// Return false if there is no common type found.
3584 bool initializeMap(FoldAddrToValueMapping &Map) {
3585 // Keep track of keys where the value is null. We will need to replace it
3586 // with constant null when we know the common type.
3587 SmallVector<Value *, 2> NullValue;
3588 Type *IntPtrTy = SQ.DL.getIntPtrType(AddrModes[0].OriginalValue->getType());
3589 for (auto &AM : AddrModes) {
3590 Value *DV = AM.GetFieldAsValue(DifferentField, IntPtrTy);
3591 if (DV) {
3592 auto *Type = DV->getType();
3593 if (CommonType && CommonType != Type)
3594 return false;
3595 CommonType = Type;
3596 Map[AM.OriginalValue] = DV;
3597 } else {
3598 NullValue.push_back(AM.OriginalValue);
3599 }
3600 }
3601 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", 3601, __extension__ __PRETTY_FUNCTION__
))
;
3602 for (auto *V : NullValue)
3603 Map[V] = Constant::getNullValue(CommonType);
3604 return true;
3605 }
3606
3607 /// We have mapping between value A and other value B where B was a field in
3608 /// addressing mode represented by A. Also we have an original value C
3609 /// representing an address we start with. Traversing from C through phi and
3610 /// selects we ended up with A's in a map. This utility function tries to find
3611 /// a value V which is a field in addressing mode C and traversing through phi
3612 /// nodes and selects we will end up in corresponded values B in a map.
3613 /// The utility will create a new Phi/Selects if needed.
3614 // The simple example looks as follows:
3615 // BB1:
3616 // p1 = b1 + 40
3617 // br cond BB2, BB3
3618 // BB2:
3619 // p2 = b2 + 40
3620 // br BB3
3621 // BB3:
3622 // p = phi [p1, BB1], [p2, BB2]
3623 // v = load p
3624 // Map is
3625 // p1 -> b1
3626 // p2 -> b2
3627 // Request is
3628 // p -> ?
3629 // The function tries to find or build phi [b1, BB1], [b2, BB2] in BB3.
3630 Value *findCommon(FoldAddrToValueMapping &Map) {
3631 // Tracks the simplification of newly created phi nodes. The reason we use
3632 // this mapping is because we will add new created Phi nodes in AddrToBase.
3633 // Simplification of Phi nodes is recursive, so some Phi node may
3634 // be simplified after we added it to AddrToBase. In reality this
3635 // simplification is possible only if original phi/selects were not
3636 // simplified yet.
3637 // Using this mapping we can find the current value in AddrToBase.
3638 SimplificationTracker ST(SQ);
3639
3640 // First step, DFS to create PHI nodes for all intermediate blocks.
3641 // Also fill traverse order for the second step.
3642 SmallVector<Value *, 32> TraverseOrder;
3643 InsertPlaceholders(Map, TraverseOrder, ST);
3644
3645 // Second Step, fill new nodes by merged values and simplify if possible.
3646 FillPlaceholders(Map, TraverseOrder, ST);
3647
3648 if (!AddrSinkNewSelects && ST.countNewSelectNodes() > 0) {
3649 ST.destroyNewNodes(CommonType);
3650 return nullptr;
3651 }
3652
3653 // Now we'd like to match New Phi nodes to existed ones.
3654 unsigned PhiNotMatchedCount = 0;
3655 if (!MatchPhiSet(ST, AddrSinkNewPhis, PhiNotMatchedCount)) {
3656 ST.destroyNewNodes(CommonType);
3657 return nullptr;
3658 }
3659
3660 auto *Result = ST.Get(Map.find(Original)->second);
3661 if (Result) {
3662 NumMemoryInstsPhiCreated += ST.countNewPhiNodes() + PhiNotMatchedCount;
3663 NumMemoryInstsSelectCreated += ST.countNewSelectNodes();
3664 }
3665 return Result;
3666 }
3667
3668 /// Try to match PHI node to Candidate.
3669 /// Matcher tracks the matched Phi nodes.
3670 bool MatchPhiNode(PHINode *PHI, PHINode *Candidate,
3671 SmallSetVector<PHIPair, 8> &Matcher,
3672 PhiNodeSet &PhiNodesToMatch) {
3673 SmallVector<PHIPair, 8> WorkList;
3674 Matcher.insert({ PHI, Candidate });
3675 SmallSet<PHINode *, 8> MatchedPHIs;
3676 MatchedPHIs.insert(PHI);
3677 WorkList.push_back({ PHI, Candidate });
3678 SmallSet<PHIPair, 8> Visited;
3679 while (!WorkList.empty()) {
3680 auto Item = WorkList.pop_back_val();
3681 if (!Visited.insert(Item).second)
3682 continue;
3683 // We iterate over all incoming values to Phi to compare them.
3684 // If values are different and both of them Phi and the first one is a
3685 // Phi we added (subject to match) and both of them is in the same basic
3686 // block then we can match our pair if values match. So we state that
3687 // these values match and add it to work list to verify that.
3688 for (auto *B : Item.first->blocks()) {
3689 Value *FirstValue = Item.first->getIncomingValueForBlock(B);
3690 Value *SecondValue = Item.second->getIncomingValueForBlock(B);
3691 if (FirstValue == SecondValue)
3692 continue;
3693
3694 PHINode *FirstPhi = dyn_cast<PHINode>(FirstValue);
3695 PHINode *SecondPhi = dyn_cast<PHINode>(SecondValue);
3696
3697 // One of them is not Phi or
3698 // The first one is not Phi node from the set we'd like to match or
3699 // Phi nodes from different basic blocks then
3700 // we will not be able to match.
3701 if (!FirstPhi || !SecondPhi || !PhiNodesToMatch.count(FirstPhi) ||
3702 FirstPhi->getParent() != SecondPhi->getParent())
3703 return false;
3704
3705 // If we already matched them then continue.
3706 if (Matcher.count({ FirstPhi, SecondPhi }))
3707 continue;
3708 // So the values are different and does not match. So we need them to
3709 // match. (But we register no more than one match per PHI node, so that
3710 // we won't later try to replace them twice.)
3711 if (MatchedPHIs.insert(FirstPhi).second)
3712 Matcher.insert({ FirstPhi, SecondPhi });
3713 // But me must check it.
3714 WorkList.push_back({ FirstPhi, SecondPhi });
3715 }
3716 }
3717 return true;
3718 }
3719
3720 /// For the given set of PHI nodes (in the SimplificationTracker) try
3721 /// to find their equivalents.
3722 /// Returns false if this matching fails and creation of new Phi is disabled.
3723 bool MatchPhiSet(SimplificationTracker &ST, bool AllowNewPhiNodes,
3724 unsigned &PhiNotMatchedCount) {
3725 // Matched and PhiNodesToMatch iterate their elements in a deterministic
3726 // order, so the replacements (ReplacePhi) are also done in a deterministic
3727 // order.
3728 SmallSetVector<PHIPair, 8> Matched;
3729 SmallPtrSet<PHINode *, 8> WillNotMatch;
3730 PhiNodeSet &PhiNodesToMatch = ST.newPhiNodes();
3731 while (PhiNodesToMatch.size()) {
3732 PHINode *PHI = *PhiNodesToMatch.begin();
3733
3734 // Add us, if no Phi nodes in the basic block we do not match.
3735 WillNotMatch.clear();
3736 WillNotMatch.insert(PHI);
3737
3738 // Traverse all Phis until we found equivalent or fail to do that.
3739 bool IsMatched = false;
3740 for (auto &P : PHI->getParent()->phis()) {
3741 // Skip new Phi nodes.
3742 if (PhiNodesToMatch.count(&P))
3743 continue;
3744 if ((IsMatched = MatchPhiNode(PHI, &P, Matched, PhiNodesToMatch)))
3745 break;
3746 // If it does not match, collect all Phi nodes from matcher.
3747 // if we end up with no match, them all these Phi nodes will not match
3748 // later.
3749 for (auto M : Matched)
3750 WillNotMatch.insert(M.first);
3751 Matched.clear();
3752 }
3753 if (IsMatched) {
3754 // Replace all matched values and erase them.
3755 for (auto MV : Matched)
3756 ST.ReplacePhi(MV.first, MV.second);
3757 Matched.clear();
3758 continue;
3759 }
3760 // If we are not allowed to create new nodes then bail out.
3761 if (!AllowNewPhiNodes)
3762 return false;
3763 // Just remove all seen values in matcher. They will not match anything.
3764 PhiNotMatchedCount += WillNotMatch.size();
3765 for (auto *P : WillNotMatch)
3766 PhiNodesToMatch.erase(P);
3767 }
3768 return true;
3769 }
3770 /// Fill the placeholders with values from predecessors and simplify them.
3771 void FillPlaceholders(FoldAddrToValueMapping &Map,
3772 SmallVectorImpl<Value *> &TraverseOrder,
3773 SimplificationTracker &ST) {
3774 while (!TraverseOrder.empty()) {
3775 Value *Current = TraverseOrder.pop_back_val();
3776 assert(Map.find(Current) != Map.end() && "No node to fill!!!")(static_cast <bool> (Map.find(Current) != Map.end() &&
"No node to fill!!!") ? void (0) : __assert_fail ("Map.find(Current) != Map.end() && \"No node to fill!!!\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 3776, __extension__ __PRETTY_FUNCTION__
))
;
3777 Value *V = Map[Current];
3778
3779 if (SelectInst *Select = dyn_cast<SelectInst>(V)) {
3780 // CurrentValue also must be Select.
3781 auto *CurrentSelect = cast<SelectInst>(Current);
3782 auto *TrueValue = CurrentSelect->getTrueValue();
3783 assert(Map.find(TrueValue) != Map.end() && "No True Value!")(static_cast <bool> (Map.find(TrueValue) != Map.end() &&
"No True Value!") ? void (0) : __assert_fail ("Map.find(TrueValue) != Map.end() && \"No True Value!\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 3783, __extension__ __PRETTY_FUNCTION__
))
;
3784 Select->setTrueValue(ST.Get(Map[TrueValue]));
3785 auto *FalseValue = CurrentSelect->getFalseValue();
3786 assert(Map.find(FalseValue) != Map.end() && "No False Value!")(static_cast <bool> (Map.find(FalseValue) != Map.end() &&
"No False Value!") ? void (0) : __assert_fail ("Map.find(FalseValue) != Map.end() && \"No False Value!\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 3786, __extension__ __PRETTY_FUNCTION__
))
;
3787 Select->setFalseValue(ST.Get(Map[FalseValue]));
3788 } else {
3789 // Must be a Phi node then.
3790 auto *PHI = cast<PHINode>(V);
3791 // Fill the Phi node with values from predecessors.
3792 for (auto *B : predecessors(PHI->getParent())) {
3793 Value *PV = cast<PHINode>(Current)->getIncomingValueForBlock(B);
3794 assert(Map.find(PV) != Map.end() && "No predecessor Value!")(static_cast <bool> (Map.find(PV) != Map.end() &&
"No predecessor Value!") ? void (0) : __assert_fail ("Map.find(PV) != Map.end() && \"No predecessor Value!\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 3794, __extension__ __PRETTY_FUNCTION__
))
;
3795 PHI->addIncoming(ST.Get(Map[PV]), B);
3796 }
3797 }
3798 Map[Current] = ST.Simplify(V);
3799 }
3800 }
3801
3802 /// Starting from original value recursively iterates over def-use chain up to
3803 /// known ending values represented in a map. For each traversed phi/select
3804 /// inserts a placeholder Phi or Select.
3805 /// Reports all new created Phi/Select nodes by adding them to set.
3806 /// Also reports and order in what values have been traversed.
3807 void InsertPlaceholders(FoldAddrToValueMapping &Map,
3808 SmallVectorImpl<Value *> &TraverseOrder,
3809 SimplificationTracker &ST) {
3810 SmallVector<Value *, 32> Worklist;
3811 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", 3812, __extension__ __PRETTY_FUNCTION__
))
3812 "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", 3812, __extension__ __PRETTY_FUNCTION__
))
;
3813 auto *Dummy = PoisonValue::get(CommonType);
3814 Worklist.push_back(Original);
3815 while (!Worklist.empty()) {
3816 Value *Current = Worklist.pop_back_val();
3817 // if it is already visited or it is an ending value then skip it.
3818 if (Map.find(Current) != Map.end())
3819 continue;
3820 TraverseOrder.push_back(Current);
3821
3822 // CurrentValue must be a Phi node or select. All others must be covered
3823 // by anchors.
3824 if (SelectInst *CurrentSelect = dyn_cast<SelectInst>(Current)) {
3825 // Is it OK to get metadata from OrigSelect?!
3826 // Create a Select placeholder with dummy value.
3827 SelectInst *Select = SelectInst::Create(
3828 CurrentSelect->getCondition(), Dummy, Dummy,
3829 CurrentSelect->getName(), CurrentSelect, CurrentSelect);
3830 Map[Current] = Select;
3831 ST.insertNewSelect(Select);
3832 // We are interested in True and False values.
3833 Worklist.push_back(CurrentSelect->getTrueValue());
3834 Worklist.push_back(CurrentSelect->getFalseValue());
3835 } else {
3836 // It must be a Phi node then.
3837 PHINode *CurrentPhi = cast<PHINode>(Current);
3838 unsigned PredCount = CurrentPhi->getNumIncomingValues();
3839 PHINode *PHI =
3840 PHINode::Create(CommonType, PredCount, "sunk_phi", CurrentPhi);
3841 Map[Current] = PHI;
3842 ST.insertNewPhi(PHI);
3843 append_range(Worklist, CurrentPhi->incoming_values());
3844 }
3845 }
3846 }
3847
3848 bool addrModeCombiningAllowed() {
3849 if (DisableComplexAddrModes)
3850 return false;
3851 switch (DifferentField) {
3852 default:
3853 return false;
3854 case ExtAddrMode::BaseRegField:
3855 return AddrSinkCombineBaseReg;
3856 case ExtAddrMode::BaseGVField:
3857 return AddrSinkCombineBaseGV;
3858 case ExtAddrMode::BaseOffsField:
3859 return AddrSinkCombineBaseOffs;
3860 case ExtAddrMode::ScaledRegField:
3861 return AddrSinkCombineScaledReg;
3862 }
3863 }
3864};
3865} // end anonymous namespace
3866
3867/// Try adding ScaleReg*Scale to the current addressing mode.
3868/// Return true and update AddrMode if this addr mode is legal for the target,
3869/// false if not.
3870bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
3871 unsigned Depth) {
3872 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
3873 // mode. Just process that directly.
3874 if (Scale == 1)
3875 return matchAddr(ScaleReg, Depth);
3876
3877 // If the scale is 0, it takes nothing to add this.
3878 if (Scale == 0)
3879 return true;
3880
3881 // If we already have a scale of this value, we can add to it, otherwise, we
3882 // need an available scale field.
3883 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
3884 return false;
3885
3886 ExtAddrMode TestAddrMode = AddrMode;
3887
3888 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
3889 // [A+B + A*7] -> [B+A*8].
3890 TestAddrMode.Scale += Scale;
3891 TestAddrMode.ScaledReg = ScaleReg;
3892
3893 // If the new address isn't legal, bail out.
3894 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
3895 return false;
3896
3897 // It was legal, so commit it.
3898 AddrMode = TestAddrMode;
3899
3900 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
3901 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
3902 // X*Scale + C*Scale to addr mode. If we found available IV increment, do not
3903 // go any further: we can reuse it and cannot eliminate it.
3904 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
3905 if (isa<Instruction>(ScaleReg) && // not a constant expr.
3906 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI))) &&
3907 !isIVIncrement(ScaleReg, &LI) && CI->getValue().isSignedIntN(64)) {
3908 TestAddrMode.InBounds = false;
3909 TestAddrMode.ScaledReg = AddLHS;
3910 TestAddrMode.BaseOffs += CI->getSExtValue() * TestAddrMode.Scale;
3911
3912 // If this addressing mode is legal, commit it and remember that we folded
3913 // this instruction.
3914 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
3915 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
3916 AddrMode = TestAddrMode;
3917 return true;
3918 }
3919 // Restore status quo.
3920 TestAddrMode = AddrMode;
3921 }
3922
3923 // If this is an add recurrence with a constant step, return the increment
3924 // instruction and the canonicalized step.
3925 auto GetConstantStep = [this](const Value * V)
3926 ->Optional<std::pair<Instruction *, APInt> > {
3927 auto *PN = dyn_cast<PHINode>(V);
3928 if (!PN)
3929 return None;
3930 auto IVInc = getIVIncrement(PN, &LI);
3931 if (!IVInc)
3932 return None;
3933 // TODO: The result of the intrinsics above is two-compliment. However when
3934 // IV inc is expressed as add or sub, iv.next is potentially a poison value.
3935 // If it has nuw or nsw flags, we need to make sure that these flags are
3936 // inferrable at the point of memory instruction. Otherwise we are replacing
3937 // well-defined two-compliment computation with poison. Currently, to avoid
3938 // potentially complex analysis needed to prove this, we reject such cases.
3939 if (auto *OIVInc = dyn_cast<OverflowingBinaryOperator>(IVInc->first))
3940 if (OIVInc->hasNoSignedWrap() || OIVInc->hasNoUnsignedWrap())
3941 return None;
3942 if (auto *ConstantStep = dyn_cast<ConstantInt>(IVInc->second))
3943 return std::make_pair(IVInc->first, ConstantStep->getValue());
3944 return None;
3945 };
3946
3947 // Try to account for the following special case:
3948 // 1. ScaleReg is an inductive variable;
3949 // 2. We use it with non-zero offset;
3950 // 3. IV's increment is available at the point of memory instruction.
3951 //
3952 // In this case, we may reuse the IV increment instead of the IV Phi to
3953 // achieve the following advantages:
3954 // 1. If IV step matches the offset, we will have no need in the offset;
3955 // 2. Even if they don't match, we will reduce the overlap of living IV
3956 // and IV increment, that will potentially lead to better register
3957 // assignment.
3958 if (AddrMode.BaseOffs) {
3959 if (auto IVStep = GetConstantStep(ScaleReg)) {
3960 Instruction *IVInc = IVStep->first;
3961 // The following assert is important to ensure a lack of infinite loops.
3962 // This transforms is (intentionally) the inverse of the one just above.
3963 // If they don't agree on the definition of an increment, we'd alternate
3964 // back and forth indefinitely.
3965 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", 3965, __extension__ __PRETTY_FUNCTION__
))
;
3966 APInt Step = IVStep->second;
3967 APInt Offset = Step * AddrMode.Scale;
3968 if (Offset.isSignedIntN(64)) {
3969 TestAddrMode.InBounds = false;
3970 TestAddrMode.ScaledReg = IVInc;
3971 TestAddrMode.BaseOffs -= Offset.getLimitedValue();
3972 // If this addressing mode is legal, commit it..
3973 // (Note that we defer the (expensive) domtree base legality check
3974 // to the very last possible point.)
3975 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace) &&
3976 getDTFn().dominates(IVInc, MemoryInst)) {
3977 AddrModeInsts.push_back(cast<Instruction>(IVInc));
3978 AddrMode = TestAddrMode;
3979 return true;
3980 }
3981 // Restore status quo.
3982 TestAddrMode = AddrMode;
3983 }
3984 }
3985 }
3986
3987 // Otherwise, just return what we have.
3988 return true;
3989}
3990
3991/// This is a little filter, which returns true if an addressing computation
3992/// involving I might be folded into a load/store accessing it.
3993/// This doesn't need to be perfect, but needs to accept at least
3994/// the set of instructions that MatchOperationAddr can.
3995static bool MightBeFoldableInst(Instruction *I) {
3996 switch (I->getOpcode()) {
3997 case Instruction::BitCast:
3998 case Instruction::AddrSpaceCast:
3999 // Don't touch identity bitcasts.
4000 if (I->getType() == I->getOperand(0)->getType())
4001 return false;
4002 return I->getType()->isIntOrPtrTy();
4003 case Instruction::PtrToInt:
4004 // PtrToInt is always a noop, as we know that the int type is pointer sized.
4005 return true;
4006 case Instruction::IntToPtr:
4007 // We know the input is intptr_t, so this is foldable.
4008 return true;
4009 case Instruction::Add:
4010 return true;
4011 case Instruction::Mul:
4012 case Instruction::Shl:
4013 // Can only handle X*C and X << C.
4014 return isa<ConstantInt>(I->getOperand(1));
4015 case Instruction::GetElementPtr:
4016 return true;
4017 default:
4018 return false;
4019 }
4020}
4021
4022/// Check whether or not \p Val is a legal instruction for \p TLI.
4023/// \note \p Val is assumed to be the product of some type promotion.
4024/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
4025/// to be legal, as the non-promoted value would have had the same state.
4026static bool isPromotedInstructionLegal(const TargetLowering &TLI,
4027 const DataLayout &DL, Value *Val) {
4028 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
4029 if (!PromotedInst)
4030 return false;
4031 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
4032 // If the ISDOpcode is undefined, it was undefined before the promotion.
4033 if (!ISDOpcode)
4034 return true;
4035 // Otherwise, check if the promoted instruction is legal or not.
4036 return TLI.isOperationLegalOrCustom(
4037 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
4038}
4039
4040namespace {
4041
4042/// Hepler class to perform type promotion.
4043class TypePromotionHelper {
4044 /// Utility function to add a promoted instruction \p ExtOpnd to
4045 /// \p PromotedInsts and record the type of extension we have seen.
4046 static void addPromotedInst(InstrToOrigTy &PromotedInsts,
4047 Instruction *ExtOpnd,
4048 bool IsSExt) {
4049 ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension;
4050 InstrToOrigTy::iterator It = PromotedInsts.find(ExtOpnd);
4051 if (It != PromotedInsts.end()) {
4052 // If the new extension is same as original, the information in
4053 // PromotedInsts[ExtOpnd] is still correct.
4054 if (It->second.getInt() == ExtTy)
4055 return;
4056
4057 // Now the new extension is different from old extension, we make
4058 // the type information invalid by setting extension type to
4059 // BothExtension.
4060 ExtTy = BothExtension;
4061 }
4062 PromotedInsts[ExtOpnd] = TypeIsSExt(ExtOpnd->getType(), ExtTy);
4063 }
4064
4065 /// Utility function to query the original type of instruction \p Opnd
4066 /// with a matched extension type. If the extension doesn't match, we
4067 /// cannot use the information we had on the original type.
4068 /// BothExtension doesn't match any extension type.
4069 static const Type *getOrigType(const InstrToOrigTy &PromotedInsts,
4070 Instruction *Opnd,
4071 bool IsSExt) {
4072 ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension;
4073 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
4074 if (It != PromotedInsts.end() && It->second.getInt() == ExtTy)
4075 return It->second.getPointer();
4076 return nullptr;
4077 }
4078
4079 /// Utility function to check whether or not a sign or zero extension
4080 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
4081 /// either using the operands of \p Inst or promoting \p Inst.
4082 /// The type of the extension is defined by \p IsSExt.
4083 /// In other words, check if:
4084 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
4085 /// #1 Promotion applies:
4086 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
4087 /// #2 Operand reuses:
4088 /// ext opnd1 to ConsideredExtType.
4089 /// \p PromotedInsts maps the instructions to their type before promotion.
4090 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
4091 const InstrToOrigTy &PromotedInsts, bool IsSExt);
4092
4093 /// Utility function to determine if \p OpIdx should be promoted when
4094 /// promoting \p Inst.
4095 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
4096 return !(isa<SelectInst>(Inst) && OpIdx == 0);
4097 }
4098
4099 /// Utility function to promote the operand of \p Ext when this
4100 /// operand is a promotable trunc or sext or zext.
4101 /// \p PromotedInsts maps the instructions to their type before promotion.
4102 /// \p CreatedInstsCost[out] contains the cost of all instructions
4103 /// created to promote the operand of Ext.
4104 /// Newly added extensions are inserted in \p Exts.
4105 /// Newly added truncates are inserted in \p Truncs.
4106 /// Should never be called directly.
4107 /// \return The promoted value which is used instead of Ext.
4108 static Value *promoteOperandForTruncAndAnyExt(
4109 Instruction *Ext, TypePromotionTransaction &TPT,
4110 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4111 SmallVectorImpl<Instruction *> *Exts,
4112 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
4113
4114 /// Utility function to promote the operand of \p Ext when this
4115 /// operand is promotable and is not a supported trunc or sext.
4116 /// \p PromotedInsts maps the instructions to their type before promotion.
4117 /// \p CreatedInstsCost[out] contains the cost of all the instructions
4118 /// created to promote the operand of Ext.
4119 /// Newly added extensions are inserted in \p Exts.
4120 /// Newly added truncates are inserted in \p Truncs.
4121 /// Should never be called directly.
4122 /// \return The promoted value which is used instead of Ext.
4123 static Value *promoteOperandForOther(Instruction *Ext,
4124 TypePromotionTransaction &TPT,
4125 InstrToOrigTy &PromotedInsts,
4126 unsigned &CreatedInstsCost,
4127 SmallVectorImpl<Instruction *> *Exts,
4128 SmallVectorImpl<Instruction *> *Truncs,
4129 const TargetLowering &TLI, bool IsSExt);
4130
4131 /// \see promoteOperandForOther.
4132 static Value *signExtendOperandForOther(
4133 Instruction *Ext, TypePromotionTransaction &TPT,
4134 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4135 SmallVectorImpl<Instruction *> *Exts,
4136 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
4137 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
4138 Exts, Truncs, TLI, true);
4139 }
4140
4141 /// \see promoteOperandForOther.
4142 static Value *zeroExtendOperandForOther(
4143 Instruction *Ext, TypePromotionTransaction &TPT,
4144 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4145 SmallVectorImpl<Instruction *> *Exts,
4146 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
4147 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
4148 Exts, Truncs, TLI, false);
4149 }
4150
4151public:
4152 /// Type for the utility function that promotes the operand of Ext.
4153 using Action = Value *(*)(Instruction *Ext, TypePromotionTransaction &TPT,
4154 InstrToOrigTy &PromotedInsts,
4155 unsigned &CreatedInstsCost,
4156 SmallVectorImpl<Instruction *> *Exts,
4157 SmallVectorImpl<Instruction *> *Truncs,
4158 const TargetLowering &TLI);
4159
4160 /// Given a sign/zero extend instruction \p Ext, return the appropriate
4161 /// action to promote the operand of \p Ext instead of using Ext.
4162 /// \return NULL if no promotable action is possible with the current
4163 /// sign extension.
4164 /// \p InsertedInsts keeps track of all the instructions inserted by the
4165 /// other CodeGenPrepare optimizations. This information is important
4166 /// because we do not want to promote these instructions as CodeGenPrepare
4167 /// will reinsert them later. Thus creating an infinite loop: create/remove.
4168 /// \p PromotedInsts maps the instructions to their type before promotion.
4169 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
4170 const TargetLowering &TLI,
4171 const InstrToOrigTy &PromotedInsts);
4172};
4173
4174} // end anonymous namespace
4175
4176bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
4177 Type *ConsideredExtType,
4178 const InstrToOrigTy &PromotedInsts,
4179 bool IsSExt) {
4180 // The promotion helper does not know how to deal with vector types yet.
4181 // To be able to fix that, we would need to fix the places where we
4182 // statically extend, e.g., constants and such.
4183 if (Inst->getType()->isVectorTy())
4184 return false;
4185
4186 // We can always get through zext.
4187 if (isa<ZExtInst>(Inst))
4188 return true;
4189
4190 // sext(sext) is ok too.
4191 if (IsSExt && isa<SExtInst>(Inst))
4192 return true;
4193
4194 // We can get through binary operator, if it is legal. In other words, the
4195 // binary operator must have a nuw or nsw flag.
4196 if (const auto *BinOp = dyn_cast<BinaryOperator>(Inst))
4197 if (isa<OverflowingBinaryOperator>(BinOp) &&
4198 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
4199 (IsSExt && BinOp->hasNoSignedWrap())))
4200 return true;
4201
4202 // ext(and(opnd, cst)) --> and(ext(opnd), ext(cst))
4203 if ((Inst->getOpcode() == Instruction::And ||
4204 Inst->getOpcode() == Instruction::Or))
4205 return true;
4206
4207 // ext(xor(opnd, cst)) --> xor(ext(opnd), ext(cst))
4208 if (Inst->getOpcode() == Instruction::Xor) {
4209 // Make sure it is not a NOT.
4210 if (const auto *Cst = dyn_cast<ConstantInt>(Inst->getOperand(1)))
4211 if (!Cst->getValue().isAllOnes())
4212 return true;
4213 }
4214
4215 // zext(shrl(opnd, cst)) --> shrl(zext(opnd), zext(cst))
4216 // It may change a poisoned value into a regular value, like
4217 // zext i32 (shrl i8 %val, 12) --> shrl i32 (zext i8 %val), 12
4218 // poisoned value regular value
4219 // It should be OK since undef covers valid value.
4220 if (Inst->getOpcode() == Instruction::LShr && !IsSExt)
4221 return true;
4222
4223 // and(ext(shl(opnd, cst)), cst) --> and(shl(ext(opnd), ext(cst)), cst)
4224 // It may change a poisoned value into a regular value, like
4225 // zext i32 (shl i8 %val, 12) --> shl i32 (zext i8 %val), 12
4226 // poisoned value regular value
4227 // It should be OK since undef covers valid value.
4228 if (Inst->getOpcode() == Instruction::Shl && Inst->hasOneUse()) {
4229 const auto *ExtInst = cast<const Instruction>(*Inst->user_begin());
4230 if (ExtInst->hasOneUse()) {
4231 const auto *AndInst = dyn_cast<const Instruction>(*ExtInst->user_begin());
4232 if (AndInst && AndInst->getOpcode() == Instruction::And) {
4233 const auto *Cst = dyn_cast<ConstantInt>(AndInst->getOperand(1));
4234 if (Cst &&
4235 Cst->getValue().isIntN(Inst->getType()->getIntegerBitWidth()))
4236 return true;
4237 }
4238 }
4239 }
4240
4241 // Check if we can do the following simplification.
4242 // ext(trunc(opnd)) --> ext(opnd)
4243 if (!isa<TruncInst>(Inst))
4244 return false;
4245
4246 Value *OpndVal = Inst->getOperand(0);
4247 // Check if we can use this operand in the extension.
4248 // If the type is larger than the result type of the extension, we cannot.
4249 if (!OpndVal->getType()->isIntegerTy() ||
4250 OpndVal->getType()->getIntegerBitWidth() >
4251 ConsideredExtType->getIntegerBitWidth())
4252 return false;
4253
4254 // If the operand of the truncate is not an instruction, we will not have
4255 // any information on the dropped bits.
4256 // (Actually we could for constant but it is not worth the extra logic).
4257 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
4258 if (!Opnd)
4259 return false;
4260
4261 // Check if the source of the type is narrow enough.
4262 // I.e., check that trunc just drops extended bits of the same kind of
4263 // the extension.
4264 // #1 get the type of the operand and check the kind of the extended bits.
4265 const Type *OpndType = getOrigType(PromotedInsts, Opnd, IsSExt);
4266 if (OpndType)
4267 ;
4268 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
4269 OpndType = Opnd->getOperand(0)->getType();
4270 else
4271 return false;
4272
4273 // #2 check that the truncate just drops extended bits.
4274 return Inst->getType()->getIntegerBitWidth() >=
4275 OpndType->getIntegerBitWidth();
4276}
4277
4278TypePromotionHelper::Action TypePromotionHelper::getAction(
4279 Instruction *Ext, const SetOfInstrs &InsertedInsts,
4280 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
4281 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", 4282, __extension__ __PRETTY_FUNCTION__
))
4282 "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", 4282, __extension__ __PRETTY_FUNCTION__
))
;
4283 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
4284 Type *ExtTy = Ext->getType();
4285 bool IsSExt = isa<SExtInst>(Ext);
4286 // If the operand of the extension is not an instruction, we cannot
4287 // get through.
4288 // If it, check we can get through.
4289 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
4290 return nullptr;
4291
4292 // Do not promote if the operand has been added by codegenprepare.
4293 // Otherwise, it means we are undoing an optimization that is likely to be
4294 // redone, thus causing potential infinite loop.
4295 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
4296 return nullptr;
4297
4298 // SExt or Trunc instructions.
4299 // Return the related handler.
4300 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
4301 isa<ZExtInst>(ExtOpnd))
4302 return promoteOperandForTruncAndAnyExt;
4303
4304 // Regular instruction.
4305 // Abort early if we will have to insert non-free instructions.
4306 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
4307 return nullptr;
4308 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
4309}
4310
4311Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
4312 Instruction *SExt, TypePromotionTransaction &TPT,
4313 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4314 SmallVectorImpl<Instruction *> *Exts,
4315 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
4316 // By construction, the operand of SExt is an instruction. Otherwise we cannot
4317 // get through it and this method should not be called.
4318 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
4319 Value *ExtVal = SExt;
4320 bool HasMergedNonFreeExt = false;
4321 if (isa<ZExtInst>(SExtOpnd)) {
4322 // Replace s|zext(zext(opnd))
4323 // => zext(opnd).
4324 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
4325 Value *ZExt =
4326 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
4327 TPT.replaceAllUsesWith(SExt, ZExt);
4328 TPT.eraseInstruction(SExt);
4329 ExtVal = ZExt;
4330 } else {
4331 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
4332 // => z|sext(opnd).
4333 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
4334 }
4335 CreatedInstsCost = 0;
4336
4337 // Remove dead code.
4338 if (SExtOpnd->use_empty())
4339 TPT.eraseInstruction(SExtOpnd);
4340
4341 // Check if the extension is still needed.
4342 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
4343 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
4344 if (ExtInst) {
4345 if (Exts)
4346 Exts->push_back(ExtInst);
4347 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
4348 }
4349 return ExtVal;
4350 }
4351
4352 // At this point we have: ext ty opnd to ty.
4353 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
4354 Value *NextVal = ExtInst->getOperand(0);
4355 TPT.eraseInstruction(ExtInst, NextVal);
4356 return NextVal;
4357}
4358
4359Value *TypePromotionHelper::promoteOperandForOther(
4360 Instruction *Ext, TypePromotionTransaction &TPT,
4361 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4362 SmallVectorImpl<Instruction *> *Exts,
4363 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
4364 bool IsSExt) {
4365 // By construction, the operand of Ext is an instruction. Otherwise we cannot
4366 // get through it and this method should not be called.
4367 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
4368 CreatedInstsCost = 0;
4369 if (!ExtOpnd->hasOneUse()) {
4370 // ExtOpnd will be promoted.
4371 // All its uses, but Ext, will need to use a truncated value of the
4372 // promoted version.
4373 // Create the truncate now.
4374 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
4375 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
4376 // Insert it just after the definition.
4377 ITrunc->moveAfter(ExtOpnd);
4378 if (Truncs)
4379 Truncs->push_back(ITrunc);
4380 }
4381
4382 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
4383 // Restore the operand of Ext (which has been replaced by the previous call
4384 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
4385 TPT.setOperand(Ext, 0, ExtOpnd);
4386 }
4387
4388 // Get through the Instruction:
4389 // 1. Update its type.
4390 // 2. Replace the uses of Ext by Inst.
4391 // 3. Extend each operand that needs to be extended.
4392
4393 // Remember the original type of the instruction before promotion.
4394 // This is useful to know that the high bits are sign extended bits.
4395 addPromotedInst(PromotedInsts, ExtOpnd, IsSExt);
4396 // Step #1.
4397 TPT.mutateType(ExtOpnd, Ext->getType());
4398 // Step #2.
4399 TPT.replaceAllUsesWith(Ext, ExtOpnd);
4400 // Step #3.
4401 Instruction *ExtForOpnd = Ext;
4402
4403 LLVM_DEBUG(dbgs() << "Propagate Ext to operands\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Propagate Ext to operands\n"
; } } while (false)
;
4404 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
4405 ++OpIdx) {
4406 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
)
;
4407 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
4408 !shouldExtOperand(ExtOpnd, OpIdx)) {
4409 LLVM_DEBUG(dbgs() << "No need to propagate\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "No need to propagate\n"
; } } while (false)
;
4410 continue;
4411 }
4412 // Check if we can statically extend the operand.
4413 Value *Opnd = ExtOpnd->getOperand(OpIdx);
4414 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
4415 LLVM_DEBUG(dbgs() << "Statically extend\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Statically extend\n"; }
} while (false)
;
4416 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
4417 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
4418 : Cst->getValue().zext(BitWidth);
4419 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
4420 continue;
4421 }
4422 // UndefValue are typed, so we have to statically sign extend them.
4423 if (isa<UndefValue>(Opnd)) {
4424 LLVM_DEBUG(dbgs() << "Statically extend\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Statically extend\n"; }
} while (false)
;
4425 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
4426 continue;
4427 }
4428
4429 // Otherwise we have to explicitly sign extend the operand.
4430 // Check if Ext was reused to extend an operand.
4431 if (!ExtForOpnd) {
4432 // If yes, create a new one.
4433 LLVM_DEBUG(dbgs() << "More operands to ext\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "More operands to ext\n"
; } } while (false)
;
4434 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
4435 : TPT.createZExt(Ext, Opnd, Ext->getType());
4436 if (!isa<Instruction>(ValForExtOpnd)) {
4437 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
4438 continue;
4439 }
4440 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
4441 }
4442 if (Exts)
4443 Exts->push_back(ExtForOpnd);
4444 TPT.setOperand(ExtForOpnd, 0, Opnd);
4445
4446 // Move the sign extension before the insertion point.
4447 TPT.moveBefore(ExtForOpnd, ExtOpnd);
4448 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
4449 CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
4450 // If more sext are required, new instructions will have to be created.
4451 ExtForOpnd = nullptr;
4452 }
4453 if (ExtForOpnd == Ext) {
4454 LLVM_DEBUG(dbgs() << "Extension is useless now\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Extension is useless now\n"
; } } while (false)
;
4455 TPT.eraseInstruction(Ext);
4456 }
4457 return ExtOpnd;
4458}
4459
4460/// Check whether or not promoting an instruction to a wider type is profitable.
4461/// \p NewCost gives the cost of extension instructions created by the
4462/// promotion.
4463/// \p OldCost gives the cost of extension instructions before the promotion
4464/// plus the number of instructions that have been
4465/// matched in the addressing mode the promotion.
4466/// \p PromotedOperand is the value that has been promoted.
4467/// \return True if the promotion is profitable, false otherwise.
4468bool AddressingModeMatcher::isPromotionProfitable(
4469 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
4470 LLVM_DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCostdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "OldCost: " << OldCost
<< "\tNewCost: " << NewCost << '\n'; } } while
(false)
4471 << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "OldCost: " << OldCost
<< "\tNewCost: " << NewCost << '\n'; } } while
(false)
;
4472 // The cost of the new extensions is greater than the cost of the
4473 // old extension plus what we folded.
4474 // This is not profitable.
4475 if (NewCost > OldCost)
4476 return false;
4477 if (NewCost < OldCost)
4478 return true;
4479 // The promotion is neutral but it may help folding the sign extension in
4480 // loads for instance.
4481 // Check that we did not create an illegal instruction.
4482 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
4483}
4484
4485/// Given an instruction or constant expr, see if we can fold the operation
4486/// into the addressing mode. If so, update the addressing mode and return
4487/// true, otherwise return false without modifying AddrMode.
4488/// If \p MovedAway is not NULL, it contains the information of whether or
4489/// not AddrInst has to be folded into the addressing mode on success.
4490/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
4491/// because it has been moved away.
4492/// Thus AddrInst must not be added in the matched instructions.
4493/// This state can happen when AddrInst is a sext, since it may be moved away.
4494/// Therefore, AddrInst may not be valid when MovedAway is true and it must
4495/// not be referenced anymore.
4496bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
4497 unsigned Depth,
4498 bool *MovedAway) {
4499 // Avoid exponential behavior on extremely deep expression trees.
4500 if (Depth >= 5) return false;
4501
4502 // By default, all matched instructions stay in place.
4503 if (MovedAway)
4504 *MovedAway = false;
4505
4506 switch (Opcode) {
4507 case Instruction::PtrToInt:
4508 // PtrToInt is always a noop, as we know that the int type is pointer sized.
4509 return matchAddr(AddrInst->getOperand(0), Depth);
4510 case Instruction::IntToPtr: {
4511 auto AS = AddrInst->getType()->getPointerAddressSpace();
4512 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
4513 // This inttoptr is a no-op if the integer type is pointer sized.
4514 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
4515 return matchAddr(AddrInst->getOperand(0), Depth);
4516 return false;
4517 }
4518 case Instruction::BitCast:
4519 // BitCast is always a noop, and we can handle it as long as it is
4520 // int->int or pointer->pointer (we don't want int<->fp or something).
4521 if (AddrInst->getOperand(0)->getType()->isIntOrPtrTy() &&
4522 // Don't touch identity bitcasts. These were probably put here by LSR,
4523 // and we don't want to mess around with them. Assume it knows what it
4524 // is doing.
4525 AddrInst->getOperand(0)->getType() != AddrInst->getType())
4526 return matchAddr(AddrInst->getOperand(0), Depth);
4527 return false;
4528 case Instruction::AddrSpaceCast: {
4529 unsigned SrcAS
4530 = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
4531 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
4532 if (TLI.getTargetMachine().isNoopAddrSpaceCast(SrcAS, DestAS))
4533 return matchAddr(AddrInst->getOperand(0), Depth);
4534 return false;
4535 }
4536 case Instruction::Add: {
4537 // Check to see if we can merge in the RHS then the LHS. If so, we win.
4538 ExtAddrMode BackupAddrMode = AddrMode;
4539 unsigned OldSize = AddrModeInsts.size();
4540 // Start a transaction at this point.
4541 // The LHS may match but not the RHS.
4542 // Therefore, we need a higher level restoration point to undo partially
4543 // matched operation.
4544 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4545 TPT.getRestorationPoint();
4546
4547 AddrMode.InBounds = false;
4548 if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
4549 matchAddr(AddrInst->getOperand(0), Depth+1))
4550 return true;
4551
4552 // Restore the old addr mode info.
4553 AddrMode = BackupAddrMode;
4554 AddrModeInsts.resize(OldSize);
4555 TPT.rollback(LastKnownGood);
4556
4557 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
4558 if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
4559 matchAddr(AddrInst->getOperand(1), Depth+1))
4560 return true;
4561
4562 // Otherwise we definitely can't merge the ADD in.
4563 AddrMode = BackupAddrMode;
4564 AddrModeInsts.resize(OldSize);
4565 TPT.rollback(LastKnownGood);
4566 break;
4567 }
4568 //case Instruction::Or:
4569 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
4570 //break;
4571 case Instruction::Mul:
4572 case Instruction::Shl: {
4573 // Can only handle X*C and X << C.
4574 AddrMode.InBounds = false;
4575 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
4576 if (!RHS || RHS->getBitWidth() > 64)
4577 return false;
4578 int64_t Scale = Opcode == Instruction::Shl
4579 ? 1LL << RHS->getLimitedValue(RHS->getBitWidth() - 1)
4580 : RHS->getSExtValue();
4581
4582 return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
4583 }
4584 case Instruction::GetElementPtr: {
4585 // Scan the GEP. We check it if it contains constant offsets and at most
4586 // one variable offset.
4587 int VariableOperand = -1;
4588 unsigned VariableScale = 0;
4589
4590 int64_t ConstantOffset = 0;
4591 gep_type_iterator GTI = gep_type_begin(AddrInst);
4592 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
4593 if (StructType *STy = GTI.getStructTypeOrNull()) {
4594 const StructLayout *SL = DL.getStructLayout(STy);
4595 unsigned Idx =
4596 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
4597 ConstantOffset += SL->getElementOffset(Idx);
4598 } else {
4599 TypeSize TS = DL.getTypeAllocSize(GTI.getIndexedType());
4600 if (TS.isNonZero()) {
4601 // The optimisations below currently only work for fixed offsets.
4602 if (TS.isScalable())
4603 return false;
4604 int64_t TypeSize = TS.getFixedSize();
4605 if (ConstantInt *CI =
4606 dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
4607 const APInt &CVal = CI->getValue();
4608 if (CVal.getMinSignedBits() <= 64) {
4609 ConstantOffset += CVal.getSExtValue() * TypeSize;
4610 continue;
4611 }
4612 }
4613 // We only allow one variable index at the moment.
4614 if (VariableOperand != -1)
4615 return false;
4616
4617 // Remember the variable index.
4618 VariableOperand = i;
4619 VariableScale = TypeSize;
4620 }
4621 }
4622 }
4623
4624 // A common case is for the GEP to only do a constant offset. In this case,
4625 // just add it to the disp field and check validity.
4626 if (VariableOperand == -1) {
4627 AddrMode.BaseOffs += ConstantOffset;
4628 if (ConstantOffset == 0 ||
4629 TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
4630 // Check to see if we can fold the base pointer in too.
4631 if (matchAddr(AddrInst->getOperand(0), Depth+1)) {
4632 if (!cast<GEPOperator>(AddrInst)->isInBounds())
4633 AddrMode.InBounds = false;
4634 return true;
4635 }
4636 } else if (EnableGEPOffsetSplit && isa<GetElementPtrInst>(AddrInst) &&
4637 TLI.shouldConsiderGEPOffsetSplit() && Depth == 0 &&
4638 ConstantOffset > 0) {
4639 // Record GEPs with non-zero offsets as candidates for splitting in the
4640 // event that the offset cannot fit into the r+i addressing mode.
4641 // Simple and common case that only one GEP is used in calculating the
4642 // address for the memory access.
4643 Value *Base = AddrInst->getOperand(0);
4644 auto *BaseI = dyn_cast<Instruction>(Base);
4645 auto *GEP = cast<GetElementPtrInst>(AddrInst);
4646 if (isa<Argument>(Base) || isa<GlobalValue>(Base) ||
4647 (BaseI && !isa<CastInst>(BaseI) &&
4648 !isa<GetElementPtrInst>(BaseI))) {
4649 // Make sure the parent block allows inserting non-PHI instructions
4650 // before the terminator.
4651 BasicBlock *Parent =
4652 BaseI ? BaseI->getParent() : &GEP->getFunction()->getEntryBlock();
4653 if (!Parent->getTerminator()->isEHPad())
4654 LargeOffsetGEP = std::make_pair(GEP, ConstantOffset);
4655 }
4656 }
4657 AddrMode.BaseOffs -= ConstantOffset;
4658 return false;
4659 }
4660
4661 // Save the valid addressing mode in case we can't match.
4662 ExtAddrMode BackupAddrMode = AddrMode;
4663 unsigned OldSize = AddrModeInsts.size();
4664
4665 // See if the scale and offset amount is valid for this target.
4666 AddrMode.BaseOffs += ConstantOffset;
4667 if (!cast<GEPOperator>(AddrInst)->isInBounds())
4668 AddrMode.InBounds = false;
4669
4670 // Match the base operand of the GEP.
4671 if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
4672 // If it couldn't be matched, just stuff the value in a register.
4673 if (AddrMode.HasBaseReg) {
4674 AddrMode = BackupAddrMode;
4675 AddrModeInsts.resize(OldSize);
4676 return false;
4677 }
4678 AddrMode.HasBaseReg = true;
4679 AddrMode.BaseReg = AddrInst->getOperand(0);
4680 }
4681
4682 // Match the remaining variable portion of the GEP.
4683 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
4684 Depth)) {
4685 // If it couldn't be matched, try stuffing the base into a register
4686 // instead of matching it, and retrying the match of the scale.
4687 AddrMode = BackupAddrMode;
4688 AddrModeInsts.resize(OldSize);
4689 if (AddrMode.HasBaseReg)
4690 return false;
4691 AddrMode.HasBaseReg = true;
4692 AddrMode.BaseReg = AddrInst->getOperand(0);
4693 AddrMode.BaseOffs += ConstantOffset;
4694 if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
4695 VariableScale, Depth)) {
4696 // If even that didn't work, bail.
4697 AddrMode = BackupAddrMode;
4698 AddrModeInsts.resize(OldSize);
4699 return false;
4700 }
4701 }
4702
4703 return true;
4704 }
4705 case Instruction::SExt:
4706 case Instruction::ZExt: {
4707 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
4708 if (!Ext)
4709 return false;
4710
4711 // Try to move this ext out of the way of the addressing mode.
4712 // Ask for a method for doing so.
4713 TypePromotionHelper::Action TPH =
4714 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
4715 if (!TPH)
4716 return false;
4717
4718 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4719 TPT.getRestorationPoint();
4720 unsigned CreatedInstsCost = 0;
4721 unsigned ExtCost = !TLI.isExtFree(Ext);
4722 Value *PromotedOperand =
4723 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
4724 // SExt has been moved away.
4725 // Thus either it will be rematched later in the recursive calls or it is
4726 // gone. Anyway, we must not fold it into the addressing mode at this point.
4727 // E.g.,
4728 // op = add opnd, 1
4729 // idx = ext op
4730 // addr = gep base, idx
4731 // is now:
4732 // promotedOpnd = ext opnd <- no match here
4733 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
4734 // addr = gep base, op <- match
4735 if (MovedAway)
4736 *MovedAway = true;
4737
4738 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", 4739, __extension__ __PRETTY_FUNCTION__
))
4739 "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", 4739, __extension__ __PRETTY_FUNCTION__
))
;
4740
4741 ExtAddrMode BackupAddrMode = AddrMode;
4742 unsigned OldSize = AddrModeInsts.size();
4743
4744 if (!matchAddr(PromotedOperand, Depth) ||
4745 // The total of the new cost is equal to the cost of the created
4746 // instructions.
4747 // The total of the old cost is equal to the cost of the extension plus
4748 // what we have saved in the addressing mode.
4749 !isPromotionProfitable(CreatedInstsCost,
4750 ExtCost + (AddrModeInsts.size() - OldSize),
4751 PromotedOperand)) {
4752 AddrMode = BackupAddrMode;
4753 AddrModeInsts.resize(OldSize);
4754 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)
;
4755 TPT.rollback(LastKnownGood);
4756 return false;
4757 }
4758 return true;
4759 }
4760 }
4761 return false;
4762}
4763
4764/// If we can, try to add the value of 'Addr' into the current addressing mode.
4765/// If Addr can't be added to AddrMode this returns false and leaves AddrMode
4766/// unmodified. This assumes that Addr is either a pointer type or intptr_t
4767/// for the target.
4768///
4769bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
4770 // Start a transaction at this point that we will rollback if the matching
4771 // fails.
4772 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4773 TPT.getRestorationPoint();
4774 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
4775 if (CI->getValue().isSignedIntN(64)) {
4776 // Fold in immediates if legal for the target.
4777 AddrMode.BaseOffs += CI->getSExtValue();
4778 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
4779 return true;
4780 AddrMode.BaseOffs -= CI->getSExtValue();
4781 }
4782 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
4783 // If this is a global variable, try to fold it into the addressing mode.
4784 if (!AddrMode.BaseGV) {
4785 AddrMode.BaseGV = GV;
4786 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
4787 return true;
4788 AddrMode.BaseGV = nullptr;
4789 }
4790 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
4791 ExtAddrMode BackupAddrMode = AddrMode;
4792 unsigned OldSize = AddrModeInsts.size();
4793
4794 // Check to see if it is possible to fold this operation.
4795 bool MovedAway = false;
4796 if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
4797 // This instruction may have been moved away. If so, there is nothing
4798 // to check here.
4799 if (MovedAway)
4800 return true;
4801 // Okay, it's possible to fold this. Check to see if it is actually
4802 // *profitable* to do so. We use a simple cost model to avoid increasing
4803 // register pressure too much.
4804 if (I->hasOneUse() ||
4805 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
4806 AddrModeInsts.push_back(I);
4807 return true;
4808 }
4809
4810 // It isn't profitable to do this, roll back.
4811 AddrMode = BackupAddrMode;
4812 AddrModeInsts.resize(OldSize);
4813 TPT.rollback(LastKnownGood);
4814 }
4815 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
4816 if (matchOperationAddr(CE, CE->getOpcode(), Depth))
4817 return true;
4818 TPT.rollback(LastKnownGood);
4819 } else if (isa<ConstantPointerNull>(Addr)) {
4820 // Null pointer gets folded without affecting the addressing mode.
4821 return true;
4822 }
4823
4824 // Worse case, the target should support [reg] addressing modes. :)
4825 if (!AddrMode.HasBaseReg) {
4826 AddrMode.HasBaseReg = true;
4827 AddrMode.BaseReg = Addr;
4828 // Still check for legality in case the target supports [imm] but not [i+r].
4829 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
4830 return true;
4831 AddrMode.HasBaseReg = false;
4832 AddrMode.BaseReg = nullptr;
4833 }
4834
4835 // If the base register is already taken, see if we can do [r+r].
4836 if (AddrMode.Scale == 0) {
4837 AddrMode.Scale = 1;
4838 AddrMode.ScaledReg = Addr;
4839 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
4840 return true;
4841 AddrMode.Scale = 0;
4842 AddrMode.ScaledReg = nullptr;
4843 }
4844 // Couldn't match.
4845 TPT.rollback(LastKnownGood);
4846 return false;
4847}
4848
4849/// Check to see if all uses of OpVal by the specified inline asm call are due
4850/// to memory operands. If so, return true, otherwise return false.
4851static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
4852 const TargetLowering &TLI,
4853 const TargetRegisterInfo &TRI) {
4854 const Function *F = CI->getFunction();
4855 TargetLowering::AsmOperandInfoVector TargetConstraints =
4856 TLI.ParseConstraints(F->getParent()->getDataLayout(), &TRI, *CI);
4857
4858 for (TargetLowering::AsmOperandInfo &OpInfo : TargetConstraints) {
4859 // Compute the constraint code and ConstraintType to use.
4860 TLI.ComputeConstraintToUse(OpInfo, SDValue());
4861
4862 // If this asm operand is our Value*, and if it isn't an indirect memory
4863 // operand, we can't fold it! TODO: Also handle C_Address?
4864 if (OpInfo.CallOperandVal == OpVal &&
4865 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
4866 !OpInfo.isIndirect))
4867 return false;
4868 }
4869
4870 return true;
4871}
4872
4873// Max number of memory uses to look at before aborting the search to conserve
4874// compile time.
4875static constexpr int MaxMemoryUsesToScan = 20;
4876
4877/// Recursively walk all the uses of I until we find a memory use.
4878/// If we find an obviously non-foldable instruction, return true.
4879/// Add accessed addresses and types to MemoryUses.
4880static bool FindAllMemoryUses(
4881 Instruction *I, SmallVectorImpl<std::pair<Value *, Type *>> &MemoryUses,
4882 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetLowering &TLI,
4883 const TargetRegisterInfo &TRI, bool OptSize, ProfileSummaryInfo *PSI,
4884 BlockFrequencyInfo *BFI, int SeenInsts = 0) {
4885 // If we already considered this instruction, we're done.
4886 if (!ConsideredInsts.insert(I).second)
4887 return false;
4888
4889 // If this is an obviously unfoldable instruction, bail out.
4890 if (!MightBeFoldableInst(I))
4891 return true;
4892
4893 // Loop over all the uses, recursively processing them.
4894 for (Use &U : I->uses()) {
4895 // Conservatively return true if we're seeing a large number or a deep chain
4896 // of users. This avoids excessive compilation times in pathological cases.
4897 if (SeenInsts++ >= MaxMemoryUsesToScan)
4898 return true;
4899
4900 Instruction *UserI = cast<Instruction>(U.getUser());
4901 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
4902 MemoryUses.push_back({U.get(), LI->getType()});
4903 continue;
4904 }
4905
4906 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
4907 if (U.getOperandNo() != StoreInst::getPointerOperandIndex())
4908 return true; // Storing addr, not into addr.
4909 MemoryUses.push_back({U.get(), SI->getValueOperand()->getType()});
4910 continue;
4911 }
4912
4913 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UserI)) {
4914 if (U.getOperandNo() != AtomicRMWInst::getPointerOperandIndex())
4915 return true; // Storing addr, not into addr.
4916 MemoryUses.push_back({U.get(), RMW->getValOperand()->getType()});
4917 continue;
4918 }
4919
4920 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(UserI)) {
4921 if (U.getOperandNo() != AtomicCmpXchgInst::getPointerOperandIndex())
4922 return true; // Storing addr, not into addr.
4923 MemoryUses.push_back({U.get(), CmpX->getCompareOperand()->getType()});
4924 continue;
4925 }
4926
4927 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
4928 if (CI->hasFnAttr(Attribute::Cold)) {
4929 // If this is a cold call, we can sink the addressing calculation into
4930 // the cold path. See optimizeCallInst
4931 bool OptForSize = OptSize ||
4932 llvm::shouldOptimizeForSize(CI->getParent(), PSI, BFI);
4933 if (!OptForSize)
4934 continue;
4935 }
4936
4937 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledOperand());
4938 if (!IA) return true;
4939
4940 // If this is a memory operand, we're cool, otherwise bail out.
4941 if (!IsOperandAMemoryOperand(CI, IA, I, TLI, TRI))
4942 return true;
4943 continue;
4944 }
4945
4946 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI, TRI, OptSize,
4947 PSI, BFI, SeenInsts))
4948 return true;
4949 }
4950
4951 return false;
4952}
4953
4954/// Return true if Val is already known to be live at the use site that we're
4955/// folding it into. If so, there is no cost to include it in the addressing
4956/// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
4957/// instruction already.
4958bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
4959 Value *KnownLive2) {
4960 // If Val is either of the known-live values, we know it is live!
4961 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
4962 return true;
4963
4964 // All values other than instructions and arguments (e.g. constants) are live.
4965 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
4966
4967 // If Val is a constant sized alloca in the entry block, it is live, this is
4968 // true because it is just a reference to the stack/frame pointer, which is
4969 // live for the whole function.
4970 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
4971 if (AI->isStaticAlloca())
4972 return true;
4973
4974 // Check to see if this value is already used in the memory instruction's
4975 // block. If so, it's already live into the block at the very least, so we
4976 // can reasonably fold it.
4977 return Val->isUsedInBasicBlock(MemoryInst->getParent());
4978}
4979
4980/// It is possible for the addressing mode of the machine to fold the specified
4981/// instruction into a load or store that ultimately uses it.
4982/// However, the specified instruction has multiple uses.
4983/// Given this, it may actually increase register pressure to fold it
4984/// into the load. For example, consider this code:
4985///
4986/// X = ...
4987/// Y = X+1
4988/// use(Y) -> nonload/store
4989/// Z = Y+1
4990/// load Z
4991///
4992/// In this case, Y has multiple uses, and can be folded into the load of Z
4993/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
4994/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
4995/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
4996/// number of computations either.
4997///
4998/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
4999/// X was live across 'load Z' for other reasons, we actually *would* want to
5000/// fold the addressing mode in the Z case. This would make Y die earlier.
5001bool AddressingModeMatcher::
5002isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
5003 ExtAddrMode &AMAfter) {
5004 if (IgnoreProfitability) return true;
5005
5006 // AMBefore is the addressing mode before this instruction was folded into it,
5007 // and AMAfter is the addressing mode after the instruction was folded. Get
5008 // the set of registers referenced by AMAfter and subtract out those
5009 // referenced by AMBefore: this is the set of values which folding in this
5010 // address extends the lifetime of.
5011 //
5012 // Note that there are only two potential values being referenced here,
5013 // BaseReg and ScaleReg (global addresses are always available, as are any
5014 // folded immediates).
5015 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
5016
5017 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
5018 // lifetime wasn't extended by adding this instruction.
5019 if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
5020 BaseReg = nullptr;
5021 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
5022 ScaledReg = nullptr;
5023
5024 // If folding this instruction (and it's subexprs) didn't extend any live
5025 // ranges, we're ok with it.
5026 if (!BaseReg && !ScaledReg)
5027 return true;
5028
5029 // If all uses of this instruction can have the address mode sunk into them,
5030 // we can remove the addressing mode and effectively trade one live register
5031 // for another (at worst.) In this context, folding an addressing mode into
5032 // the use is just a particularly nice way of sinking it.
5033 SmallVector<std::pair<Value *, Type *>, 16> MemoryUses;
5034 SmallPtrSet<Instruction*, 16> ConsideredInsts;
5035 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI, TRI, OptSize,
5036 PSI, BFI))
5037 return false; // Has a non-memory, non-foldable use!
5038
5039 // Now that we know that all uses of this instruction are part of a chain of
5040 // computation involving only operations that could theoretically be folded
5041 // into a memory use, loop over each of these memory operation uses and see
5042 // if they could *actually* fold the instruction. The assumption is that
5043 // addressing modes are cheap and that duplicating the computation involved
5044 // many times is worthwhile, even on a fastpath. For sinking candidates
5045 // (i.e. cold call sites), this serves as a way to prevent excessive code
5046 // growth since most architectures have some reasonable small and fast way to
5047 // compute an effective address. (i.e LEA on x86)
5048 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
5049 for (const std::pair<Value *, Type *> &Pair : MemoryUses) {
5050 Value *Address = Pair.first;
5051 Type *AddressAccessTy = Pair.second;
5052 unsigned AS = Address->getType()->getPointerAddressSpace();
5053
5054 // Do a match against the root of this address, ignoring profitability. This
5055 // will tell us if the addressing mode for the memory operation will
5056 // *actually* cover the shared instruction.
5057 ExtAddrMode Result;
5058 std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr,
5059 0);
5060 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5061 TPT.getRestorationPoint();
5062 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, TRI, LI, getDTFn,
5063 AddressAccessTy, AS, MemoryInst, Result,
5064 InsertedInsts, PromotedInsts, TPT,
5065 LargeOffsetGEP, OptSize, PSI, BFI);
5066 Matcher.IgnoreProfitability = true;
5067 bool Success = Matcher.matchAddr(Address, 0);
5068 (void)Success; 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", 5068, __extension__ __PRETTY_FUNCTION__
))
;
5069
5070 // The match was to check the profitability, the changes made are not
5071 // part of the original matcher. Therefore, they should be dropped
5072 // otherwise the original matcher will not present the right state.
5073 TPT.rollback(LastKnownGood);
5074
5075 // If the match didn't cover I, then it won't be shared by it.
5076 if (!is_contained(MatchedAddrModeInsts, I))
5077 return false;
5078
5079 MatchedAddrModeInsts.clear();
5080 }
5081
5082 return true;
5083}
5084
5085/// Return true if the specified values are defined in a
5086/// different basic block than BB.
5087static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
5088 if (Instruction *I = dyn_cast<Instruction>(V))
5089 return I->getParent() != BB;
5090 return false;
5091}
5092
5093/// Sink addressing mode computation immediate before MemoryInst if doing so
5094/// can be done without increasing register pressure. The need for the
5095/// register pressure constraint means this can end up being an all or nothing
5096/// decision for all uses of the same addressing computation.
5097///
5098/// Load and Store Instructions often have addressing modes that can do
5099/// significant amounts of computation. As such, instruction selection will try
5100/// to get the load or store to do as much computation as possible for the
5101/// program. The problem is that isel can only see within a single block. As
5102/// such, we sink as much legal addressing mode work into the block as possible.
5103///
5104/// This method is used to optimize both load/store and inline asms with memory
5105/// operands. It's also used to sink addressing computations feeding into cold
5106/// call sites into their (cold) basic block.
5107///
5108/// The motivation for handling sinking into cold blocks is that doing so can
5109/// both enable other address mode sinking (by satisfying the register pressure
5110/// constraint above), and reduce register pressure globally (by removing the
5111/// addressing mode computation from the fast path entirely.).
5112bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
5113 Type *AccessTy, unsigned AddrSpace) {
5114 Value *Repl = Addr;
5115
5116 // Try to collapse single-value PHI nodes. This is necessary to undo
5117 // unprofitable PRE transformations.
5118 SmallVector<Value*, 8> worklist;
5119 SmallPtrSet<Value*, 16> Visited;
5120 worklist.push_back(Addr);
5121
5122 // Use a worklist to iteratively look through PHI and select nodes, and
5123 // ensure that the addressing mode obtained from the non-PHI/select roots of
5124 // the graph are compatible.
5125 bool PhiOrSelectSeen = false;
5126 SmallVector<Instruction*, 16> AddrModeInsts;
5127 const SimplifyQuery SQ(*DL, TLInfo);
5128 AddressingModeCombiner AddrModes(SQ, Addr);
5129 TypePromotionTransaction TPT(RemovedInsts);
5130 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5131 TPT.getRestorationPoint();
5132 while (!worklist.empty()) {
5133 Value *V = worklist.pop_back_val();
5134
5135 // We allow traversing cyclic Phi nodes.
5136 // In case of success after this loop we ensure that traversing through
5137 // Phi nodes ends up with all cases to compute address of the form
5138 // BaseGV + Base + Scale * Index + Offset
5139 // where Scale and Offset are constans and BaseGV, Base and Index
5140 // are exactly the same Values in all cases.
5141 // It means that BaseGV, Scale and Offset dominate our memory instruction
5142 // and have the same value as they had in address computation represented
5143 // as Phi. So we can safely sink address computation to memory instruction.
5144 if (!Visited.insert(V).second)
5145 continue;
5146
5147 // For a PHI node, push all of its incoming values.
5148 if (PHINode *P = dyn_cast<PHINode>(V)) {
5149 append_range(worklist, P->incoming_values());
5150 PhiOrSelectSeen = true;
5151 continue;
5152 }
5153 // Similar for select.
5154 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
5155 worklist.push_back(SI->getFalseValue());
5156 worklist.push_back(SI->getTrueValue());
5157 PhiOrSelectSeen = true;
5158 continue;
5159 }
5160
5161 // For non-PHIs, determine the addressing mode being computed. Note that
5162 // the result may differ depending on what other uses our candidate
5163 // addressing instructions might have.
5164 AddrModeInsts.clear();
5165 std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr,
5166 0);
5167 // Defer the query (and possible computation of) the dom tree to point of
5168 // actual use. It's expected that most address matches don't actually need
5169 // the domtree.
5170 auto getDTFn = [MemoryInst, this]() -> const DominatorTree & {
5171 Function *F = MemoryInst->getParent()->getParent();
5172 return this->getDT(*F);
5173 };
5174 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
5175 V, AccessTy, AddrSpace, MemoryInst, AddrModeInsts, *TLI, *LI, getDTFn,
5176 *TRI, InsertedInsts, PromotedInsts, TPT, LargeOffsetGEP, OptSize, PSI,
5177 BFI.get());
5178
5179 GetElementPtrInst *GEP = LargeOffsetGEP.first;
5180 if (GEP && !NewGEPBases.count(GEP)) {
5181 // If splitting the underlying data structure can reduce the offset of a
5182 // GEP, collect the GEP. Skip the GEPs that are the new bases of
5183 // previously split data structures.
5184 LargeOffsetGEPMap[GEP->getPointerOperand()].push_back(LargeOffsetGEP);
5185 LargeOffsetGEPID.insert(std::make_pair(GEP, LargeOffsetGEPID.size()));
5186 }
5187
5188 NewAddrMode.OriginalValue = V;
5189 if (!AddrModes.addNewAddrMode(NewAddrMode))
5190 break;
5191 }
5192
5193 // Try to combine the AddrModes we've collected. If we couldn't collect any,
5194 // or we have multiple but either couldn't combine them or combining them
5195 // wouldn't do anything useful, bail out now.
5196 if (!AddrModes.combineAddrModes()) {
5197 TPT.rollback(LastKnownGood);
5198 return false;
5199 }
5200 bool Modified = TPT.commit();
5201
5202 // Get the combined AddrMode (or the only AddrMode, if we only had one).
5203 ExtAddrMode AddrMode = AddrModes.getAddrMode();
5204
5205 // If all the instructions matched are already in this BB, don't do anything.
5206 // If we saw a Phi node then it is not local definitely, and if we saw a select
5207 // then we want to push the address calculation past it even if it's already
5208 // in this BB.
5209 if (!PhiOrSelectSeen && none_of(AddrModeInsts, [&](Value *V) {
5210 return IsNonLocalValue(V, MemoryInst->getParent());
5211 })) {
5212 LLVM_DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrModedo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "CGP: Found local addrmode: "
<< AddrMode << "\n"; } } while (false)
5213 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "CGP: Found local addrmode: "
<< AddrMode << "\n"; } } while (false)
;
5214 return Modified;
5215 }
5216
5217 // Insert this computation right after this user. Since our caller is
5218 // scanning from the top of the BB to the bottom, reuse of the expr are
5219 // guaranteed to happen later.
5220 IRBuilder<> Builder(MemoryInst);
5221
5222 // Now that we determined the addressing expression we want to use and know
5223 // that we have to sink it into this block. Check to see if we have already
5224 // done this for some other load/store instr in this block. If so, reuse
5225 // the computation. Before attempting reuse, check if the address is valid
5226 // as it may have been erased.
5227
5228 WeakTrackingVH SunkAddrVH = SunkAddrs[Addr];
5229
5230 Value * SunkAddr = SunkAddrVH.pointsToAliveValue() ? SunkAddrVH : nullptr;
5231 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
5232 if (SunkAddr) {
5233 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)
5234 << " for " << *MemoryInst << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "CGP: Reusing nonlocal addrmode: "
<< AddrMode << " for " << *MemoryInst <<
"\n"; } } while (false)
;
5235 if (SunkAddr->getType() != Addr->getType()) {
5236 if (SunkAddr->getType()->getPointerAddressSpace() !=
5237 Addr->getType()->getPointerAddressSpace() &&
5238 !DL->isNonIntegralPointerType(Addr->getType())) {
5239 // There are two reasons the address spaces might not match: a no-op
5240 // addrspacecast, or a ptrtoint/inttoptr pair. Either way, we emit a
5241 // ptrtoint/inttoptr pair to ensure we match the original semantics.
5242 // TODO: allow bitcast between different address space pointers with the
5243 // same size.
5244 SunkAddr = Builder.CreatePtrToInt(SunkAddr, IntPtrTy, "sunkaddr");
5245 SunkAddr =
5246 Builder.CreateIntToPtr(SunkAddr, Addr->getType(), "sunkaddr");
5247 } else
5248 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
5249 }
5250 } else if (AddrSinkUsingGEPs || (!AddrSinkUsingGEPs.getNumOccurrences() &&
5251 SubtargetInfo->addrSinkUsingGEPs())) {
5252 // By default, we use the GEP-based method when AA is used later. This
5253 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
5254 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)
5255 << " for " << *MemoryInst << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "CGP: SINKING nonlocal addrmode: "
<< AddrMode << " for " << *MemoryInst <<
"\n"; } } while (false)
;
5256 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
5257
5258 // First, find the pointer.
5259 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
5260 ResultPtr = AddrMode.BaseReg;
5261 AddrMode.BaseReg = nullptr;
5262 }
5263
5264 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
5265 // We can't add more than one pointer together, nor can we scale a
5266 // pointer (both of which seem meaningless).
5267 if (ResultPtr || AddrMode.Scale != 1)
5268 return Modified;
5269
5270 ResultPtr = AddrMode.ScaledReg;
5271 AddrMode.Scale = 0;
5272 }
5273
5274 // It is only safe to sign extend the BaseReg if we know that the math
5275 // required to create it did not overflow before we extend it. Since
5276 // the original IR value was tossed in favor of a constant back when
5277 // the AddrMode was created we need to bail out gracefully if widths
5278 // do not match instead of extending it.
5279 //
5280 // (See below for code to add the scale.)
5281 if (AddrMode.Scale) {
5282 Type *ScaledRegTy = AddrMode.ScaledReg->getType();
5283 if (cast<IntegerType>(IntPtrTy)->getBitWidth() >
5284 cast<IntegerType>(ScaledRegTy)->getBitWidth())
5285 return Modified;
5286 }
5287
5288 if (AddrMode.BaseGV) {
5289 if (ResultPtr)
5290 return Modified;
5291
5292 ResultPtr = AddrMode.BaseGV;
5293 }
5294
5295 // If the real base value actually came from an inttoptr, then the matcher
5296 // will look through it and provide only the integer value. In that case,
5297 // use it here.
5298 if (!DL->isNonIntegralPointerType(Addr->getType())) {
5299 if (!ResultPtr && AddrMode.BaseReg) {
5300 ResultPtr = Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(),
5301 "sunkaddr");
5302 AddrMode.BaseReg = nullptr;
5303 } else if (!ResultPtr && AddrMode.Scale == 1) {
5304 ResultPtr = Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(),
5305 "sunkaddr");
5306 AddrMode.Scale = 0;
5307 }
5308 }
5309
5310 if (!ResultPtr &&
5311 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
5312 SunkAddr = Constant::getNullValue(Addr->getType());
5313 } else if (!ResultPtr) {
5314 return Modified;
5315 } else {
5316 Type *I8PtrTy =
5317 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
5318 Type *I8Ty = Builder.getInt8Ty();
5319
5320 // Start with the base register. Do this first so that subsequent address
5321 // matching finds it last, which will prevent it from trying to match it
5322 // as the scaled value in case it happens to be a mul. That would be
5323 // problematic if we've sunk a different mul for the scale, because then
5324 // we'd end up sinking both muls.
5325 if (AddrMode.BaseReg) {
5326 Value *V = AddrMode.BaseReg;
5327 if (V->getType() != IntPtrTy)
5328 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
5329
5330 ResultIndex = V;
5331 }
5332
5333 // Add the scale value.
5334 if (AddrMode.Scale) {
5335 Value *V = AddrMode.ScaledReg;
5336 if (V->getType() == IntPtrTy) {
5337 // done.
5338 } else {
5339 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", 5341, __extension__ __PRETTY_FUNCTION__
))
5340 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", 5341, __extension__ __PRETTY_FUNCTION__
))
5341 "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", 5341, __extension__ __PRETTY_FUNCTION__
))
;
5342 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
5343 }
5344
5345 if (AddrMode.Scale != 1)
5346 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
5347 "sunkaddr");
5348 if (ResultIndex)
5349 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
5350 else
5351 ResultIndex = V;
5352 }
5353
5354 // Add in the Base Offset if present.
5355 if (AddrMode.BaseOffs) {
5356 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
5357 if (ResultIndex) {
5358 // We need to add this separately from the scale above to help with
5359 // SDAG consecutive load/store merging.
5360 if (ResultPtr->getType() != I8PtrTy)
5361 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
5362 ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex,
5363 "sunkaddr", AddrMode.InBounds);
5364 }
5365
5366 ResultIndex = V;
5367 }
5368
5369 if (!ResultIndex) {
5370 SunkAddr = ResultPtr;
5371 } else {
5372 if (ResultPtr->getType() != I8PtrTy)
5373 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
5374 SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr",
5375 AddrMode.InBounds);
5376 }
5377
5378 if (SunkAddr->getType() != Addr->getType()) {
5379 if (SunkAddr->getType()->getPointerAddressSpace() !=
5380 Addr->getType()->getPointerAddressSpace() &&
5381 !DL->isNonIntegralPointerType(Addr->getType())) {
5382 // There are two reasons the address spaces might not match: a no-op
5383 // addrspacecast, or a ptrtoint/inttoptr pair. Either way, we emit a
5384 // ptrtoint/inttoptr pair to ensure we match the original semantics.
5385 // TODO: allow bitcast between different address space pointers with
5386 // the same size.
5387 SunkAddr = Builder.CreatePtrToInt(SunkAddr, IntPtrTy, "sunkaddr");
5388 SunkAddr =
5389 Builder.CreateIntToPtr(SunkAddr, Addr->getType(), "sunkaddr");
5390 } else
5391 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
5392 }
5393 }
5394 } else {
5395 // We'd require a ptrtoint/inttoptr down the line, which we can't do for
5396 // non-integral pointers, so in that case bail out now.
5397 Type *BaseTy = AddrMode.BaseReg ? AddrMode.BaseReg->getType() : nullptr;
5398 Type *ScaleTy = AddrMode.Scale ? AddrMode.ScaledReg->getType() : nullptr;
5399 PointerType *BasePtrTy = dyn_cast_or_null<PointerType>(BaseTy);
5400 PointerType *ScalePtrTy = dyn_cast_or_null<PointerType>(ScaleTy);
5401 if (DL->isNonIntegralPointerType(Addr->getType()) ||
5402 (BasePtrTy && DL->isNonIntegralPointerType(BasePtrTy)) ||
5403 (ScalePtrTy && DL->isNonIntegralPointerType(ScalePtrTy)) ||
5404 (AddrMode.BaseGV &&
5405 DL->isNonIntegralPointerType(AddrMode.BaseGV->getType())))
5406 return Modified;
5407
5408 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)
5409 << " for " << *MemoryInst << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "CGP: SINKING nonlocal addrmode: "
<< AddrMode << " for " << *MemoryInst <<
"\n"; } } while (false)
;
5410 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
5411 Value *Result = nullptr;
5412
5413 // Start with the base register. Do this first so that subsequent address
5414 // matching finds it last, which will prevent it from trying to match it
5415 // as the scaled value in case it happens to be a mul. That would be
5416 // problematic if we've sunk a different mul for the scale, because then
5417 // we'd end up sinking both muls.
5418 if (AddrMode.BaseReg) {
5419 Value *V = AddrMode.BaseReg;
5420 if (V->getType()->isPointerTy())
5421 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
5422 if (V->getType() != IntPtrTy)
5423 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
5424 Result = V;
5425 }
5426
5427 // Add the scale value.
5428 if (AddrMode.Scale) {
5429 Value *V = AddrMode.ScaledReg;
5430 if (V->getType() == IntPtrTy) {
5431 // done.
5432 } else if (V->getType()->isPointerTy()) {
5433 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
5434 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
5435 cast<IntegerType>(V->getType())->getBitWidth()) {
5436 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
5437 } else {
5438 // It is only safe to sign extend the BaseReg if we know that the math
5439 // required to create it did not overflow before we extend it. Since
5440 // the original IR value was tossed in favor of a constant back when
5441 // the AddrMode was created we need to bail out gracefully if widths
5442 // do not match instead of extending it.
5443 Instruction *I = dyn_cast_or_null<Instruction>(Result);
5444 if (I && (Result != AddrMode.BaseReg))
5445 I->eraseFromParent();
5446 return Modified;
5447 }
5448 if (AddrMode.Scale != 1)
5449 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
5450 "sunkaddr");
5451 if (Result)
5452 Result = Builder.CreateAdd(Result, V, "sunkaddr");
5453 else
5454 Result = V;
5455 }
5456
5457 // Add in the BaseGV if present.
5458 if (AddrMode.BaseGV) {
5459 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
5460 if (Result)
5461 Result = Builder.CreateAdd(Result, V, "sunkaddr");
5462 else
5463 Result = 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 (Result)
5470 Result = Builder.CreateAdd(Result, V, "sunkaddr");
5471 else
5472 Result = V;
5473 }
5474
5475 if (!Result)
5476 SunkAddr = Constant::getNullValue(Addr->getType());
5477 else
5478 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
5479 }
5480
5481 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
5482 // Store the newly computed address into the cache. In the case we reused a
5483 // value, this should be idempotent.
5484 SunkAddrs[Addr] = WeakTrackingVH(SunkAddr);
5485
5486 // If we have no uses, recursively delete the value and all dead instructions
5487 // using it.
5488 if (Repl->use_empty()) {
5489 resetIteratorIfInvalidatedWhileCalling(CurInstIterator->getParent(), [&]() {
5490 RecursivelyDeleteTriviallyDeadInstructions(
5491 Repl, TLInfo, nullptr,
5492 [&](Value *V) { removeAllAssertingVHReferences(V); });
5493 });
5494 }
5495 ++NumMemoryInsts;
5496 return true;
5497}
5498
5499/// Rewrite GEP input to gather/scatter to enable SelectionDAGBuilder to find
5500/// a uniform base to use for ISD::MGATHER/MSCATTER. SelectionDAGBuilder can
5501/// only handle a 2 operand GEP in the same basic block or a splat constant
5502/// vector. The 2 operands to the GEP must have a scalar pointer and a vector
5503/// index.
5504///
5505/// If the existing GEP has a vector base pointer that is splat, we can look
5506/// through the splat to find the scalar pointer. If we can't find a scalar
5507/// pointer there's nothing we can do.
5508///
5509/// If we have a GEP with more than 2 indices where the middle indices are all
5510/// zeroes, we can replace it with 2 GEPs where the second has 2 operands.
5511///
5512/// If the final index isn't a vector or is a splat, we can emit a scalar GEP
5513/// followed by a GEP with an all zeroes vector index. This will enable
5514/// SelectionDAGBuilder to use the scalar GEP as the uniform base and have a
5515/// zero index.
5516bool CodeGenPrepare::optimizeGatherScatterInst(Instruction *MemoryInst,
5517 Value *Ptr) {
5518 Value *NewAddr;
5519
5520 if (const auto *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
5521 // Don't optimize GEPs that don't have indices.
5522 if (!GEP->hasIndices())
5523 return false;
5524
5525 // If the GEP and the gather/scatter aren't in the same BB, don't optimize.
5526 // FIXME: We should support this by sinking the GEP.
5527 if (MemoryInst->getParent() != GEP->getParent())
5528 return false;
5529
5530 SmallVector<Value *, 2> Ops(GEP->operands());
5531
5532 bool RewriteGEP = false;
5533
5534 if (Ops[0]->getType()->isVectorTy()) {
5535 Ops[0] = getSplatValue(Ops[0]);
5536 if (!Ops[0])
5537 return false;
5538 RewriteGEP = true;
5539 }
5540
5541 unsigned FinalIndex = Ops.size() - 1;
5542
5543 // Ensure all but the last index is 0.
5544 // FIXME: This isn't strictly required. All that's required is that they are
5545 // all scalars or splats.
5546 for (unsigned i = 1; i < FinalIndex; ++i) {
5547 auto *C = dyn_cast<Constant>(Ops[i]);
5548 if (!C)
5549 return false;
5550 if (isa<VectorType>(C->getType()))
5551 C = C->getSplatValue();
5552 auto *CI = dyn_cast_or_null<ConstantInt>(C);
5553 if (!CI || !CI->isZero())
5554 return false;
5555 // Scalarize the index if needed.
5556 Ops[i] = CI;
5557 }
5558
5559 // Try to scalarize the final index.
5560 if (Ops[FinalIndex]->getType()->isVectorTy()) {
5561 if (Value *V = getSplatValue(Ops[FinalIndex])) {
5562 auto *C = dyn_cast<ConstantInt>(V);
5563 // Don't scalarize all zeros vector.
5564 if (!C || !C->isZero()) {
5565 Ops[FinalIndex] = V;
5566 RewriteGEP = true;
5567 }
5568 }
5569 }
5570
5571 // If we made any changes or the we have extra operands, we need to generate
5572 // new instructions.
5573 if (!RewriteGEP && Ops.size() == 2)
5574 return false;
5575
5576 auto NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
5577
5578 IRBuilder<> Builder(MemoryInst);
5579
5580 Type *SourceTy = GEP->getSourceElementType();
5581 Type *ScalarIndexTy = DL->getIndexType(Ops[0]->getType()->getScalarType());
5582
5583 // If the final index isn't a vector, emit a scalar GEP containing all ops
5584 // and a vector GEP with all zeroes final index.
5585 if (!Ops[FinalIndex]->getType()->isVectorTy()) {
5586 NewAddr = Builder.CreateGEP(SourceTy, Ops[0],
5587 makeArrayRef(Ops).drop_front());
5588 auto *IndexTy = VectorType::get(ScalarIndexTy, NumElts);
5589 auto *SecondTy = GetElementPtrInst::getIndexedType(
5590 SourceTy, makeArrayRef(Ops).drop_front());
5591 NewAddr =
5592 Builder.CreateGEP(SecondTy, NewAddr, Constant::getNullValue(IndexTy));
5593 } else {
5594 Value *Base = Ops[0];
5595 Value *Index = Ops[FinalIndex];
5596
5597 // Create a scalar GEP if there are more than 2 operands.
5598 if (Ops.size() != 2) {
5599 // Replace the last index with 0.
5600 Ops[FinalIndex] = Constant::getNullValue(ScalarIndexTy);
5601 Base = Builder.CreateGEP(SourceTy, Base,
5602 makeArrayRef(Ops).drop_front());
5603 SourceTy = GetElementPtrInst::getIndexedType(
5604 SourceTy, makeArrayRef(Ops).drop_front());
5605 }
5606
5607 // Now create the GEP with scalar pointer and vector index.
5608 NewAddr = Builder.CreateGEP(SourceTy, Base, Index);
5609 }
5610 } else if (!isa<Constant>(Ptr)) {
5611 // Not a GEP, maybe its a splat and we can create a GEP to enable
5612 // SelectionDAGBuilder to use it as a uniform base.
5613 Value *V = getSplatValue(Ptr);
5614 if (!V)
5615 return false;
5616
5617 auto NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
5618
5619 IRBuilder<> Builder(MemoryInst);
5620
5621 // Emit a vector GEP with a scalar pointer and all 0s vector index.
5622 Type *ScalarIndexTy = DL->getIndexType(V->getType()->getScalarType());
5623 auto *IndexTy = VectorType::get(ScalarIndexTy, NumElts);
5624 Type *ScalarTy;
5625 if (cast<IntrinsicInst>(MemoryInst)->getIntrinsicID() ==
5626 Intrinsic::masked_gather) {
5627 ScalarTy = MemoryInst->getType()->getScalarType();
5628 } else {
5629 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", 5630, __extension__ __PRETTY_FUNCTION__
))
5630 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", 5630, __extension__ __PRETTY_FUNCTION__
))
;
5631 ScalarTy = MemoryInst->getOperand(0)->getType()->getScalarType();
5632 }
5633 NewAddr = Builder.CreateGEP(ScalarTy, V, Constant::getNullValue(IndexTy));
5634 } else {
5635 // Constant, SelectionDAGBuilder knows to check if its a splat.
5636 return false;
5637 }
5638
5639 MemoryInst->replaceUsesOfWith(Ptr, NewAddr);
5640
5641 // If we have no uses, recursively delete the value and all dead instructions
5642 // using it.
5643 if (Ptr->use_empty())
5644 RecursivelyDeleteTriviallyDeadInstructions(
5645 Ptr, TLInfo, nullptr,
5646 [&](Value *V) { removeAllAssertingVHReferences(V); });
5647
5648 return true;
5649}
5650
5651/// If there are any memory operands, use OptimizeMemoryInst to sink their
5652/// address computing into the block when possible / profitable.
5653bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
5654 bool MadeChange = false;
5655
5656 const TargetRegisterInfo *TRI =
5657 TM->getSubtargetImpl(*CS->getFunction())->getRegisterInfo();
5658 TargetLowering::AsmOperandInfoVector TargetConstraints =
5659 TLI->ParseConstraints(*DL, TRI, *CS);
5660 unsigned ArgNo = 0;
5661 for (TargetLowering::AsmOperandInfo &OpInfo : TargetConstraints) {
5662 // Compute the constraint code and ConstraintType to use.
5663 TLI->ComputeConstraintToUse(OpInfo, SDValue());
5664
5665 // TODO: Also handle C_Address?
5666 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
5667 OpInfo.isIndirect) {
5668 Value *OpVal = CS->getArgOperand(ArgNo++);
5669 MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
5670 } else if (OpInfo.Type == InlineAsm::isInput)
5671 ArgNo++;
5672 }
5673
5674 return MadeChange;
5675}
5676
5677/// Check if all the uses of \p Val are equivalent (or free) zero or
5678/// sign extensions.
5679static bool hasSameExtUse(Value *Val, const TargetLowering &TLI) {
5680 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", 5680, __extension__ __PRETTY_FUNCTION__
))
;
5681 const Instruction *FirstUser = cast<Instruction>(*Val->user_begin());
5682 bool IsSExt = isa<SExtInst>(FirstUser);
5683 Type *ExtTy = FirstUser->getType();
5684 for (const User *U : Val->users()) {
5685 const Instruction *UI = cast<Instruction>(U);
5686 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
5687 return false;
5688 Type *CurTy = UI->getType();
5689 // Same input and output types: Same instruction after CSE.
5690 if (CurTy == ExtTy)
5691 continue;
5692
5693 // If IsSExt is true, we are in this situation:
5694 // a = Val
5695 // b = sext ty1 a to ty2
5696 // c = sext ty1 a to ty3
5697 // Assuming ty2 is shorter than ty3, this could be turned into:
5698 // a = Val
5699 // b = sext ty1 a to ty2
5700 // c = sext ty2 b to ty3
5701 // However, the last sext is not free.
5702 if (IsSExt)
5703 return false;
5704
5705 // This is a ZExt, maybe this is free to extend from one type to another.
5706 // In that case, we would not account for a different use.
5707 Type *NarrowTy;
5708 Type *LargeTy;
5709 if (ExtTy->getScalarType()->getIntegerBitWidth() >
5710 CurTy->getScalarType()->getIntegerBitWidth()) {
5711 NarrowTy = CurTy;
5712 LargeTy = ExtTy;
5713 } else {
5714 NarrowTy = ExtTy;
5715 LargeTy = CurTy;
5716 }
5717
5718 if (!TLI.isZExtFree(NarrowTy, LargeTy))
5719 return false;
5720 }
5721 // All uses are the same or can be derived from one another for free.
5722 return true;
5723}
5724
5725/// Try to speculatively promote extensions in \p Exts and continue
5726/// promoting through newly promoted operands recursively as far as doing so is
5727/// profitable. Save extensions profitably moved up, in \p ProfitablyMovedExts.
5728/// When some promotion happened, \p TPT contains the proper state to revert
5729/// them.
5730///
5731/// \return true if some promotion happened, false otherwise.
5732bool CodeGenPrepare::tryToPromoteExts(
5733 TypePromotionTransaction &TPT, const SmallVectorImpl<Instruction *> &Exts,
5734 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
5735 unsigned CreatedInstsCost) {
5736 bool Promoted = false;
5737
5738 // Iterate over all the extensions to try to promote them.
5739 for (auto *I : Exts) {
5740 // Early check if we directly have ext(load).
5741 if (isa<LoadInst>(I->getOperand(0))) {
5742 ProfitablyMovedExts.push_back(I);
5743 continue;
5744 }
5745
5746 // Check whether or not we want to do any promotion. The reason we have
5747 // this check inside the for loop is to catch the case where an extension
5748 // is directly fed by a load because in such case the extension can be moved
5749 // up without any promotion on its operands.
5750 if (!TLI->enableExtLdPromotion() || DisableExtLdPromotion)
5751 return false;
5752
5753 // Get the action to perform the promotion.
5754 TypePromotionHelper::Action TPH =
5755 TypePromotionHelper::getAction(I, InsertedInsts, *TLI, PromotedInsts);
5756 // Check if we can promote.
5757 if (!TPH) {
5758 // Save the current extension as we cannot move up through its operand.
5759 ProfitablyMovedExts.push_back(I);
5760 continue;
5761 }
5762
5763 // Save the current state.
5764 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5765 TPT.getRestorationPoint();
5766 SmallVector<Instruction *, 4> NewExts;
5767 unsigned NewCreatedInstsCost = 0;
5768 unsigned ExtCost = !TLI->isExtFree(I);
5769 // Promote.
5770 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
5771 &NewExts, nullptr, *TLI);
5772 assert(PromotedVal &&(static_cast <bool> (PromotedVal && "TypePromotionHelper should have filtered out those cases"
) ? void (0) : __assert_fail ("PromotedVal && \"TypePromotionHelper should have filtered out those cases\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 5773, __extension__ __PRETTY_FUNCTION__
))
5773 "TypePromotionHelper should have filtered out those cases")(static_cast <bool> (PromotedVal && "TypePromotionHelper should have filtered out those cases"
) ? void (0) : __assert_fail ("PromotedVal && \"TypePromotionHelper should have filtered out those cases\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 5773, __extension__ __PRETTY_FUNCTION__
))
;
5774
5775 // We would be able to merge only one extension in a load.
5776 // Therefore, if we have more than 1 new extension we heuristically
5777 // cut this search path, because it means we degrade the code quality.
5778 // With exactly 2, the transformation is neutral, because we will merge
5779 // one extension but leave one. However, we optimistically keep going,
5780 // because the new extension may be removed too.
5781 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
5782 // FIXME: It would be possible to propagate a negative value instead of
5783 // conservatively ceiling it to 0.
5784 TotalCreatedInstsCost =
5785 std::max((long long)0, (TotalCreatedInstsCost - ExtCost));
5786 if (!StressExtLdPromotion &&
5787 (TotalCreatedInstsCost > 1 ||
5788 !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
5789 // This promotion is not profitable, rollback to the previous state, and
5790 // save the current extension in ProfitablyMovedExts as the latest
5791 // speculative promotion turned out to be unprofitable.
5792 TPT.rollback(LastKnownGood);
5793 ProfitablyMovedExts.push_back(I);
5794 continue;
5795 }
5796 // Continue promoting NewExts as far as doing so is profitable.
5797 SmallVector<Instruction *, 2> NewlyMovedExts;
5798 (void)tryToPromoteExts(TPT, NewExts, NewlyMovedExts, TotalCreatedInstsCost);
5799 bool NewPromoted = false;
5800 for (auto *ExtInst : NewlyMovedExts) {
5801 Instruction *MovedExt = cast<Instruction>(ExtInst);
5802 Value *ExtOperand = MovedExt->getOperand(0);
5803 // If we have reached to a load, we need this extra profitability check
5804 // as it could potentially be merged into an ext(load).
5805 if (isa<LoadInst>(ExtOperand) &&
5806 !(StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
5807 (ExtOperand->hasOneUse() || hasSameExtUse(ExtOperand, *TLI))))
5808 continue;
5809
5810 ProfitablyMovedExts.push_back(MovedExt);
5811 NewPromoted = true;
5812 }
5813
5814 // If none of speculative promotions for NewExts is profitable, rollback
5815 // and save the current extension (I) as the last profitable extension.
5816 if (!NewPromoted) {
5817 TPT.rollback(LastKnownGood);
5818 ProfitablyMovedExts.push_back(I);
5819 continue;
5820 }
5821 // The promotion is profitable.
5822 Promoted = true;
5823 }
5824 return Promoted;
5825}
5826
5827/// Merging redundant sexts when one is dominating the other.
5828bool CodeGenPrepare::mergeSExts(Function &F) {
5829 bool Changed = false;
5830 for (auto &Entry : ValToSExtendedUses) {
5831 SExts &Insts = Entry.second;
5832 SExts CurPts;
5833 for (Instruction *Inst : Insts) {
5834 if (RemovedInsts.count(Inst) || !isa<SExtInst>(Inst) ||
5835 Inst->getOperand(0) != Entry.first)
5836 continue;
5837 bool inserted = false;
5838 for (auto &Pt : CurPts) {
5839 if (getDT(F).dominates(Inst, Pt)) {
5840 Pt->replaceAllUsesWith(Inst);
5841 RemovedInsts.insert(Pt);
5842 Pt->removeFromParent();
5843 Pt = Inst;
5844 inserted = true;
5845 Changed = true;
5846 break;
5847 }
5848 if (!getDT(F).dominates(Pt, Inst))
5849 // Give up if we need to merge in a common dominator as the
5850 // experiments show it is not profitable.
5851 continue;
5852 Inst->replaceAllUsesWith(Pt);
5853 RemovedInsts.insert(Inst);
5854 Inst->removeFromParent();
5855 inserted = true;
5856 Changed = true;
5857 break;
5858 }
5859 if (!inserted)
5860 CurPts.push_back(Inst);
5861 }
5862 }
5863 return Changed;
5864}
5865
5866// Splitting large data structures so that the GEPs accessing them can have
5867// smaller offsets so that they can be sunk to the same blocks as their users.
5868// For example, a large struct starting from %base is split into two parts
5869// where the second part starts from %new_base.
5870//
5871// Before:
5872// BB0:
5873// %base =
5874//
5875// BB1:
5876// %gep0 = gep %base, off0
5877// %gep1 = gep %base, off1
5878// %gep2 = gep %base, off2
5879//
5880// BB2:
5881// %load1 = load %gep0
5882// %load2 = load %gep1
5883// %load3 = load %gep2
5884//
5885// After:
5886// BB0:
5887// %base =
5888// %new_base = gep %base, off0
5889//
5890// BB1:
5891// %new_gep0 = %new_base
5892// %new_gep1 = gep %new_base, off1 - off0
5893// %new_gep2 = gep %new_base, off2 - off0
5894//
5895// BB2:
5896// %load1 = load i32, i32* %new_gep0
5897// %load2 = load i32, i32* %new_gep1
5898// %load3 = load i32, i32* %new_gep2
5899//
5900// %new_gep1 and %new_gep2 can be sunk to BB2 now after the splitting because
5901// their offsets are smaller enough to fit into the addressing mode.
5902bool CodeGenPrepare::splitLargeGEPOffsets() {
5903 bool Changed = false;
5904 for (auto &Entry : LargeOffsetGEPMap) {
5905 Value *OldBase = Entry.first;
5906 SmallVectorImpl<std::pair<AssertingVH<GetElementPtrInst>, int64_t>>
5907 &LargeOffsetGEPs = Entry.second;
5908 auto compareGEPOffset =
5909 [&](const std::pair<GetElementPtrInst *, int64_t> &LHS,
5910 const std::pair<GetElementPtrInst *, int64_t> &RHS) {
5911 if (LHS.first == RHS.first)
5912 return false;
5913 if (LHS.second != RHS.second)
5914 return LHS.second < RHS.second;
5915 return LargeOffsetGEPID[LHS.first] < LargeOffsetGEPID[RHS.first];
5916 };
5917 // Sorting all the GEPs of the same data structures based on the offsets.
5918 llvm::sort(LargeOffsetGEPs, compareGEPOffset);
5919 LargeOffsetGEPs.erase(
5920 std::unique(LargeOffsetGEPs.begin(), LargeOffsetGEPs.end()),
5921 LargeOffsetGEPs.end());
5922 // Skip if all the GEPs have the same offsets.
5923 if (LargeOffsetGEPs.front().second == LargeOffsetGEPs.back().second)
5924 continue;
5925 GetElementPtrInst *BaseGEP = LargeOffsetGEPs.begin()->first;
5926 int64_t BaseOffset = LargeOffsetGEPs.begin()->second;
5927 Value *NewBaseGEP = nullptr;
5928
5929 auto *LargeOffsetGEP = LargeOffsetGEPs.begin();
5930 while (LargeOffsetGEP != LargeOffsetGEPs.end()) {
5931 GetElementPtrInst *GEP = LargeOffsetGEP->first;
5932 int64_t Offset = LargeOffsetGEP->second;
5933 if (Offset != BaseOffset) {
5934 TargetLowering::AddrMode AddrMode;
5935 AddrMode.BaseOffs = Offset - BaseOffset;
5936 // The result type of the GEP might not be the type of the memory
5937 // access.
5938 if (!TLI->isLegalAddressingMode(*DL, AddrMode,
5939 GEP->getResultElementType(),
5940 GEP->getAddressSpace())) {
5941 // We need to create a new base if the offset to the current base is
5942 // too large to fit into the addressing mode. So, a very large struct
5943 // may be split into several parts.
5944 BaseGEP = GEP;
5945 BaseOffset = Offset;
5946 NewBaseGEP = nullptr;
5947 }
5948 }
5949
5950 // Generate a new GEP to replace the current one.
5951 LLVMContext &Ctx = GEP->getContext();
5952 Type *IntPtrTy = DL->getIntPtrType(GEP->getType());
5953 Type *I8PtrTy =
5954 Type::getInt8PtrTy(Ctx, GEP->getType()->getPointerAddressSpace());
5955 Type *I8Ty = Type::getInt8Ty(Ctx);
5956
5957 if (!NewBaseGEP) {
5958 // Create a new base if we don't have one yet. Find the insertion
5959 // pointer for the new base first.
5960 BasicBlock::iterator NewBaseInsertPt;
5961 BasicBlock *NewBaseInsertBB;
5962 if (auto *BaseI = dyn_cast<Instruction>(OldBase)) {
5963 // If the base of the struct is an instruction, the new base will be
5964 // inserted close to it.
5965 NewBaseInsertBB = BaseI->getParent();
5966 if (isa<PHINode>(BaseI))
5967 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
5968 else if (InvokeInst *Invoke = dyn_cast<InvokeInst>(BaseI)) {
5969 NewBaseInsertBB =
5970 SplitEdge(NewBaseInsertBB, Invoke->getNormalDest());
5971 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
5972 } else
5973 NewBaseInsertPt = std::next(BaseI->getIterator());
5974 } else {
5975 // If the current base is an argument or global value, the new base
5976 // will be inserted to the entry block.
5977 NewBaseInsertBB = &BaseGEP->getFunction()->getEntryBlock();
5978 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
5979 }
5980 IRBuilder<> NewBaseBuilder(NewBaseInsertBB, NewBaseInsertPt);
5981 // Create a new base.
5982 Value *BaseIndex = ConstantInt::get(IntPtrTy, BaseOffset);
5983 NewBaseGEP = OldBase;
5984 if (NewBaseGEP->getType() != I8PtrTy)
5985 NewBaseGEP = NewBaseBuilder.CreatePointerCast(NewBaseGEP, I8PtrTy);
5986 NewBaseGEP =
5987 NewBaseBuilder.CreateGEP(I8Ty, NewBaseGEP, BaseIndex, "splitgep");
5988 NewGEPBases.insert(NewBaseGEP);
5989 }
5990
5991 IRBuilder<> Builder(GEP);
5992 Value *NewGEP = NewBaseGEP;
5993 if (Offset == BaseOffset) {
5994 if (GEP->getType() != I8PtrTy)
5995 NewGEP = Builder.CreatePointerCast(NewGEP, GEP->getType());
5996 } else {
5997 // Calculate the new offset for the new GEP.
5998 Value *Index = ConstantInt::get(IntPtrTy, Offset - BaseOffset);
5999 NewGEP = Builder.CreateGEP(I8Ty, NewBaseGEP, Index);
6000
6001 if (GEP->getType() != I8PtrTy)
6002 NewGEP = Builder.CreatePointerCast(NewGEP, GEP->getType());
6003 }
6004 GEP->replaceAllUsesWith(NewGEP);
6005 LargeOffsetGEPID.erase(GEP);
6006 LargeOffsetGEP = LargeOffsetGEPs.erase(LargeOffsetGEP);
6007 GEP->eraseFromParent();
6008 Changed = true;
6009 }
6010 }
6011 return Changed;
6012}
6013
6014bool CodeGenPrepare::optimizePhiType(
6015 PHINode *I, SmallPtrSetImpl<PHINode *> &Visited,
6016 SmallPtrSetImpl<Instruction *> &DeletedInstrs) {
6017 // We are looking for a collection on interconnected phi nodes that together
6018 // only use loads/bitcasts and are used by stores/bitcasts, and the bitcasts
6019 // are of the same type. Convert the whole set of nodes to the type of the
6020 // bitcast.
6021 Type *PhiTy = I->getType();
6022 Type *ConvertTy = nullptr;
6023 if (Visited.count(I) ||
6024 (!I->getType()->isIntegerTy() && !I->getType()->isFloatingPointTy()))
6025 return false;
6026
6027 SmallVector<Instruction *, 4> Worklist;
6028 Worklist.push_back(cast<Instruction>(I));
6029 SmallPtrSet<PHINode *, 4> PhiNodes;
6030 PhiNodes.insert(I);
6031 Visited.insert(I);
6032 SmallPtrSet<Instruction *, 4> Defs;
6033 SmallPtrSet<Instruction *, 4> Uses;
6034 // This works by adding extra bitcasts between load/stores and removing
6035 // existing bicasts. If we have a phi(bitcast(load)) or a store(bitcast(phi))
6036 // we can get in the situation where we remove a bitcast in one iteration
6037 // just to add it again in the next. We need to ensure that at least one
6038 // bitcast we remove are anchored to something that will not change back.
6039 bool AnyAnchored = false;
6040
6041 while (!Worklist.empty()) {
6042 Instruction *II = Worklist.pop_back_val();
6043
6044 if (auto *Phi = dyn_cast<PHINode>(II)) {
6045 // Handle Defs, which might also be PHI's
6046 for (Value *V : Phi->incoming_values()) {
6047 if (auto *OpPhi = dyn_cast<PHINode>(V)) {
6048 if (!PhiNodes.count(OpPhi)) {
6049 if (!Visited.insert(OpPhi).second)
6050 return false;
6051 PhiNodes.insert(OpPhi);
6052 Worklist.push_back(OpPhi);
6053 }
6054 } else if (auto *OpLoad = dyn_cast<LoadInst>(V)) {
6055 if (!OpLoad->isSimple())
6056 return false;
6057 if (Defs.insert(OpLoad).second)
6058 Worklist.push_back(OpLoad);
6059 } else if (auto *OpEx = dyn_cast<ExtractElementInst>(V)) {
6060 if (Defs.insert(OpEx).second)
6061 Worklist.push_back(OpEx);
6062 } else if (auto *OpBC = dyn_cast<BitCastInst>(V)) {
6063 if (!ConvertTy)
6064 ConvertTy = OpBC->getOperand(0)->getType();
6065 if (OpBC->getOperand(0)->getType() != ConvertTy)
6066 return false;
6067 if (Defs.insert(OpBC).second) {
6068 Worklist.push_back(OpBC);
6069 AnyAnchored |= !isa<LoadInst>(OpBC->getOperand(0)) &&
6070 !isa<ExtractElementInst>(OpBC->getOperand(0));
6071 }
6072 } else if (!isa<UndefValue>(V)) {
6073 return false;
6074 }
6075 }
6076 }
6077
6078 // Handle uses which might also be phi's
6079 for (User *V : II->users()) {
6080 if (auto *OpPhi = dyn_cast<PHINode>(V)) {
6081 if (!PhiNodes.count(OpPhi)) {
6082 if (Visited.count(OpPhi))
6083 return false;
6084 PhiNodes.insert(OpPhi);
6085 Visited.insert(OpPhi);
6086 Worklist.push_back(OpPhi);
6087 }
6088 } else if (auto *OpStore = dyn_cast<StoreInst>(V)) {
6089 if (!OpStore->isSimple() || OpStore->getOperand(0) != II)
6090 return false;
6091 Uses.insert(OpStore);
6092 } else if (auto *OpBC = dyn_cast<BitCastInst>(V)) {
6093 if (!ConvertTy)
6094 ConvertTy = OpBC->getType();
6095 if (OpBC->getType() != ConvertTy)
6096 return false;
6097 Uses.insert(OpBC);
6098 AnyAnchored |=
6099 any_of(OpBC->users(), [](User *U) { return !isa<StoreInst>(U); });
6100 } else {
6101 return false;
6102 }
6103 }
6104 }
6105
6106 if (!ConvertTy || !AnyAnchored || !TLI->shouldConvertPhiType(PhiTy, ConvertTy))
6107 return false;
6108
6109 LLVM_DEBUG(dbgs() << "Converting " << *I << "\n and connected nodes to "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Converting " << *
I << "\n and connected nodes to " << *ConvertTy <<
"\n"; } } while (false)
6110 << *ConvertTy << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Converting " << *
I << "\n and connected nodes to " << *ConvertTy <<
"\n"; } } while (false)
;
6111
6112 // Create all the new phi nodes of the new type, and bitcast any loads to the
6113 // correct type.
6114 ValueToValueMap ValMap;
6115 ValMap[UndefValue::get(PhiTy)] = UndefValue::get(ConvertTy);
6116 for (Instruction *D : Defs) {
6117 if (isa<BitCastInst>(D)) {
6118 ValMap[D] = D->getOperand(0);
6119 DeletedInstrs.insert(D);
6120 } else {
6121 ValMap[D] =
6122 new BitCastInst(D, ConvertTy, D->getName() + ".bc", D->getNextNode());
6123 }
6124 }
6125 for (PHINode *Phi : PhiNodes)
6126 ValMap[Phi] = PHINode::Create(ConvertTy, Phi->getNumIncomingValues(),
6127 Phi->getName() + ".tc", Phi);
6128 // Pipe together all the PhiNodes.
6129 for (PHINode *Phi : PhiNodes) {
6130 PHINode *NewPhi = cast<PHINode>(ValMap[Phi]);
6131 for (int i = 0, e = Phi->getNumIncomingValues(); i < e; i++)
6132 NewPhi->addIncoming(ValMap[Phi->getIncomingValue(i)],
6133 Phi->getIncomingBlock(i));
6134 Visited.insert(NewPhi);
6135 }
6136 // And finally pipe up the stores and bitcasts
6137 for (Instruction *U : Uses) {
6138 if (isa<BitCastInst>(U)) {
6139 DeletedInstrs.insert(U);
6140 U->replaceAllUsesWith(ValMap[U->getOperand(0)]);
6141 } else {
6142 U->setOperand(0,
6143 new BitCastInst(ValMap[U->getOperand(0)], PhiTy, "bc", U));
6144 }
6145 }
6146
6147 // Save the removed phis to be deleted later.
6148 for (PHINode *Phi : PhiNodes)
6149 DeletedInstrs.insert(Phi);
6150 return true;
6151}
6152
6153bool CodeGenPrepare::optimizePhiTypes(Function &F) {
6154 if (!OptimizePhiTypes)
6155 return false;
6156
6157 bool Changed = false;
6158 SmallPtrSet<PHINode *, 4> Visited;
6159 SmallPtrSet<Instruction *, 4> DeletedInstrs;
6160
6161 // Attempt to optimize all the phis in the functions to the correct type.
6162 for (auto &BB : F)
6163 for (auto &Phi : BB.phis())
6164 Changed |= optimizePhiType(&Phi, Visited, DeletedInstrs);
6165
6166 // Remove any old phi's that have been converted.
6167 for (auto *I : DeletedInstrs) {
6168 I->replaceAllUsesWith(PoisonValue::get(I->getType()));
6169 I->eraseFromParent();
6170 }
6171
6172 return Changed;
6173}
6174
6175/// Return true, if an ext(load) can be formed from an extension in
6176/// \p MovedExts.
6177bool CodeGenPrepare::canFormExtLd(
6178 const SmallVectorImpl<Instruction *> &MovedExts, LoadInst *&LI,
6179 Instruction *&Inst, bool HasPromoted) {
6180 for (auto *MovedExtInst : MovedExts) {
6181 if (isa<LoadInst>(MovedExtInst->getOperand(0))) {
6182 LI = cast<LoadInst>(MovedExtInst->getOperand(0));
6183 Inst = MovedExtInst;
6184 break;
6185 }
6186 }
6187 if (!LI)
6188 return false;
6189
6190 // If they're already in the same block, there's nothing to do.
6191 // Make the cheap checks first if we did not promote.
6192 // If we promoted, we need to check if it is indeed profitable.
6193 if (!HasPromoted && LI->getParent() == Inst->getParent())
6194 return false;
6195
6196 return TLI->isExtLoad(LI, Inst, *DL);
6197}
6198
6199/// Move a zext or sext fed by a load into the same basic block as the load,
6200/// unless conditions are unfavorable. This allows SelectionDAG to fold the
6201/// extend into the load.
6202///
6203/// E.g.,
6204/// \code
6205/// %ld = load i32* %addr
6206/// %add = add nuw i32 %ld, 4
6207/// %zext = zext i32 %add to i64
6208// \endcode
6209/// =>
6210/// \code
6211/// %ld = load i32* %addr
6212/// %zext = zext i32 %ld to i64
6213/// %add = add nuw i64 %zext, 4
6214/// \encode
6215/// Note that the promotion in %add to i64 is done in tryToPromoteExts(), which
6216/// allow us to match zext(load i32*) to i64.
6217///
6218/// Also, try to promote the computations used to obtain a sign extended
6219/// value used into memory accesses.
6220/// E.g.,
6221/// \code
6222/// a = add nsw i32 b, 3
6223/// d = sext i32 a to i64
6224/// e = getelementptr ..., i64 d
6225/// \endcode
6226/// =>
6227/// \code
6228/// f = sext i32 b to i64
6229/// a = add nsw i64 f, 3
6230/// e = getelementptr ..., i64 a
6231/// \endcode
6232///
6233/// \p Inst[in/out] the extension may be modified during the process if some
6234/// promotions apply.
6235bool CodeGenPrepare::optimizeExt(Instruction *&Inst) {
6236 bool AllowPromotionWithoutCommonHeader = false;
6237 /// See if it is an interesting sext operations for the address type
6238 /// promotion before trying to promote it, e.g., the ones with the right
6239 /// type and used in memory accesses.
6240 bool ATPConsiderable = TTI->shouldConsiderAddressTypePromotion(
6241 *Inst, AllowPromotionWithoutCommonHeader);
6242 TypePromotionTransaction TPT(RemovedInsts);
6243 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
6244 TPT.getRestorationPoint();
6245 SmallVector<Instruction *, 1> Exts;
6246 SmallVector<Instruction *, 2> SpeculativelyMovedExts;
6247 Exts.push_back(Inst);
6248
6249 bool HasPromoted = tryToPromoteExts(TPT, Exts, SpeculativelyMovedExts);
6250
6251 // Look for a load being extended.
6252 LoadInst *LI = nullptr;
6253 Instruction *ExtFedByLoad;
6254
6255 // Try to promote a chain of computation if it allows to form an extended
6256 // load.
6257 if (canFormExtLd(SpeculativelyMovedExts, LI, ExtFedByLoad, HasPromoted)) {
6258 assert(LI && ExtFedByLoad && "Expect a valid load and extension")(static_cast <bool> (LI && ExtFedByLoad &&
"Expect a valid load and extension") ? void (0) : __assert_fail
("LI && ExtFedByLoad && \"Expect a valid load and extension\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 6258, __extension__ __PRETTY_FUNCTION__
))
;
6259 TPT.commit();
6260 // Move the extend into the same block as the load.
6261 ExtFedByLoad->moveAfter(LI);
6262 ++NumExtsMoved;
6263 Inst = ExtFedByLoad;
6264 return true;
6265 }
6266
6267 // Continue promoting SExts if known as considerable depending on targets.
6268 if (ATPConsiderable &&
6269 performAddressTypePromotion(Inst, AllowPromotionWithoutCommonHeader,
6270 HasPromoted, TPT, SpeculativelyMovedExts))
6271 return true;
6272
6273 TPT.rollback(LastKnownGood);
6274 return false;
6275}
6276
6277// Perform address type promotion if doing so is profitable.
6278// If AllowPromotionWithoutCommonHeader == false, we should find other sext
6279// instructions that sign extended the same initial value. However, if
6280// AllowPromotionWithoutCommonHeader == true, we expect promoting the
6281// extension is just profitable.
6282bool CodeGenPrepare::performAddressTypePromotion(
6283 Instruction *&Inst, bool AllowPromotionWithoutCommonHeader,
6284 bool HasPromoted, TypePromotionTransaction &TPT,
6285 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts) {
6286 bool Promoted = false;
6287 SmallPtrSet<Instruction *, 1> UnhandledExts;
6288 bool AllSeenFirst = true;
6289 for (auto *I : SpeculativelyMovedExts) {
6290 Value *HeadOfChain = I->getOperand(0);
6291 DenseMap<Value *, Instruction *>::iterator AlreadySeen =
6292 SeenChainsForSExt.find(HeadOfChain);
6293 // If there is an unhandled SExt which has the same header, try to promote
6294 // it as well.
6295 if (AlreadySeen != SeenChainsForSExt.end()) {
6296 if (AlreadySeen->second != nullptr)
6297 UnhandledExts.insert(AlreadySeen->second);
6298 AllSeenFirst = false;
6299 }
6300 }
6301
6302 if (!AllSeenFirst || (AllowPromotionWithoutCommonHeader &&
6303 SpeculativelyMovedExts.size() == 1)) {
6304 TPT.commit();
6305 if (HasPromoted)
6306 Promoted = true;
6307 for (auto *I : SpeculativelyMovedExts) {
6308 Value *HeadOfChain = I->getOperand(0);
6309 SeenChainsForSExt[HeadOfChain] = nullptr;
6310 ValToSExtendedUses[HeadOfChain].push_back(I);
6311 }
6312 // Update Inst as promotion happen.
6313 Inst = SpeculativelyMovedExts.pop_back_val();
6314 } else {
6315 // This is the first chain visited from the header, keep the current chain
6316 // as unhandled. Defer to promote this until we encounter another SExt
6317 // chain derived from the same header.
6318 for (auto *I : SpeculativelyMovedExts) {
6319 Value *HeadOfChain = I->getOperand(0);
6320 SeenChainsForSExt[HeadOfChain] = Inst;
6321 }
6322 return false;
6323 }
6324
6325 if (!AllSeenFirst && !UnhandledExts.empty())
6326 for (auto *VisitedSExt : UnhandledExts) {
6327 if (RemovedInsts.count(VisitedSExt))
6328 continue;
6329 TypePromotionTransaction TPT(RemovedInsts);
6330 SmallVector<Instruction *, 1> Exts;
6331 SmallVector<Instruction *, 2> Chains;
6332 Exts.push_back(VisitedSExt);
6333 bool HasPromoted = tryToPromoteExts(TPT, Exts, Chains);
6334 TPT.commit();
6335 if (HasPromoted)
6336 Promoted = true;
6337 for (auto *I : Chains) {
6338 Value *HeadOfChain = I->getOperand(0);
6339 // Mark this as handled.
6340 SeenChainsForSExt[HeadOfChain] = nullptr;
6341 ValToSExtendedUses[HeadOfChain].push_back(I);
6342 }
6343 }
6344 return Promoted;
6345}
6346
6347bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
6348 BasicBlock *DefBB = I->getParent();
6349
6350 // If the result of a {s|z}ext and its source are both live out, rewrite all
6351 // other uses of the source with result of extension.
6352 Value *Src = I->getOperand(0);
6353 if (Src->hasOneUse())
6354 return false;
6355
6356 // Only do this xform if truncating is free.
6357 if (!TLI->isTruncateFree(I->getType(), Src->getType()))
6358 return false;
6359
6360 // Only safe to perform the optimization if the source is also defined in
6361 // this block.
6362 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
6363 return false;
6364
6365 bool DefIsLiveOut = false;
6366 for (User *U : I->users()) {
6367 Instruction *UI = cast<Instruction>(U);
6368
6369 // Figure out which BB this ext is used in.
6370 BasicBlock *UserBB = UI->getParent();
6371 if (UserBB == DefBB) continue;
6372 DefIsLiveOut = true;
6373 break;
6374 }
6375 if (!DefIsLiveOut)
6376 return false;
6377
6378 // Make sure none of the uses are PHI nodes.
6379 for (User *U : Src->users()) {
6380 Instruction *UI = cast<Instruction>(U);
6381 BasicBlock *UserBB = UI->getParent();
6382 if (UserBB == DefBB) continue;
6383 // Be conservative. We don't want this xform to end up introducing
6384 // reloads just before load / store instructions.
6385 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
6386 return false;
6387 }
6388
6389 // InsertedTruncs - Only insert one trunc in each block once.
6390 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
6391
6392 bool MadeChange = false;
6393 for (Use &U : Src->uses()) {
6394 Instruction *User = cast<Instruction>(U.getUser());
6395
6396 // Figure out which BB this ext is used in.
6397 BasicBlock *UserBB = User->getParent();
6398 if (UserBB == DefBB) continue;
6399
6400 // Both src and def are live in this block. Rewrite the use.
6401 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
6402
6403 if (!InsertedTrunc) {
6404 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
6405 assert(InsertPt != UserBB->end())(static_cast <bool> (InsertPt != UserBB->end()) ? void
(0) : __assert_fail ("InsertPt != UserBB->end()", "llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 6405, __extension__ __PRETTY_FUNCTION__))
;
6406 InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
6407 InsertedInsts.insert(InsertedTrunc);
6408 }
6409
6410 // Replace a use of the {s|z}ext source with a use of the result.
6411 U = InsertedTrunc;
6412 ++NumExtUses;
6413 MadeChange = true;
6414 }
6415
6416 return MadeChange;
6417}
6418
6419// Find loads whose uses only use some of the loaded value's bits. Add an "and"
6420// just after the load if the target can fold this into one extload instruction,
6421// with the hope of eliminating some of the other later "and" instructions using
6422// the loaded value. "and"s that are made trivially redundant by the insertion
6423// of the new "and" are removed by this function, while others (e.g. those whose
6424// path from the load goes through a phi) are left for isel to potentially
6425// remove.
6426//
6427// For example:
6428//
6429// b0:
6430// x = load i32
6431// ...
6432// b1:
6433// y = and x, 0xff
6434// z = use y
6435//
6436// becomes:
6437//
6438// b0:
6439// x = load i32
6440// x' = and x, 0xff
6441// ...
6442// b1:
6443// z = use x'
6444//
6445// whereas:
6446//
6447// b0:
6448// x1 = load i32
6449// ...
6450// b1:
6451// x2 = load i32
6452// ...
6453// b2:
6454// x = phi x1, x2
6455// y = and x, 0xff
6456//
6457// becomes (after a call to optimizeLoadExt for each load):
6458//
6459// b0:
6460// x1 = load i32
6461// x1' = and x1, 0xff
6462// ...
6463// b1:
6464// x2 = load i32
6465// x2' = and x2, 0xff
6466// ...
6467// b2:
6468// x = phi x1', x2'
6469// y = and x, 0xff
6470bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
6471 if (!Load->isSimple() || !Load->getType()->isIntOrPtrTy())
6472 return false;
6473
6474 // Skip loads we've already transformed.
6475 if (Load->hasOneUse() &&
6476 InsertedInsts.count(cast<Instruction>(*Load->user_begin())))
6477 return false;
6478
6479 // Look at all uses of Load, looking through phis, to determine how many bits
6480 // of the loaded value are needed.
6481 SmallVector<Instruction *, 8> WorkList;
6482 SmallPtrSet<Instruction *, 16> Visited;
6483 SmallVector<Instruction *, 8> AndsToMaybeRemove;
6484 for (auto *U : Load->users())
6485 WorkList.push_back(cast<Instruction>(U));
6486
6487 EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
6488 unsigned BitWidth = LoadResultVT.getSizeInBits();
6489 // If the BitWidth is 0, do not try to optimize the type
6490 if (BitWidth == 0)
6491 return false;
6492
6493 APInt DemandBits(BitWidth, 0);
6494 APInt WidestAndBits(BitWidth, 0);
6495
6496 while (!WorkList.empty()) {
6497 Instruction *I = WorkList.pop_back_val();
6498
6499 // Break use-def graph loops.
6500 if (!Visited.insert(I).second)
6501 continue;
6502
6503 // For a PHI node, push all of its users.
6504 if (auto *Phi = dyn_cast<PHINode>(I)) {
6505 for (auto *U : Phi->users())
6506 WorkList.push_back(cast<Instruction>(U));
6507 continue;
6508 }
6509
6510 switch (I->getOpcode()) {
6511 case Instruction::And: {
6512 auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
6513 if (!AndC)
6514 return false;
6515 APInt AndBits = AndC->getValue();
6516 DemandBits |= AndBits;
6517 // Keep track of the widest and mask we see.
6518 if (AndBits.ugt(WidestAndBits))
6519 WidestAndBits = AndBits;
6520 if (AndBits == WidestAndBits && I->getOperand(0) == Load)
6521 AndsToMaybeRemove.push_back(I);
6522 break;
6523 }
6524
6525 case Instruction::Shl: {
6526 auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
6527 if (!ShlC)
6528 return false;
6529 uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
6530 DemandBits.setLowBits(BitWidth - ShiftAmt);
6531 break;
6532 }
6533
6534 case Instruction::Trunc: {
6535 EVT TruncVT = TLI->getValueType(*DL, I->getType());
6536 unsigned TruncBitWidth = TruncVT.getSizeInBits();
6537 DemandBits.setLowBits(TruncBitWidth);
6538 break;
6539 }
6540
6541 default:
6542 return false;
6543 }
6544 }
6545
6546 uint32_t ActiveBits = DemandBits.getActiveBits();
6547 // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
6548 // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example,
6549 // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but
6550 // (and (load x) 1) is not matched as a single instruction, rather as a LDR
6551 // followed by an AND.
6552 // TODO: Look into removing this restriction by fixing backends to either
6553 // return false for isLoadExtLegal for i1 or have them select this pattern to
6554 // a single instruction.
6555 //
6556 // Also avoid hoisting if we didn't see any ands with the exact DemandBits
6557 // mask, since these are the only ands that will be removed by isel.
6558 if (ActiveBits <= 1 || !DemandBits.isMask(ActiveBits) ||
6559 WidestAndBits != DemandBits)
6560 return false;
6561
6562 LLVMContext &Ctx = Load->getType()->getContext();
6563 Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
6564 EVT TruncVT = TLI->getValueType(*DL, TruncTy);
6565
6566 // Reject cases that won't be matched as extloads.
6567 if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
6568 !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT))
6569 return false;
6570
6571 IRBuilder<> Builder(Load->getNextNode());
6572 auto *NewAnd = cast<Instruction>(
6573 Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
6574 // Mark this instruction as "inserted by CGP", so that other
6575 // optimizations don't touch it.
6576 InsertedInsts.insert(NewAnd);
6577
6578 // Replace all uses of load with new and (except for the use of load in the
6579 // new and itself).
6580 Load->replaceAllUsesWith(NewAnd);
6581 NewAnd->setOperand(0, Load);
6582
6583 // Remove any and instructions that are now redundant.
6584 for (auto *And : AndsToMaybeRemove)
6585 // Check that the and mask is the same as the one we decided to put on the
6586 // new and.
6587 if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
6588 And->replaceAllUsesWith(NewAnd);
6589 if (&*CurInstIterator == And)
6590 CurInstIterator = std::next(And->getIterator());
6591 And->eraseFromParent();
6592 ++NumAndUses;
6593 }
6594
6595 ++NumAndsAdded;
6596 return true;
6597}
6598
6599/// Check if V (an operand of a select instruction) is an expensive instruction
6600/// that is only used once.
6601static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
6602 auto *I = dyn_cast<Instruction>(V);
6603 // If it's safe to speculatively execute, then it should not have side
6604 // effects; therefore, it's safe to sink and possibly *not* execute.
6605 return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
6606 TTI->getInstructionCost(I, TargetTransformInfo::TCK_SizeAndLatency) >=
6607 TargetTransformInfo::TCC_Expensive;
6608}
6609
6610/// Returns true if a SelectInst should be turned into an explicit branch.
6611static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
6612 const TargetLowering *TLI,
6613 SelectInst *SI) {
6614 // If even a predictable select is cheap, then a branch can't be cheaper.
6615 if (!TLI->isPredictableSelectExpensive())
6616 return false;
6617
6618 // FIXME: This should use the same heuristics as IfConversion to determine
6619 // whether a select is better represented as a branch.
6620
6621 // If metadata tells us that the select condition is obviously predictable,
6622 // then we want to replace the select with a branch.
6623 uint64_t TrueWeight, FalseWeight;
6624 if (extractBranchWeights(*SI, TrueWeight, FalseWeight)) {
6625 uint64_t Max = std::max(TrueWeight, FalseWeight);
6626 uint64_t Sum = TrueWeight + FalseWeight;
6627 if (Sum != 0) {
6628 auto Probability = BranchProbability::getBranchProbability(Max, Sum);
6629 if (Probability > TTI->getPredictableBranchThreshold())
6630 return true;
6631 }
6632 }
6633
6634 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
6635
6636 // If a branch is predictable, an out-of-order CPU can avoid blocking on its
6637 // comparison condition. If the compare has more than one use, there's
6638 // probably another cmov or setcc around, so it's not worth emitting a branch.
6639 if (!Cmp || !Cmp->hasOneUse())
6640 return false;
6641
6642 // If either operand of the select is expensive and only needed on one side
6643 // of the select, we should form a branch.
6644 if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
6645 sinkSelectOperand(TTI, SI->getFalseValue()))
6646 return true;
6647
6648 return false;
6649}
6650
6651/// If \p isTrue is true, return the true value of \p SI, otherwise return
6652/// false value of \p SI. If the true/false value of \p SI is defined by any
6653/// select instructions in \p Selects, look through the defining select
6654/// instruction until the true/false value is not defined in \p Selects.
6655static Value *getTrueOrFalseValue(
6656 SelectInst *SI, bool isTrue,
6657 const SmallPtrSet<const Instruction *, 2> &Selects) {
6658 Value *V = nullptr;
6659
6660 for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI);
6661 DefSI = dyn_cast<SelectInst>(V)) {
6662 assert(DefSI->getCondition() == SI->getCondition() &&(static_cast <bool> (DefSI->getCondition() == SI->
getCondition() && "The condition of DefSI does not match with SI"
) ? void (0) : __assert_fail ("DefSI->getCondition() == SI->getCondition() && \"The condition of DefSI does not match with SI\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 6663, __extension__ __PRETTY_FUNCTION__
))
6663 "The condition of DefSI does not match with SI")(static_cast <bool> (DefSI->getCondition() == SI->
getCondition() && "The condition of DefSI does not match with SI"
) ? void (0) : __assert_fail ("DefSI->getCondition() == SI->getCondition() && \"The condition of DefSI does not match with SI\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 6663, __extension__ __PRETTY_FUNCTION__
))
;
6664 V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
6665 }
6666
6667 assert(V && "Failed to get select true/false value")(static_cast <bool> (V && "Failed to get select true/false value"
) ? void (0) : __assert_fail ("V && \"Failed to get select true/false value\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 6667, __extension__ __PRETTY_FUNCTION__
))
;
6668 return V;
6669}
6670
6671bool CodeGenPrepare::optimizeShiftInst(BinaryOperator *Shift) {
6672 assert(Shift->isShift() && "Expected a shift")(static_cast <bool> (Shift->isShift() && "Expected a shift"
) ? void (0) : __assert_fail ("Shift->isShift() && \"Expected a shift\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 6672, __extension__ __PRETTY_FUNCTION__
))
;
6673
6674 // If this is (1) a vector shift, (2) shifts by scalars are cheaper than
6675 // general vector shifts, and (3) the shift amount is a select-of-splatted
6676 // values, hoist the shifts before the select:
6677 // shift Op0, (select Cond, TVal, FVal) -->
6678 // select Cond, (shift Op0, TVal), (shift Op0, FVal)
6679 //
6680 // This is inverting a generic IR transform when we know that the cost of a
6681 // general vector shift is more than the cost of 2 shift-by-scalars.
6682 // We can't do this effectively in SDAG because we may not be able to
6683 // determine if the select operands are splats from within a basic block.
6684 Type *Ty = Shift->getType();
6685 if (!Ty->isVectorTy() || !TLI->isVectorShiftByScalarCheap(Ty))
6686 return false;
6687 Value *Cond, *TVal, *FVal;
6688 if (!match(Shift->getOperand(1),
6689 m_OneUse(m_Select(m_Value(Cond), m_Value(TVal), m_Value(FVal)))))
6690 return false;
6691 if (!isSplatValue(TVal) || !isSplatValue(FVal))
6692 return false;
6693
6694 IRBuilder<> Builder(Shift);
6695 BinaryOperator::BinaryOps Opcode = Shift->getOpcode();
6696 Value *NewTVal = Builder.CreateBinOp(Opcode, Shift->getOperand(0), TVal);
6697 Value *NewFVal = Builder.CreateBinOp(Opcode, Shift->getOperand(0), FVal);
6698 Value *NewSel = Builder.CreateSelect(Cond, NewTVal, NewFVal);
6699 Shift->replaceAllUsesWith(NewSel);
6700 Shift->eraseFromParent();
6701 return true;
6702}
6703
6704bool CodeGenPrepare::optimizeFunnelShift(IntrinsicInst *Fsh) {
6705 Intrinsic::ID Opcode = Fsh->getIntrinsicID();
6706 assert((Opcode == Intrinsic::fshl || Opcode == Intrinsic::fshr) &&(static_cast <bool> ((Opcode == Intrinsic::fshl || Opcode
== Intrinsic::fshr) && "Expected a funnel shift") ? void
(0) : __assert_fail ("(Opcode == Intrinsic::fshl || Opcode == Intrinsic::fshr) && \"Expected a funnel shift\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 6707, __extension__ __PRETTY_FUNCTION__
))
6707 "Expected a funnel shift")(static_cast <bool> ((Opcode == Intrinsic::fshl || Opcode
== Intrinsic::fshr) && "Expected a funnel shift") ? void
(0) : __assert_fail ("(Opcode == Intrinsic::fshl || Opcode == Intrinsic::fshr) && \"Expected a funnel shift\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 6707, __extension__ __PRETTY_FUNCTION__
))
;
6708
6709 // If this is (1) a vector funnel shift, (2) shifts by scalars are cheaper
6710 // than general vector shifts, and (3) the shift amount is select-of-splatted
6711 // values, hoist the funnel shifts before the select:
6712 // fsh Op0, Op1, (select Cond, TVal, FVal) -->
6713 // select Cond, (fsh Op0, Op1, TVal), (fsh Op0, Op1, FVal)
6714 //
6715 // This is inverting a generic IR transform when we know that the cost of a
6716 // general vector shift is more than the cost of 2 shift-by-scalars.
6717 // We can't do this effectively in SDAG because we may not be able to
6718 // determine if the select operands are splats from within a basic block.
6719 Type *Ty = Fsh->getType();
6720 if (!Ty->isVectorTy() || !TLI->isVectorShiftByScalarCheap(Ty))
6721 return false;
6722 Value *Cond, *TVal, *FVal;
6723 if (!match(Fsh->getOperand(2),
6724 m_OneUse(m_Select(m_Value(Cond), m_Value(TVal), m_Value(FVal)))))
6725 return false;
6726 if (!isSplatValue(TVal) || !isSplatValue(FVal))
6727 return false;
6728
6729 IRBuilder<> Builder(Fsh);
6730 Value *X = Fsh->getOperand(0), *Y = Fsh->getOperand(1);
6731 Value *NewTVal = Builder.CreateIntrinsic(Opcode, Ty, { X, Y, TVal });
6732 Value *NewFVal = Builder.CreateIntrinsic(Opcode, Ty, { X, Y, FVal });
6733 Value *NewSel = Builder.CreateSelect(Cond, NewTVal, NewFVal);
6734 Fsh->replaceAllUsesWith(NewSel);
6735 Fsh->eraseFromParent();
6736 return true;
6737}
6738
6739/// If we have a SelectInst that will likely profit from branch prediction,
6740/// turn it into a branch.
6741bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
6742 if (DisableSelectToBranch)
6743 return false;
6744
6745 // If the SelectOptimize pass is enabled, selects have already been optimized.
6746 if (!getCGPassBuilderOption().DisableSelectOptimize)
6747 return false;
6748
6749 // Find all consecutive select instructions that share the same condition.
6750 SmallVector<SelectInst *, 2> ASI;
6751 ASI.push_back(SI);
6752 for (BasicBlock::iterator It = ++BasicBlock::iterator(SI);
6753 It != SI->getParent()->end(); ++It) {
6754 SelectInst *I = dyn_cast<SelectInst>(&*It);
6755 if (I && SI->getCondition() == I->getCondition()) {
6756 ASI.push_back(I);
6757 } else {
6758 break;
6759 }
6760 }
6761
6762 SelectInst *LastSI = ASI.back();
6763 // Increment the current iterator to skip all the rest of select instructions
6764 // because they will be either "not lowered" or "all lowered" to branch.
6765 CurInstIterator = std::next(LastSI->getIterator());
6766
6767 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
6768
6769 // Can we convert the 'select' to CF ?
6770 if (VectorCond || SI->getMetadata(LLVMContext::MD_unpredictable))
6771 return false;
6772
6773 TargetLowering::SelectSupportKind SelectKind;
6774 if (VectorCond)
6775 SelectKind = TargetLowering::VectorMaskSelect;
6776 else if (SI->getType()->isVectorTy())
6777 SelectKind = TargetLowering::ScalarCondVectorVal;
6778 else
6779 SelectKind = TargetLowering::ScalarValSelect;
6780
6781 if (TLI->isSelectSupported(SelectKind) &&
6782 (!isFormingBranchFromSelectProfitable(TTI, TLI, SI) || OptSize ||
6783 llvm::shouldOptimizeForSize(SI->getParent(), PSI, BFI.get())))
6784 return false;
6785
6786 // The DominatorTree needs to be rebuilt by any consumers after this
6787 // transformation. We simply reset here rather than setting the ModifiedDT
6788 // flag to avoid restarting the function walk in runOnFunction for each
6789 // select optimized.
6790 DT.reset();
6791
6792 // Transform a sequence like this:
6793 // start:
6794 // %cmp = cmp uge i32 %a, %b
6795 // %sel = select i1 %cmp, i32 %c, i32 %d
6796 //
6797 // Into:
6798 // start:
6799 // %cmp = cmp uge i32 %a, %b
6800 // %cmp.frozen = freeze %cmp
6801 // br i1 %cmp.frozen, label %select.true, label %select.false
6802 // select.true:
6803 // br label %select.end
6804 // select.false:
6805 // br label %select.end
6806 // select.end:
6807 // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
6808 //
6809 // %cmp should be frozen, otherwise it may introduce undefined behavior.
6810 // In addition, we may sink instructions that produce %c or %d from
6811 // the entry block into the destination(s) of the new branch.
6812 // If the true or false blocks do not contain a sunken instruction, that
6813 // block and its branch may be optimized away. In that case, one side of the
6814 // first branch will point directly to select.end, and the corresponding PHI
6815 // predecessor block will be the start block.
6816
6817 // First, we split the block containing the select into 2 blocks.
6818 BasicBlock *StartBlock = SI->getParent();
6819 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI));
6820 BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
6821 BFI->setBlockFreq(EndBlock, BFI->getBlockFreq(StartBlock).getFrequency());
6822
6823 // Delete the unconditional branch that was just created by the split.
6824 StartBlock->getTerminator()->eraseFromParent();
6825
6826 // These are the new basic blocks for the conditional branch.
6827 // At least one will become an actual new basic block.
6828 BasicBlock *TrueBlock = nullptr;
6829 BasicBlock *FalseBlock = nullptr;
6830 BranchInst *TrueBranch = nullptr;
6831 BranchInst *FalseBranch = nullptr;
6832
6833 // Sink expensive instructions into the conditional blocks to avoid executing
6834 // them speculatively.
6835 for (SelectInst *SI : ASI) {
6836 if (sinkSelectOperand(TTI, SI->getTrueValue())) {
6837 if (TrueBlock == nullptr) {
6838 TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink",
6839 EndBlock->getParent(), EndBlock);
6840 TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
6841 TrueBranch->setDebugLoc(SI->getDebugLoc());
6842 }
6843 auto *TrueInst = cast<Instruction>(SI->getTrueValue());
6844 TrueInst->moveBefore(TrueBranch);
6845 }
6846 if (sinkSelectOperand(TTI, SI->getFalseValue())) {
6847 if (FalseBlock == nullptr) {
6848 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink",
6849 EndBlock->getParent(), EndBlock);
6850 FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
6851 FalseBranch->setDebugLoc(SI->getDebugLoc());
6852 }
6853 auto *FalseInst = cast<Instruction>(SI->getFalseValue());
6854 FalseInst->moveBefore(FalseBranch);
6855 }
6856 }
6857
6858 // If there was nothing to sink, then arbitrarily choose the 'false' side
6859 // for a new input value to the PHI.
6860 if (TrueBlock == FalseBlock) {
6861 assert(TrueBlock == nullptr &&(static_cast <bool> (TrueBlock == nullptr && "Unexpected basic block transform while optimizing select"
) ? void (0) : __assert_fail ("TrueBlock == nullptr && \"Unexpected basic block transform while optimizing select\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 6862, __extension__ __PRETTY_FUNCTION__
))
6862 "Unexpected basic block transform while optimizing select")(static_cast <bool> (TrueBlock == nullptr && "Unexpected basic block transform while optimizing select"
) ? void (0) : __assert_fail ("TrueBlock == nullptr && \"Unexpected basic block transform while optimizing select\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 6862, __extension__ __PRETTY_FUNCTION__
))
;
6863
6864 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
6865 EndBlock->getParent(), EndBlock);
6866 auto *FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
6867 FalseBranch->setDebugLoc(SI->getDebugLoc());
6868 }
6869
6870 // Insert the real conditional branch based on the original condition.
6871 // If we did not create a new block for one of the 'true' or 'false' paths
6872 // of the condition, it means that side of the branch goes to the end block
6873 // directly and the path originates from the start block from the point of
6874 // view of the new PHI.
6875 BasicBlock *TT, *FT;
6876 if (TrueBlock == nullptr) {
6877 TT = EndBlock;
6878 FT = FalseBlock;
6879 TrueBlock = StartBlock;
6880 } else if (FalseBlock == nullptr) {
6881 TT = TrueBlock;
6882 FT = EndBlock;
6883 FalseBlock = StartBlock;
6884 } else {
6885 TT = TrueBlock;
6886 FT = FalseBlock;
6887 }
6888 IRBuilder<> IB(SI);
6889 auto *CondFr = IB.CreateFreeze(SI->getCondition(), SI->getName() + ".frozen");
6890 IB.CreateCondBr(CondFr, TT, FT, SI);
6891
6892 SmallPtrSet<const Instruction *, 2> INS;
6893 INS.insert(ASI.begin(), ASI.end());
6894 // Use reverse iterator because later select may use the value of the
6895 // earlier select, and we need to propagate value through earlier select
6896 // to get the PHI operand.
6897 for (SelectInst *SI : llvm::reverse(ASI)) {
6898 // The select itself is replaced with a PHI Node.
6899 PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
6900 PN->takeName(SI);
6901 PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock);
6902 PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock);
6903 PN->setDebugLoc(SI->getDebugLoc());
6904
6905 SI->replaceAllUsesWith(PN);
6906 SI->eraseFromParent();
6907 INS.erase(SI);
6908 ++NumSelectsExpanded;
6909 }
6910
6911 // Instruct OptimizeBlock to skip to the next block.
6912 CurInstIterator = StartBlock->end();
6913 return true;
6914}
6915
6916/// Some targets only accept certain types for splat inputs. For example a VDUP
6917/// in MVE takes a GPR (integer) register, and the instruction that incorporate
6918/// a VDUP (such as a VADD qd, qm, rm) also require a gpr register.
6919bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
6920 // Accept shuf(insertelem(undef/poison, val, 0), undef/poison, <0,0,..>) only
6921 if (!match(SVI, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()),
6922 m_Undef(), m_ZeroMask())))
6923 return false;
6924 Type *NewType = TLI->shouldConvertSplatType(SVI);
6925 if (!NewType)
6926 return false;
6927
6928 auto *SVIVecType = cast<FixedVectorType>(SVI->getType());
6929 assert(!NewType->isVectorTy() && "Expected a scalar type!")(static_cast <bool> (!NewType->isVectorTy() &&
"Expected a scalar type!") ? void (0) : __assert_fail ("!NewType->isVectorTy() && \"Expected a scalar type!\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 6929, __extension__ __PRETTY_FUNCTION__
))
;
6930 assert(NewType->getScalarSizeInBits() == SVIVecType->getScalarSizeInBits() &&(static_cast <bool> (NewType->getScalarSizeInBits() ==
SVIVecType->getScalarSizeInBits() && "Expected a type of the same size!"
) ? void (0) : __assert_fail ("NewType->getScalarSizeInBits() == SVIVecType->getScalarSizeInBits() && \"Expected a type of the same size!\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 6931, __extension__ __PRETTY_FUNCTION__
))
6931 "Expected a type of the same size!")(static_cast <bool> (NewType->getScalarSizeInBits() ==
SVIVecType->getScalarSizeInBits() && "Expected a type of the same size!"
) ? void (0) : __assert_fail ("NewType->getScalarSizeInBits() == SVIVecType->getScalarSizeInBits() && \"Expected a type of the same size!\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 6931, __extension__ __PRETTY_FUNCTION__
))
;
6932 auto *NewVecType =
6933 FixedVectorType::get(NewType, SVIVecType->getNumElements());
6934
6935 // Create a bitcast (shuffle (insert (bitcast(..))))
6936 IRBuilder<> Builder(SVI->getContext());
6937 Builder.SetInsertPoint(SVI);
6938 Value *BC1 = Builder.CreateBitCast(
6939 cast<Instruction>(SVI->getOperand(0))->getOperand(1), NewType);
6940 Value *Shuffle = Builder.CreateVectorSplat(NewVecType->getNumElements(), BC1);
6941 Value *BC2 = Builder.CreateBitCast(Shuffle, SVIVecType);
6942
6943 SVI->replaceAllUsesWith(BC2);
6944 RecursivelyDeleteTriviallyDeadInstructions(
6945 SVI, TLInfo, nullptr, [&](Value *V) { removeAllAssertingVHReferences(V); });
6946
6947 // Also hoist the bitcast up to its operand if it they are not in the same
6948 // block.
6949 if (auto *BCI = dyn_cast<Instruction>(BC1))
6950 if (auto *Op = dyn_cast<Instruction>(BCI->getOperand(0)))
6951 if (BCI->getParent() != Op->getParent() && !isa<PHINode>(Op) &&
6952 !Op->isTerminator() && !Op->isEHPad())
6953 BCI->moveAfter(Op);
6954
6955 return true;
6956}
6957
6958bool CodeGenPrepare::tryToSinkFreeOperands(Instruction *I) {
6959 // If the operands of I can be folded into a target instruction together with
6960 // I, duplicate and sink them.
6961 SmallVector<Use *, 4> OpsToSink;
6962 if (!TLI->shouldSinkOperands(I, OpsToSink))
6963 return false;
6964
6965 // OpsToSink can contain multiple uses in a use chain (e.g.
6966 // (%u1 with %u1 = shufflevector), (%u2 with %u2 = zext %u1)). The dominating
6967 // uses must come first, so we process the ops in reverse order so as to not
6968 // create invalid IR.
6969 BasicBlock *TargetBB = I->getParent();
6970 bool Changed = false;
6971 SmallVector<Use *, 4> ToReplace;
6972 Instruction *InsertPoint = I;
6973 DenseMap<const Instruction *, unsigned long> InstOrdering;
6974 unsigned long InstNumber = 0;
6975 for (const auto &I : *TargetBB)
6976 InstOrdering[&I] = InstNumber++;
6977
6978 for (Use *U : reverse(OpsToSink)) {
6979 auto *UI = cast<Instruction>(U->get());
6980 if (isa<PHINode>(UI))
6981 continue;
6982 if (UI->getParent() == TargetBB) {
6983 if (InstOrdering[UI] < InstOrdering[InsertPoint])
6984 InsertPoint = UI;
6985 continue;
6986 }
6987 ToReplace.push_back(U);
6988 }
6989
6990 SetVector<Instruction *> MaybeDead;
6991 DenseMap<Instruction *, Instruction *> NewInstructions;
6992 for (Use *U : ToReplace) {
6993 auto *UI = cast<Instruction>(U->get());
6994 Instruction *NI = UI->clone();
6995 NewInstructions[UI] = NI;
6996 MaybeDead.insert(UI);
6997 LLVM_DEBUG(dbgs() << "Sinking " << *UI << " to user " << *I << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Sinking " << *UI
<< " to user " << *I << "\n"; } } while (false
)
;
6998 NI->insertBefore(InsertPoint);
6999 InsertPoint = NI;
7000 InsertedInsts.insert(NI);
7001
7002 // Update the use for the new instruction, making sure that we update the
7003 // sunk instruction uses, if it is part of a chain that has already been
7004 // sunk.
7005 Instruction *OldI = cast<Instruction>(U->getUser());
7006 if (NewInstructions.count(OldI))
7007 NewInstructions[OldI]->setOperand(U->getOperandNo(), NI);
7008 else
7009 U->set(NI);
7010 Changed = true;
7011 }
7012
7013 // Remove instructions that are dead after sinking.
7014 for (auto *I : MaybeDead) {
7015 if (!I->hasNUsesOrMore(1)) {
7016 LLVM_DEBUG(dbgs() << "Removing dead instruction: " << *I << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Removing dead instruction: "
<< *I << "\n"; } } while (false)
;
7017 I->eraseFromParent();
7018 }
7019 }
7020
7021 return Changed;
7022}
7023
7024bool CodeGenPrepare::optimizeSwitchType(SwitchInst *SI) {
7025 Value *Cond = SI->getCondition();
7026 Type *OldType = Cond->getType();
7027 LLVMContext &Context = Cond->getContext();
7028 EVT OldVT = TLI->getValueType(*DL, OldType);
7029 MVT RegType = TLI->getPreferredSwitchConditionType(Context, OldVT);
7030 unsigned RegWidth = RegType.getSizeInBits();
7031
7032 if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
7033 return false;
7034
7035 // If the register width is greater than the type width, expand the condition
7036 // of the switch instruction and each case constant to the width of the
7037 // register. By widening the type of the switch condition, subsequent
7038 // comparisons (for case comparisons) will not need to be extended to the
7039 // preferred register width, so we will potentially eliminate N-1 extends,
7040 // where N is the number of cases in the switch.
7041 auto *NewType = Type::getIntNTy(Context, RegWidth);
7042
7043 // Extend the switch condition and case constants using the target preferred
7044 // extend unless the switch condition is a function argument with an extend
7045 // attribute. In that case, we can avoid an unnecessary mask/extension by
7046 // matching the argument extension instead.
7047 Instruction::CastOps ExtType = Instruction::ZExt;
7048 // Some targets prefer SExt over ZExt.
7049 if (TLI->isSExtCheaperThanZExt(OldVT, RegType))
7050 ExtType = Instruction::SExt;
7051
7052 if (auto *Arg = dyn_cast<Argument>(Cond)) {
7053 if (Arg->hasSExtAttr())
7054 ExtType = Instruction::SExt;
7055 if (Arg->hasZExtAttr())
7056 ExtType = Instruction::ZExt;
7057 }
7058
7059 auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
7060 ExtInst->insertBefore(SI);
7061 ExtInst->setDebugLoc(SI->getDebugLoc());
7062 SI->setCondition(ExtInst);
7063 for (auto Case : SI->cases()) {
7064 const APInt &NarrowConst = Case.getCaseValue()->getValue();
7065 APInt WideConst = (ExtType == Instruction::ZExt) ?
7066 NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth);
7067 Case.setValue(ConstantInt::get(Context, WideConst));
7068 }
7069
7070 return true;
7071}
7072
7073bool CodeGenPrepare::optimizeSwitchPhiConstants(SwitchInst *SI) {
7074 // The SCCP optimization tends to produce code like this:
7075 // switch(x) { case 42: phi(42, ...) }
7076 // Materializing the constant for the phi-argument needs instructions; So we
7077 // change the code to:
7078 // switch(x) { case 42: phi(x, ...) }
7079
7080 Value *Condition = SI->getCondition();
7081 // Avoid endless loop in degenerate case.
7082 if (isa<ConstantInt>(*Condition))
7083 return false;
7084
7085 bool Changed = false;
7086 BasicBlock *SwitchBB = SI->getParent();
7087 Type *ConditionType = Condition->getType();
7088
7089 for (const SwitchInst::CaseHandle &Case : SI->cases()) {
7090 ConstantInt *CaseValue = Case.getCaseValue();
7091 BasicBlock *CaseBB = Case.getCaseSuccessor();
7092 // Set to true if we previously checked that `CaseBB` is only reached by
7093 // a single case from this switch.
7094 bool CheckedForSinglePred = false;
7095 for (PHINode &PHI : CaseBB->phis()) {
7096 Type *PHIType = PHI.getType();
7097 // If ZExt is free then we can also catch patterns like this:
7098 // switch((i32)x) { case 42: phi((i64)42, ...); }
7099 // and replace `(i64)42` with `zext i32 %x to i64`.
7100 bool TryZExt =
7101 PHIType->isIntegerTy() &&
7102 PHIType->getIntegerBitWidth() > ConditionType->getIntegerBitWidth() &&
7103 TLI->isZExtFree(ConditionType, PHIType);
7104 if (PHIType == ConditionType || TryZExt) {
7105 // Set to true to skip this case because of multiple preds.
7106 bool SkipCase = false;
7107 Value *Replacement = nullptr;
7108 for (unsigned I = 0, E = PHI.getNumIncomingValues(); I != E; I++) {
7109 Value *PHIValue = PHI.getIncomingValue(I);
7110 if (PHIValue != CaseValue) {
7111 if (!TryZExt)
7112 continue;
7113 ConstantInt *PHIValueInt = dyn_cast<ConstantInt>(PHIValue);
7114 if (!PHIValueInt ||
7115 PHIValueInt->getValue() !=
7116 CaseValue->getValue().zext(PHIType->getIntegerBitWidth()))
7117 continue;
7118 }
7119 if (PHI.getIncomingBlock(I) != SwitchBB)
7120 continue;
7121 // We cannot optimize if there are multiple case labels jumping to
7122 // this block. This check may get expensive when there are many
7123 // case labels so we test for it last.
7124 if (!CheckedForSinglePred) {
7125 CheckedForSinglePred = true;
7126 if (SI->findCaseDest(CaseBB) == nullptr) {
7127 SkipCase = true;
7128 break;
7129 }
7130 }
7131
7132 if (Replacement == nullptr) {
7133 if (PHIValue == CaseValue) {
7134 Replacement = Condition;
7135 } else {
7136 IRBuilder<> Builder(SI);
7137 Replacement = Builder.CreateZExt(Condition, PHIType);
7138 }
7139 }
7140 PHI.setIncomingValue(I, Replacement);
7141 Changed = true;
7142 }
7143 if (SkipCase)
7144 break;
7145 }
7146 }
7147 }
7148 return Changed;
7149}
7150
7151bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
7152 bool Changed = optimizeSwitchType(SI);
7153 Changed |= optimizeSwitchPhiConstants(SI);
7154 return Changed;
7155}
7156
7157namespace {
7158
7159/// Helper class to promote a scalar operation to a vector one.
7160/// This class is used to move downward extractelement transition.
7161/// E.g.,
7162/// a = vector_op <2 x i32>
7163/// b = extractelement <2 x i32> a, i32 0
7164/// c = scalar_op b
7165/// store c
7166///
7167/// =>
7168/// a = vector_op <2 x i32>
7169/// c = vector_op a (equivalent to scalar_op on the related lane)
7170/// * d = extractelement <2 x i32> c, i32 0
7171/// * store d
7172/// Assuming both extractelement and store can be combine, we get rid of the
7173/// transition.
7174class VectorPromoteHelper {
7175 /// DataLayout associated with the current module.
7176 const DataLayout &DL;
7177
7178 /// Used to perform some checks on the legality of vector operations.
7179 const TargetLowering &TLI;
7180
7181 /// Used to estimated the cost of the promoted chain.
7182 const TargetTransformInfo &TTI;
7183
7184 /// The transition being moved downwards.
7185 Instruction *Transition;
7186
7187 /// The sequence of instructions to be promoted.
7188 SmallVector<Instruction *, 4> InstsToBePromoted;
7189
7190 /// Cost of combining a store and an extract.
7191 unsigned StoreExtractCombineCost;
7192
7193 /// Instruction that will be combined with the transition.
7194 Instruction *CombineInst = nullptr;
7195
7196 /// The instruction that represents the current end of the transition.
7197 /// Since we are faking the promotion until we reach the end of the chain
7198 /// of computation, we need a way to get the current end of the transition.
7199 Instruction *getEndOfTransition() const {
7200 if (InstsToBePromoted.empty())
7201 return Transition;
7202 return InstsToBePromoted.back();
7203 }
7204
7205 /// Return the index of the original value in the transition.
7206 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
7207 /// c, is at index 0.
7208 unsigned getTransitionOriginalValueIdx() const {
7209 assert(isa<ExtractElementInst>(Transition) &&(static_cast <bool> (isa<ExtractElementInst>(Transition
) && "Other kind of transitions are not supported yet"
) ? void (0) : __assert_fail ("isa<ExtractElementInst>(Transition) && \"Other kind of transitions are not supported yet\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 7210, __extension__ __PRETTY_FUNCTION__
))
7210 "Other kind of transitions are not supported yet")(static_cast <bool> (isa<ExtractElementInst>(Transition
) && "Other kind of transitions are not supported yet"
) ? void (0) : __assert_fail ("isa<ExtractElementInst>(Transition) && \"Other kind of transitions are not supported yet\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 7210, __extension__ __PRETTY_FUNCTION__
))
;
7211 return 0;
7212 }
7213
7214 /// Return the index of the index in the transition.
7215 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
7216 /// is at index 1.
7217 unsigned getTransitionIdx() const {
7218 assert(isa<ExtractElementInst>(Transition) &&(static_cast <bool> (isa<ExtractElementInst>(Transition
) && "Other kind of transitions are not supported yet"
) ? void (0) : __assert_fail ("isa<ExtractElementInst>(Transition) && \"Other kind of transitions are not supported yet\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 7219, __extension__ __PRETTY_FUNCTION__
))
7219 "Other kind of transitions are not supported yet")(static_cast <bool> (isa<ExtractElementInst>(Transition
) && "Other kind of transitions are not supported yet"
) ? void (0) : __assert_fail ("isa<ExtractElementInst>(Transition) && \"Other kind of transitions are not supported yet\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 7219, __extension__ __PRETTY_FUNCTION__
))
;
7220 return 1;
7221 }
7222
7223 /// Get the type of the transition.
7224 /// This is the type of the original value.
7225 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
7226 /// transition is <2 x i32>.
7227 Type *getTransitionType() const {
7228 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
7229 }
7230
7231 /// Promote \p ToBePromoted by moving \p Def downward through.
7232 /// I.e., we have the following sequence:
7233 /// Def = Transition <ty1> a to <ty2>
7234 /// b = ToBePromoted <ty2> Def, ...
7235 /// =>
7236 /// b = ToBePromoted <ty1> a, ...
7237 /// Def = Transition <ty1> ToBePromoted to <ty2>
7238 void promoteImpl(Instruction *ToBePromoted);
7239
7240 /// Check whether or not it is profitable to promote all the
7241 /// instructions enqueued to be promoted.
7242 bool isProfitableToPromote() {
7243 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
7244 unsigned Index = isa<ConstantInt>(ValIdx)
7245 ? cast<ConstantInt>(ValIdx)->getZExtValue()
7246 : -1;
7247 Type *PromotedType = getTransitionType();
7248
7249 StoreInst *ST = cast<StoreInst>(CombineInst);
7250 unsigned AS = ST->getPointerAddressSpace();
7251 // Check if this store is supported.
7252 if (!TLI.allowsMisalignedMemoryAccesses(
7253 TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
7254 ST->getAlign())) {
7255 // If this is not supported, there is no way we can combine
7256 // the extract with the store.
7257 return false;
7258 }
7259
7260 // The scalar chain of computation has to pay for the transition
7261 // scalar to vector.
7262 // The vector chain has to account for the combining cost.
7263 InstructionCost ScalarCost =
7264 TTI.getVectorInstrCost(*Transition, PromotedType, Index);
7265 InstructionCost VectorCost = StoreExtractCombineCost;
7266 enum TargetTransformInfo::TargetCostKind CostKind =
7267 TargetTransformInfo::TCK_RecipThroughput;
7268 for (const auto &Inst : InstsToBePromoted) {
7269 // Compute the cost.
7270 // By construction, all instructions being promoted are arithmetic ones.
7271 // Moreover, one argument is a constant that can be viewed as a splat
7272 // constant.
7273 Value *Arg0 = Inst->getOperand(0);
7274 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
7275 isa<ConstantFP>(Arg0);
7276 TargetTransformInfo::OperandValueInfo Arg0Info, Arg1Info;
7277 if (IsArg0Constant)
7278 Arg0Info.Kind = TargetTransformInfo::OK_UniformConstantValue;
7279 else
7280 Arg1Info.Kind = TargetTransformInfo::OK_UniformConstantValue;
7281
7282 ScalarCost += TTI.getArithmeticInstrCost(
7283 Inst->getOpcode(), Inst->getType(), CostKind, Arg0Info, Arg1Info);
7284 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
7285 CostKind, Arg0Info, Arg1Info);
7286 }
7287 LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
<< ScalarCost << "\nVector: " << VectorCost
<< '\n'; } } while (false)
7288 dbgs() << "Estimated cost of computation to be promoted:\nScalar: "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
<< ScalarCost << "\nVector: " << VectorCost
<< '\n'; } } while (false)
7289 << ScalarCost << "\nVector: " << VectorCost << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
<< ScalarCost << "\nVector: " << VectorCost
<< '\n'; } } while (false)
;
7290 return ScalarCost > VectorCost;
7291 }
7292
7293 /// Generate a constant vector with \p Val with the same
7294 /// number of elements as the transition.
7295 /// \p UseSplat defines whether or not \p Val should be replicated
7296 /// across the whole vector.
7297 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
7298 /// otherwise we generate a vector with as many undef as possible:
7299 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
7300 /// used at the index of the extract.
7301 Value *getConstantVector(Constant *Val, bool UseSplat) const {
7302 unsigned ExtractIdx = std::numeric_limits<unsigned>::max();
7303 if (!UseSplat) {
7304 // If we cannot determine where the constant must be, we have to
7305 // use a splat constant.
7306 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
7307 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
7308 ExtractIdx = CstVal->getSExtValue();
7309 else
7310 UseSplat = true;
7311 }
7312
7313 ElementCount EC = cast<VectorType>(getTransitionType())->getElementCount();
7314 if (UseSplat)
7315 return ConstantVector::getSplat(EC, Val);
7316
7317 if (!EC.isScalable()) {
7318 SmallVector<Constant *, 4> ConstVec;
7319 UndefValue *UndefVal = UndefValue::get(Val->getType());
7320 for (unsigned Idx = 0; Idx != EC.getKnownMinValue(); ++Idx) {
7321 if (Idx == ExtractIdx)
7322 ConstVec.push_back(Val);
7323 else
7324 ConstVec.push_back(UndefVal);
7325 }
7326 return ConstantVector::get(ConstVec);
7327 } else
7328 llvm_unreachable(::llvm::llvm_unreachable_internal("Generate scalable vector for non-splat is unimplemented"
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 7329)
7329 "Generate scalable vector for non-splat is unimplemented")::llvm::llvm_unreachable_internal("Generate scalable vector for non-splat is unimplemented"
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 7329)
;
7330 }
7331
7332 /// Check if promoting to a vector type an operand at \p OperandIdx
7333 /// in \p Use can trigger undefined behavior.
7334 static bool canCauseUndefinedBehavior(const Instruction *Use,
7335 unsigned OperandIdx) {
7336 // This is not safe to introduce undef when the operand is on
7337 // the right hand side of a division-like instruction.
7338 if (OperandIdx != 1)
7339 return false;
7340 switch (Use->getOpcode()) {
7341 default:
7342 return false;
7343 case Instruction::SDiv:
7344 case Instruction::UDiv:
7345 case Instruction::SRem:
7346 case Instruction::URem:
7347 return true;
7348 case Instruction::FDiv:
7349 case Instruction::FRem:
7350 return !Use->hasNoNaNs();
7351 }
7352 llvm_unreachable(nullptr)::llvm::llvm_unreachable_internal(nullptr, "llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 7352)
;
7353 }
7354
7355public:
7356 VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
7357 const TargetTransformInfo &TTI, Instruction *Transition,
7358 unsigned CombineCost)
7359 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
7360 StoreExtractCombineCost(CombineCost) {
7361 assert(Transition && "Do not know how to promote null")(static_cast <bool> (Transition && "Do not know how to promote null"
) ? void (0) : __assert_fail ("Transition && \"Do not know how to promote null\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 7361, __extension__ __PRETTY_FUNCTION__
))
;
7362 }
7363
7364 /// Check if we can promote \p ToBePromoted to \p Type.
7365 bool canPromote(const Instruction *ToBePromoted) const {
7366 // We could support CastInst too.
7367 return isa<BinaryOperator>(ToBePromoted);
7368 }
7369
7370 /// Check if it is profitable to promote \p ToBePromoted
7371 /// by moving downward the transition through.
7372 bool shouldPromote(const Instruction *ToBePromoted) const {
7373 // Promote only if all the operands can be statically expanded.
7374 // Indeed, we do not want to introduce any new kind of transitions.
7375 for (const Use &U : ToBePromoted->operands()) {
7376 const Value *Val = U.get();
7377 if (Val == getEndOfTransition()) {
7378 // If the use is a division and the transition is on the rhs,
7379 // we cannot promote the operation, otherwise we may create a
7380 // division by zero.
7381 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
7382 return false;
7383 continue;
7384 }
7385 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
7386 !isa<ConstantFP>(Val))
7387 return false;
7388 }
7389 // Check that the resulting operation is legal.
7390 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
7391 if (!ISDOpcode)
7392 return false;
7393 return StressStoreExtract ||
7394 TLI.isOperationLegalOrCustom(
7395 ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
7396 }
7397
7398 /// Check whether or not \p Use can be combined
7399 /// with the transition.
7400 /// I.e., is it possible to do Use(Transition) => AnotherUse?
7401 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
7402
7403 /// Record \p ToBePromoted as part of the chain to be promoted.
7404 void enqueueForPromotion(Instruction *ToBePromoted) {
7405 InstsToBePromoted.push_back(ToBePromoted);
7406 }
7407
7408 /// Set the instruction that will be combined with the transition.
7409 void recordCombineInstruction(Instruction *ToBeCombined) {
7410 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine")(static_cast <bool> (canCombine(ToBeCombined) &&
"Unsupported instruction to combine") ? void (0) : __assert_fail
("canCombine(ToBeCombined) && \"Unsupported instruction to combine\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 7410, __extension__ __PRETTY_FUNCTION__
))
;
7411 CombineInst = ToBeCombined;
7412 }
7413
7414 /// Promote all the instructions enqueued for promotion if it is
7415 /// is profitable.
7416 /// \return True if the promotion happened, false otherwise.
7417 bool promote() {
7418 // Check if there is something to promote.
7419 // Right now, if we do not have anything to combine with,
7420 // we assume the promotion is not profitable.
7421 if (InstsToBePromoted.empty() || !CombineInst)
7422 return false;
7423
7424 // Check cost.
7425 if (!StressStoreExtract && !isProfitableToPromote())
7426 return false;
7427
7428 // Promote.
7429 for (auto &ToBePromoted : InstsToBePromoted)
7430 promoteImpl(ToBePromoted);
7431 InstsToBePromoted.clear();
7432 return true;
7433 }
7434};
7435
7436} // end anonymous namespace
7437
7438void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
7439 // At this point, we know that all the operands of ToBePromoted but Def
7440 // can be statically promoted.
7441 // For Def, we need to use its parameter in ToBePromoted:
7442 // b = ToBePromoted ty1 a
7443 // Def = Transition ty1 b to ty2
7444 // Move the transition down.
7445 // 1. Replace all uses of the promoted operation by the transition.
7446 // = ... b => = ... Def.
7447 assert(ToBePromoted->getType() == Transition->getType() &&(static_cast <bool> (ToBePromoted->getType() == Transition
->getType() && "The type of the result of the transition does not match "
"the final type") ? void (0) : __assert_fail ("ToBePromoted->getType() == Transition->getType() && \"The type of the result of the transition does not match \" \"the final type\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 7449, __extension__ __PRETTY_FUNCTION__
))
7448 "The type of the result of the transition does not match "(static_cast <bool> (ToBePromoted->getType() == Transition
->getType() && "The type of the result of the transition does not match "
"the final type") ? void (0) : __assert_fail ("ToBePromoted->getType() == Transition->getType() && \"The type of the result of the transition does not match \" \"the final type\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 7449, __extension__ __PRETTY_FUNCTION__
))
7449 "the final type")(static_cast <bool> (ToBePromoted->getType() == Transition
->getType() && "The type of the result of the transition does not match "
"the final type") ? void (0) : __assert_fail ("ToBePromoted->getType() == Transition->getType() && \"The type of the result of the transition does not match \" \"the final type\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 7449, __extension__ __PRETTY_FUNCTION__
))
;
7450 ToBePromoted->replaceAllUsesWith(Transition);
7451 // 2. Update the type of the uses.
7452 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
7453 Type *TransitionTy = getTransitionType();
7454 ToBePromoted->mutateType(TransitionTy);
7455 // 3. Update all the operands of the promoted operation with promoted
7456 // operands.
7457 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
7458 for (Use &U : ToBePromoted->operands()) {
7459 Value *Val = U.get();
7460 Value *NewVal = nullptr;
7461 if (Val == Transition)
7462 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
7463 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
7464 isa<ConstantFP>(Val)) {
7465 // Use a splat constant if it is not safe to use undef.
7466 NewVal = getConstantVector(
7467 cast<Constant>(Val),
7468 isa<UndefValue>(Val) ||
7469 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
7470 } else
7471 llvm_unreachable("Did you modified shouldPromote and forgot to update "::llvm::llvm_unreachable_internal("Did you modified shouldPromote and forgot to update "
"this?", "llvm/lib/CodeGen/CodeGenPrepare.cpp", 7472)
7472 "this?")::llvm::llvm_unreachable_internal("Did you modified shouldPromote and forgot to update "
"this?", "llvm/lib/CodeGen/CodeGenPrepare.cpp", 7472)
;
7473 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
7474 }
7475 Transition->moveAfter(ToBePromoted);
7476 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
7477}
7478
7479/// Some targets can do store(extractelement) with one instruction.
7480/// Try to push the extractelement towards the stores when the target
7481/// has this feature and this is profitable.
7482bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
7483 unsigned CombineCost = std::numeric_limits<unsigned>::max();
7484 if (DisableStoreExtract ||
7485 (!StressStoreExtract &&
7486 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
7487 Inst->getOperand(1), CombineCost)))
7488 return false;
7489
7490 // At this point we know that Inst is a vector to scalar transition.
7491 // Try to move it down the def-use chain, until:
7492 // - We can combine the transition with its single use
7493 // => we got rid of the transition.
7494 // - We escape the current basic block
7495 // => we would need to check that we are moving it at a cheaper place and
7496 // we do not do that for now.
7497 BasicBlock *Parent = Inst->getParent();
7498 LLVM_DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Found an interesting transition: "
<< *Inst << '\n'; } } while (false)
;
7499 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
7500 // If the transition has more than one use, assume this is not going to be
7501 // beneficial.
7502 while (Inst->hasOneUse()) {
7503 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
7504 LLVM_DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Use: " << *ToBePromoted
<< '\n'; } } while (false)
;
7505
7506 if (ToBePromoted->getParent() != Parent) {
7507 LLVM_DEBUG(dbgs() << "Instruction to promote is in a different block ("do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Instruction to promote is in a different block ("
<< ToBePromoted->getParent()->getName() <<
") than the transition (" << Parent->getName() <<
").\n"; } } while (false)
7508 << ToBePromoted->getParent()->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Instruction to promote is in a different block ("
<< ToBePromoted->getParent()->getName() <<
") than the transition (" << Parent->getName() <<
").\n"; } } while (false)
7509 << ") than the transition (" << Parent->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Instruction to promote is in a different block ("
<< ToBePromoted->getParent()->getName() <<
") than the transition (" << Parent->getName() <<
").\n"; } } while (false)
7510 << ").\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Instruction to promote is in a different block ("
<< ToBePromoted->getParent()->getName() <<
") than the transition (" << Parent->getName() <<
").\n"; } } while (false)
;
7511 return false;
7512 }
7513
7514 if (VPH.canCombine(ToBePromoted)) {
7515 LLVM_DEBUG(dbgs() << "Assume " << *Inst << '\n'do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Assume " << *Inst
<< '\n' << "will be combined with: " << *ToBePromoted
<< '\n'; } } while (false)
7516 << "will be combined with: " << *ToBePromoted << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Assume " << *Inst
<< '\n' << "will be combined with: " << *ToBePromoted
<< '\n'; } } while (false)
;
7517 VPH.recordCombineInstruction(ToBePromoted);
7518 bool Changed = VPH.promote();
7519 NumStoreExtractExposed += Changed;
7520 return Changed;
7521 }
7522
7523 LLVM_DEBUG(dbgs() << "Try promoting.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Try promoting.\n"; } }
while (false)
;
7524 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
7525 return false;
7526
7527 LLVM_DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Promoting is possible... Enqueue for promotion!\n"
; } } while (false)
;
7528
7529 VPH.enqueueForPromotion(ToBePromoted);
7530 Inst = ToBePromoted;
7531 }
7532 return false;
7533}
7534
7535/// For the instruction sequence of store below, F and I values
7536/// are bundled together as an i64 value before being stored into memory.
7537/// Sometimes it is more efficient to generate separate stores for F and I,
7538/// which can remove the bitwise instructions or sink them to colder places.
7539///
7540/// (store (or (zext (bitcast F to i32) to i64),
7541/// (shl (zext I to i64), 32)), addr) -->
7542/// (store F, addr) and (store I, addr+4)
7543///
7544/// Similarly, splitting for other merged store can also be beneficial, like:
7545/// For pair of {i32, i32}, i64 store --> two i32 stores.
7546/// For pair of {i32, i16}, i64 store --> two i32 stores.
7547/// For pair of {i16, i16}, i32 store --> two i16 stores.
7548/// For pair of {i16, i8}, i32 store --> two i16 stores.
7549/// For pair of {i8, i8}, i16 store --> two i8 stores.
7550///
7551/// We allow each target to determine specifically which kind of splitting is
7552/// supported.
7553///
7554/// The store patterns are commonly seen from the simple code snippet below
7555/// if only std::make_pair(...) is sroa transformed before inlined into hoo.
7556/// void goo(const std::pair<int, float> &);
7557/// hoo() {
7558/// ...
7559/// goo(std::make_pair(tmp, ftmp));
7560/// ...
7561/// }
7562///
7563/// Although we already have similar splitting in DAG Combine, we duplicate
7564/// it in CodeGenPrepare to catch the case in which pattern is across
7565/// multiple BBs. The logic in DAG Combine is kept to catch case generated
7566/// during code expansion.
7567static bool splitMergedValStore(StoreInst &SI, const DataLayout &DL,
7568 const TargetLowering &TLI) {
7569 // Handle simple but common cases only.
7570 Type *StoreType = SI.getValueOperand()->getType();
7571
7572 // The code below assumes shifting a value by <number of bits>,
7573 // whereas scalable vectors would have to be shifted by
7574 // <2log(vscale) + number of bits> in order to store the
7575 // low/high parts. Bailing out for now.
7576 if (isa<ScalableVectorType>(StoreType))
7577 return false;
7578
7579 if (!DL.typeSizeEqualsStoreSize(StoreType) ||
7580 DL.getTypeSizeInBits(StoreType) == 0)
7581 return false;
7582
7583 unsigned HalfValBitSize = DL.getTypeSizeInBits(StoreType) / 2;
7584 Type *SplitStoreType = Type::getIntNTy(SI.getContext(), HalfValBitSize);
7585 if (!DL.typeSizeEqualsStoreSize(SplitStoreType))
7586 return false;
7587
7588 // Don't split the store if it is volatile.
7589 if (SI.isVolatile())
7590 return false;
7591
7592 // Match the following patterns:
7593 // (store (or (zext LValue to i64),
7594 // (shl (zext HValue to i64), 32)), HalfValBitSize)
7595 // or
7596 // (store (or (shl (zext HValue to i64), 32)), HalfValBitSize)
7597 // (zext LValue to i64),
7598 // Expect both operands of OR and the first operand of SHL have only
7599 // one use.
7600 Value *LValue, *HValue;
7601 if (!match(SI.getValueOperand(),
7602 m_c_Or(m_OneUse(m_ZExt(m_Value(LValue))),
7603 m_OneUse(m_Shl(m_OneUse(m_ZExt(m_Value(HValue))),
7604 m_SpecificInt(HalfValBitSize))))))
7605 return false;
7606
7607 // Check LValue and HValue are int with size less or equal than 32.
7608 if (!LValue->getType()->isIntegerTy() ||
7609 DL.getTypeSizeInBits(LValue->getType()) > HalfValBitSize ||
7610 !HValue->getType()->isIntegerTy() ||
7611 DL.getTypeSizeInBits(HValue->getType()) > HalfValBitSize)
7612 return false;
7613
7614 // If LValue/HValue is a bitcast instruction, use the EVT before bitcast
7615 // as the input of target query.
7616 auto *LBC = dyn_cast<BitCastInst>(LValue);
7617 auto *HBC = dyn_cast<BitCastInst>(HValue);
7618 EVT LowTy = LBC ? EVT::getEVT(LBC->getOperand(0)->getType())
7619 : EVT::getEVT(LValue->getType());
7620 EVT HighTy = HBC ? EVT::getEVT(HBC->getOperand(0)->getType())
7621 : EVT::getEVT(HValue->getType());
7622 if (!ForceSplitStore && !TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
7623 return false;
7624
7625 // Start to split store.
7626 IRBuilder<> Builder(SI.getContext());
7627 Builder.SetInsertPoint(&SI);
7628
7629 // If LValue/HValue is a bitcast in another BB, create a new one in current
7630 // BB so it may be merged with the splitted stores by dag combiner.
7631 if (LBC && LBC->getParent() != SI.getParent())
7632 LValue = Builder.CreateBitCast(LBC->getOperand(0), LBC->getType());
7633 if (HBC && HBC->getParent() != SI.getParent())
7634 HValue = Builder.CreateBitCast(HBC->getOperand(0), HBC->getType());
7635
7636 bool IsLE = SI.getModule()->getDataLayout().isLittleEndian();
7637 auto CreateSplitStore = [&](Value *V, bool Upper) {
7638 V = Builder.CreateZExtOrBitCast(V, SplitStoreType);
7639 Value *Addr = Builder.CreateBitCast(
7640 SI.getOperand(1),
7641 SplitStoreType->getPointerTo(SI.getPointerAddressSpace()));
7642 Align Alignment = SI.getAlign();
7643 const bool IsOffsetStore = (IsLE && Upper) || (!IsLE && !Upper);
7644 if (IsOffsetStore) {
7645 Addr = Builder.CreateGEP(
7646 SplitStoreType, Addr,
7647 ConstantInt::get(Type::getInt32Ty(SI.getContext()), 1));
7648
7649 // When splitting the store in half, naturally one half will retain the
7650 // alignment of the original wider store, regardless of whether it was
7651 // over-aligned or not, while the other will require adjustment.
7652 Alignment = commonAlignment(Alignment, HalfValBitSize / 8);
7653 }
7654 Builder.CreateAlignedStore(V, Addr, Alignment);
7655 };
7656
7657 CreateSplitStore(LValue, false);
7658 CreateSplitStore(HValue, true);
7659
7660 // Delete the old store.
7661 SI.eraseFromParent();
7662 return true;
7663}
7664
7665// Return true if the GEP has two operands, the first operand is of a sequential
7666// type, and the second operand is a constant.
7667static bool GEPSequentialConstIndexed(GetElementPtrInst *GEP) {
7668 gep_type_iterator I = gep_type_begin(*GEP);
7669 return GEP->getNumOperands() == 2 &&
7670 I.isSequential() &&
7671 isa<ConstantInt>(GEP->getOperand(1));
7672}
7673
7674// Try unmerging GEPs to reduce liveness interference (register pressure) across
7675// IndirectBr edges. Since IndirectBr edges tend to touch on many blocks,
7676// reducing liveness interference across those edges benefits global register
7677// allocation. Currently handles only certain cases.
7678//
7679// For example, unmerge %GEPI and %UGEPI as below.
7680//
7681// ---------- BEFORE ----------
7682// SrcBlock:
7683// ...
7684// %GEPIOp = ...
7685// ...
7686// %GEPI = gep %GEPIOp, Idx
7687// ...
7688// indirectbr ... [ label %DstB0, label %DstB1, ... label %DstBi ... ]
7689// (* %GEPI is alive on the indirectbr edges due to other uses ahead)
7690// (* %GEPIOp is alive on the indirectbr edges only because of it's used by
7691// %UGEPI)
7692//
7693// DstB0: ... (there may be a gep similar to %UGEPI to be unmerged)
7694// DstB1: ... (there may be a gep similar to %UGEPI to be unmerged)
7695// ...
7696//
7697// DstBi:
7698// ...
7699// %UGEPI = gep %GEPIOp, UIdx
7700// ...
7701// ---------------------------
7702//
7703// ---------- AFTER ----------
7704// SrcBlock:
7705// ... (same as above)
7706// (* %GEPI is still alive on the indirectbr edges)
7707// (* %GEPIOp is no longer alive on the indirectbr edges as a result of the
7708// unmerging)
7709// ...
7710//
7711// DstBi:
7712// ...
7713// %UGEPI = gep %GEPI, (UIdx-Idx)
7714// ...
7715// ---------------------------
7716//
7717// The register pressure on the IndirectBr edges is reduced because %GEPIOp is
7718// no longer alive on them.
7719//
7720// We try to unmerge GEPs here in CodGenPrepare, as opposed to limiting merging
7721// of GEPs in the first place in InstCombiner::visitGetElementPtrInst() so as
7722// not to disable further simplications and optimizations as a result of GEP
7723// merging.
7724//
7725// Note this unmerging may increase the length of the data flow critical path
7726// (the path from %GEPIOp to %UGEPI would go through %GEPI), which is a tradeoff
7727// between the register pressure and the length of data-flow critical
7728// path. Restricting this to the uncommon IndirectBr case would minimize the
7729// impact of potentially longer critical path, if any, and the impact on compile
7730// time.
7731static bool tryUnmergingGEPsAcrossIndirectBr(GetElementPtrInst *GEPI,
7732 const TargetTransformInfo *TTI) {
7733 BasicBlock *SrcBlock = GEPI->getParent();
7734 // Check that SrcBlock ends with an IndirectBr. If not, give up. The common
7735 // (non-IndirectBr) cases exit early here.
7736 if (!isa<IndirectBrInst>(SrcBlock->getTerminator()))
7737 return false;
7738 // Check that GEPI is a simple gep with a single constant index.
7739 if (!GEPSequentialConstIndexed(GEPI))
7740 return false;
7741 ConstantInt *GEPIIdx = cast<ConstantInt>(GEPI->getOperand(1));
7742 // Check that GEPI is a cheap one.
7743 if (TTI->getIntImmCost(GEPIIdx->getValue(), GEPIIdx->getType(),
7744 TargetTransformInfo::TCK_SizeAndLatency)
7745 > TargetTransformInfo::TCC_Basic)
7746 return false;
7747 Value *GEPIOp = GEPI->getOperand(0);
7748 // Check that GEPIOp is an instruction that's also defined in SrcBlock.
7749 if (!isa<Instruction>(GEPIOp))
7750 return false;
7751 auto *GEPIOpI = cast<Instruction>(GEPIOp);
7752 if (GEPIOpI->getParent() != SrcBlock)
7753 return false;
7754 // Check that GEP is used outside the block, meaning it's alive on the
7755 // IndirectBr edge(s).
7756 if (llvm::none_of(GEPI->users(), [&](User *Usr) {
7757 if (auto *I = dyn_cast<Instruction>(Usr)) {
7758 if (I->getParent() != SrcBlock) {
7759 return true;
7760 }
7761 }
7762 return false;
7763 }))
7764 return false;
7765 // The second elements of the GEP chains to be unmerged.
7766 std::vector<GetElementPtrInst *> UGEPIs;
7767 // Check each user of GEPIOp to check if unmerging would make GEPIOp not alive
7768 // on IndirectBr edges.
7769 for (User *Usr : GEPIOp->users()) {
7770 if (Usr == GEPI) continue;
7771 // Check if Usr is an Instruction. If not, give up.
7772 if (!isa<Instruction>(Usr))
7773 return false;
7774 auto *UI = cast<Instruction>(Usr);
7775 // Check if Usr in the same block as GEPIOp, which is fine, skip.
7776 if (UI->getParent() == SrcBlock)
7777 continue;
7778 // Check if Usr is a GEP. If not, give up.
7779 if (!isa<GetElementPtrInst>(Usr))
7780 return false;
7781 auto *UGEPI = cast<GetElementPtrInst>(Usr);
7782 // Check if UGEPI is a simple gep with a single constant index and GEPIOp is
7783 // the pointer operand to it. If so, record it in the vector. If not, give
7784 // up.
7785 if (!GEPSequentialConstIndexed(UGEPI))
7786 return false;
7787 if (UGEPI->getOperand(0) != GEPIOp)
7788 return false;
7789 if (GEPIIdx->getType() !=
7790 cast<ConstantInt>(UGEPI->getOperand(1))->getType())
7791 return false;
7792 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
7793 if (TTI->getIntImmCost(UGEPIIdx->getValue(), UGEPIIdx->getType(),
7794 TargetTransformInfo::TCK_SizeAndLatency)
7795 > TargetTransformInfo::TCC_Basic)
7796 return false;
7797 UGEPIs.push_back(UGEPI);
7798 }
7799 if (UGEPIs.size() == 0)
7800 return false;
7801 // Check the materializing cost of (Uidx-Idx).
7802 for (GetElementPtrInst *UGEPI : UGEPIs) {
7803 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
7804 APInt NewIdx = UGEPIIdx->getValue() - GEPIIdx->getValue();
7805 InstructionCost ImmCost = TTI->getIntImmCost(
7806 NewIdx, GEPIIdx->getType(), TargetTransformInfo::TCK_SizeAndLatency);
7807 if (ImmCost > TargetTransformInfo::TCC_Basic)
7808 return false;
7809 }
7810 // Now unmerge between GEPI and UGEPIs.
7811 for (GetElementPtrInst *UGEPI : UGEPIs) {
7812 UGEPI->setOperand(0, GEPI);
7813 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
7814 Constant *NewUGEPIIdx =
7815 ConstantInt::get(GEPIIdx->getType(),
7816 UGEPIIdx->getValue() - GEPIIdx->getValue());
7817 UGEPI->setOperand(1, NewUGEPIIdx);
7818 // If GEPI is not inbounds but UGEPI is inbounds, change UGEPI to not
7819 // inbounds to avoid UB.
7820 if (!GEPI->isInBounds()) {
7821 UGEPI->setIsInBounds(false);
7822 }
7823 }
7824 // After unmerging, verify that GEPIOp is actually only used in SrcBlock (not
7825 // alive on IndirectBr edges).
7826 assert(llvm::none_of(GEPIOp->users(),(static_cast <bool> (llvm::none_of(GEPIOp->users(), [
&](User *Usr) { return cast<Instruction>(Usr)->getParent
() != SrcBlock; }) && "GEPIOp is used outside SrcBlock"
) ? void (0) : __assert_fail ("llvm::none_of(GEPIOp->users(), [&](User *Usr) { return cast<Instruction>(Usr)->getParent() != SrcBlock; }) && \"GEPIOp is used outside SrcBlock\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 7830, __extension__ __PRETTY_FUNCTION__
))
7827 [&](User *Usr) {(static_cast <bool> (llvm::none_of(GEPIOp->users(), [
&](User *Usr) { return cast<Instruction>(Usr)->getParent
() != SrcBlock; }) && "GEPIOp is used outside SrcBlock"
) ? void (0) : __assert_fail ("llvm::none_of(GEPIOp->users(), [&](User *Usr) { return cast<Instruction>(Usr)->getParent() != SrcBlock; }) && \"GEPIOp is used outside SrcBlock\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 7830, __extension__ __PRETTY_FUNCTION__
))
7828 return cast<Instruction>(Usr)->getParent() != SrcBlock;(static_cast <bool> (llvm::none_of(GEPIOp->users(), [
&](User *Usr) { return cast<Instruction>(Usr)->getParent
() != SrcBlock; }) && "GEPIOp is used outside SrcBlock"
) ? void (0) : __assert_fail ("llvm::none_of(GEPIOp->users(), [&](User *Usr) { return cast<Instruction>(Usr)->getParent() != SrcBlock; }) && \"GEPIOp is used outside SrcBlock\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 7830, __extension__ __PRETTY_FUNCTION__
))
7829 }) &&(static_cast <bool> (llvm::none_of(GEPIOp->users(), [
&](User *Usr) { return cast<Instruction>(Usr)->getParent
() != SrcBlock; }) && "GEPIOp is used outside SrcBlock"
) ? void (0) : __assert_fail ("llvm::none_of(GEPIOp->users(), [&](User *Usr) { return cast<Instruction>(Usr)->getParent() != SrcBlock; }) && \"GEPIOp is used outside SrcBlock\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 7830, __extension__ __PRETTY_FUNCTION__
))
7830 "GEPIOp is used outside SrcBlock")(static_cast <bool> (llvm::none_of(GEPIOp->users(), [
&](User *Usr) { return cast<Instruction>(Usr)->getParent
() != SrcBlock; }) && "GEPIOp is used outside SrcBlock"
) ? void (0) : __assert_fail ("llvm::none_of(GEPIOp->users(), [&](User *Usr) { return cast<Instruction>(Usr)->getParent() != SrcBlock; }) && \"GEPIOp is used outside SrcBlock\""
, "llvm/lib/CodeGen/CodeGenPrepare.cpp", 7830, __extension__ __PRETTY_FUNCTION__
))
;
7831 return true;
7832}
7833
7834static bool optimizeBranch(BranchInst *Branch, const TargetLowering &TLI) {
7835 // Try and convert
7836 // %c = icmp ult %x, 8
7837 // br %c, bla, blb
7838 // %tc = lshr %x, 3
7839 // to
7840 // %tc = lshr %x, 3
7841 // %c = icmp eq %tc, 0
7842 // br %c, bla, blb
7843 // Creating the cmp to zero can be better for the backend, especially if the
7844 // lshr produces flags that can be used automatically.
7845 if (!TLI.preferZeroCompareBranch() || !Branch->isConditional())
7846 return false;
7847
7848 ICmpInst *Cmp = dyn_cast<ICmpInst>(Branch->getCondition());
7849 if (!Cmp || !isa<ConstantInt>(Cmp->getOperand(1)) || !Cmp->hasOneUse())
7850 return false;
7851
7852 Value *X = Cmp->getOperand(0);
7853 APInt CmpC = cast<ConstantInt>(Cmp->getOperand(1))->getValue();
7854
7855 for (auto *U : X->users()) {
7856 Instruction *UI = dyn_cast<Instruction>(U);
7857 // A quick dominance check
7858 if (!UI ||
7859 (UI->getParent() != Branch->getParent() &&
7860 UI->getParent() != Branch->getSuccessor(0) &&
7861 UI->getParent() != Branch->getSuccessor(1)) ||
7862 (UI->getParent() != Branch->getParent() &&
7863 !UI->getParent()->getSinglePredecessor()))
7864 continue;
7865
7866 if (CmpC.isPowerOf2() && Cmp->getPredicate() == ICmpInst::ICMP_ULT &&
7867 match(UI, m_Shr(m_Specific(X), m_SpecificInt(CmpC.logBase2())))) {
7868 IRBuilder<> Builder(Branch);
7869 if (UI->getParent() != Branch->getParent())
7870 UI->moveBefore(Branch);
7871 Value *NewCmp = Builder.CreateCmp(ICmpInst::ICMP_EQ, UI,
7872 ConstantInt::get(UI->getType(), 0));
7873 LLVM_DEBUG(dbgs() << "Converting " << *Cmp << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Converting " << *
Cmp << "\n"; } } while (false)
;
7874 LLVM_DEBUG(dbgs() << " to compare on zero: " << *NewCmp << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << " to compare on zero: "
<< *NewCmp << "\n"; } } while (false)
;
7875 Cmp->replaceAllUsesWith(NewCmp);
7876 return true;
7877 }
7878 if (Cmp->isEquality() &&
7879 (match(UI, m_Add(m_Specific(X), m_SpecificInt(-CmpC))) ||
7880 match(UI, m_Sub(m_Specific(X), m_SpecificInt(CmpC))))) {
7881 IRBuilder<> Builder(Branch);
7882 if (UI->getParent() != Branch->getParent())
7883 UI->moveBefore(Branch);
7884 Value *NewCmp = Builder.CreateCmp(Cmp->getPredicate(), UI,
7885 ConstantInt::get(UI->getType(), 0));
7886 LLVM_DEBUG(dbgs() << "Converting " << *Cmp << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Converting " << *
Cmp << "\n"; } } while (false)
;
7887 LLVM_DEBUG(dbgs() << " to compare on zero: " << *NewCmp << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << " to compare on zero: "
<< *NewCmp << "\n"; } } while (false)
;
7888 Cmp->replaceAllUsesWith(NewCmp);
7889 return true;
7890 }
7891 }
7892 return false;
7893}
7894
7895bool CodeGenPrepare::optimizeInst(Instruction *I, bool &ModifiedDT) {
7896 // Bail out if we inserted the instruction to prevent optimizations from
7897 // stepping on each other's toes.
7898 if (InsertedInsts.count(I))
7899 return false;
7900
7901 // TODO: Move into the switch on opcode below here.
7902 if (PHINode *P = dyn_cast<PHINode>(I)) {
7903 // It is possible for very late stage optimizations (such as SimplifyCFG)
7904 // to introduce PHI nodes too late to be cleaned up. If we detect such a
7905 // trivial PHI, go ahead and zap it here.
7906 if (Value *V = simplifyInstruction(P, {*DL, TLInfo})) {
7907 LargeOffsetGEPMap.erase(P);
7908 P->replaceAllUsesWith(V);
7909 P->eraseFromParent();
7910 ++NumPHIsElim;
7911 return true;
7912 }
7913 return false;
7914 }
7915
7916 if (CastInst *CI = dyn_cast<CastInst>(I)) {
7917 // If the source of the cast is a constant, then this should have
7918 // already been constant folded. The only reason NOT to constant fold
7919 // it is if something (e.g. LSR) was careful to place the constant
7920 // evaluation in a block other than then one that uses it (e.g. to hoist
7921 // the address of globals out of a loop). If this is the case, we don't
7922 // want to forward-subst the cast.
7923 if (isa<Constant>(CI->getOperand(0)))
7924 return false;
7925
7926 if (OptimizeNoopCopyExpression(CI, *TLI, *DL))
7927 return true;
7928
7929 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7930 /// Sink a zext or sext into its user blocks if the target type doesn't
7931 /// fit in one register
7932 if (TLI->getTypeAction(CI->getContext(),
7933 TLI->getValueType(*DL, CI->getType())) ==
7934 TargetLowering::TypeExpandInteger) {
7935 return SinkCast(CI);
7936 } else {
7937 bool MadeChange = optimizeExt(I);
7938 return MadeChange | optimizeExtUses(I);
7939 }
7940 }
7941 return false;
7942 }
7943
7944 if (auto *Cmp = dyn_cast<CmpInst>(I))
7945 if (optimizeCmp(Cmp, ModifiedDT))
7946 return true;
7947
7948 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7949 LI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
7950 bool Modified = optimizeLoadExt(LI);
7951 unsigned AS = LI->getPointerAddressSpace();
7952 Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
7953 return Modified;
7954 }
7955
7956 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
7957 if (splitMergedValStore(*SI, *DL, *TLI))
7958 return true;
7959 SI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
7960 unsigned AS = SI->getPointerAddressSpace();
7961 return optimizeMemoryInst(I, SI->getOperand(1),
7962 SI->getOperand(0)->getType(), AS);
7963 }
7964
7965 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
7966 unsigned AS = RMW->getPointerAddressSpace();
7967 return optimizeMemoryInst(I, RMW->getPointerOperand(),
7968 RMW->getType(), AS);
7969 }
7970
7971 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(I)) {
7972 unsigned AS = CmpX->getPointerAddressSpace();
7973 return optimizeMemoryInst(I, CmpX->getPointerOperand(),
7974 CmpX->getCompareOperand()->getType(), AS);
7975 }
7976
7977 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
7978
7979 if (BinOp && BinOp->getOpcode() == Instruction::And && EnableAndCmpSinking &&
7980 sinkAndCmp0Expression(BinOp, *TLI, InsertedInsts))
7981 return true;
7982
7983 // TODO: Move this into the switch on opcode - it handles shifts already.
7984 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
7985 BinOp->getOpcode() == Instruction::LShr)) {
7986 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
7987 if (CI && TLI->hasExtractBitsInsn())
7988 if (OptimizeExtractBits(BinOp, CI, *TLI, *DL))
7989 return true;
7990 }
7991
7992 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
7993 if (GEPI->hasAllZeroIndices()) {
7994 /// The GEP operand must be a pointer, so must its result -> BitCast
7995 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
7996 GEPI->getName(), GEPI);
7997 NC->setDebugLoc(GEPI->getDebugLoc());
7998 GEPI->replaceAllUsesWith(NC);
7999 GEPI->eraseFromParent();
8000 ++NumGEPsElim;
8001 optimizeInst(NC, ModifiedDT);
8002 return true;
8003 }
8004 if (tryUnmergingGEPsAcrossIndirectBr(GEPI, TTI)) {
8005 return true;
8006 }
8007 return false;
8008 }
8009
8010 if (FreezeInst *FI = dyn_cast<FreezeInst>(I)) {
8011 // freeze(icmp a, const)) -> icmp (freeze a), const
8012 // This helps generate efficient conditional jumps.
8013 Instruction *CmpI = nullptr;
8014 if (ICmpInst *II = dyn_cast<ICmpInst>(FI->getOperand(0)))
8015 CmpI = II;
8016 else if (FCmpInst *F = dyn_cast<FCmpInst>(FI->getOperand(0)))
8017 CmpI = F->getFastMathFlags().none() ? F : nullptr;
8018
8019 if (CmpI && CmpI->hasOneUse()) {
8020 auto Op0 = CmpI->getOperand(0), Op1 = CmpI->getOperand(1);
8021 bool Const0 = isa<ConstantInt>(Op0) || isa<ConstantFP>(Op0) ||
8022 isa<ConstantPointerNull>(Op0);
8023 bool Const1 = isa<ConstantInt>(Op1) || isa<ConstantFP>(Op1) ||
8024 isa<ConstantPointerNull>(Op1);
8025 if (Const0 || Const1) {
8026 if (!Const0 || !Const1) {
8027 auto *F = new FreezeInst(Const0 ? Op1 : Op0, "", CmpI);
8028 F->takeName(FI);
8029 CmpI->setOperand(Const0 ? 1 : 0, F);
8030 }
8031 FI->replaceAllUsesWith(CmpI);
8032 FI->eraseFromParent();
8033 return true;
8034 }
8035 }
8036 return false;
8037 }
8038
8039 if (tryToSinkFreeOperands(I))
8040 return true;
8041
8042 switch (I->getOpcode()) {
8043 case Instruction::Shl:
8044 case Instruction::LShr:
8045 case Instruction::AShr:
8046 return optimizeShiftInst(cast<BinaryOperator>(I));
8047 case Instruction::Call:
8048 return optimizeCallInst(cast<CallInst>(I), ModifiedDT);
8049 case Instruction::Select:
8050 return optimizeSelectInst(cast<SelectInst>(I));
8051 case Instruction::ShuffleVector:
8052 return optimizeShuffleVectorInst(cast<ShuffleVectorInst>(I));
8053 case Instruction::Switch:
8054 return optimizeSwitchInst(cast<SwitchInst>(I));
8055 case Instruction::ExtractElement:
8056 return optimizeExtractElementInst(cast<ExtractElementInst>(I));
8057 case Instruction::Br:
8058 return optimizeBranch(cast<BranchInst>(I), *TLI);
8059 }
8060
8061 return false;
8062}
8063
8064/// Given an OR instruction, check to see if this is a bitreverse
8065/// idiom. If so, insert the new intrinsic and return true.
8066bool CodeGenPrepare::makeBitReverse(Instruction &I) {
8067 if (!I.getType()->isIntegerTy() ||
8068 !TLI->isOperationLegalOrCustom(ISD::BITREVERSE,
8069 TLI->getValueType(*DL, I.getType(), true)))
8070 return false;
8071
8072 SmallVector<Instruction*, 4> Insts;
8073 if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts))
8074 return false;
8075 Instruction *LastInst = Insts.back();
8076 I.replaceAllUsesWith(LastInst);
8077 RecursivelyDeleteTriviallyDeadInstructions(
8078 &I, TLInfo, nullptr, [&](Value *V) { removeAllAssertingVHReferences(V); });
8079 return true;
8080}
8081
8082// In this pass we look for GEP and cast instructions that are used
8083// across basic blocks and rewrite them to improve basic-block-at-a-time
8084// selection.
8085bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool &ModifiedDT) {
8086 SunkAddrs.clear();
8087 bool MadeChange = false;
8088
8089 CurInstIterator = BB.begin();
8090 while (CurInstIterator != BB.end()) {
8091 MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
8092 if (ModifiedDT)
8093 return true;
8094 }
8095
8096 bool MadeBitReverse = true;
8097 while (MadeBitReverse) {
8098 MadeBitReverse = false;
8099 for (auto &I : reverse(BB)) {
8100 if (makeBitReverse(I)) {
8101 MadeBitReverse = MadeChange = true;
8102 break;
8103 }
8104 }
8105 }
8106 MadeChange |= dupRetToEnableTailCallOpts(&BB, ModifiedDT);
8107
8108 return MadeChange;
8109}
8110
8111// Some CGP optimizations may move or alter what's computed in a block. Check
8112// whether a dbg.value intrinsic could be pointed at a more appropriate operand.
8113bool CodeGenPrepare::fixupDbgValue(Instruction *I) {
8114 assert(isa<DbgValueInst>(I))(static_cast <bool> (isa<DbgValueInst>(I)) ? void
(0) : __assert_fail ("isa<DbgValueInst>(I)", "llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 8114, __extension__ __PRETTY_FUNCTION__))
;
8115 DbgValueInst &DVI = *cast<DbgValueInst>(I);
8116
8117 // Does this dbg.value refer to a sunk address calculation?
8118 bool AnyChange = false;
8119 SmallDenseSet<Value *> LocationOps(DVI.location_ops().begin(),
8120 DVI.location_ops().end());
8121 for (Value *Location : LocationOps) {
8122 WeakTrackingVH SunkAddrVH = SunkAddrs[Location];
8123 Value *SunkAddr = SunkAddrVH.pointsToAliveValue() ? SunkAddrVH : nullptr;
8124 if (SunkAddr) {
8125 // Point dbg.value at locally computed address, which should give the best
8126 // opportunity to be accurately lowered. This update may change the type
8127 // of pointer being referred to; however this makes no difference to
8128 // debugging information, and we can't generate bitcasts that may affect
8129 // codegen.
8130 DVI.replaceVariableLocationOp(Location, SunkAddr);
8131 AnyChange = true;
8132 }
8133 }
8134 return AnyChange;
8135}
8136
8137// A llvm.dbg.value may be using a value before its definition, due to
8138// optimizations in this pass and others. Scan for such dbg.values, and rescue
8139// them by moving the dbg.value to immediately after the value definition.
8140// FIXME: Ideally this should never be necessary, and this has the potential
8141// to re-order dbg.value intrinsics.
8142bool CodeGenPrepare::placeDbgValues(Function &F) {
8143 bool MadeChange = false;
8144 DominatorTree DT(F);
8145
8146 for (BasicBlock &BB : F) {
8147 for (Instruction &Insn : llvm::make_early_inc_range(BB)) {
8148 DbgValueInst *DVI = dyn_cast<DbgValueInst>(&Insn);
8149 if (!DVI)
8150 continue;
8151
8152 SmallVector<Instruction *, 4> VIs;
8153 for (Value *V : DVI->getValues())
8154 if (Instruction *VI = dyn_cast_or_null<Instruction>(V))
8155 VIs.push_back(VI);
8156
8157 // This DVI may depend on multiple instructions, complicating any
8158 // potential sink. This block takes the defensive approach, opting to
8159 // "undef" the DVI if it has more than one instruction and any of them do
8160 // not dominate DVI.
8161 for (Instruction *VI : VIs) {
8162 if (VI->isTerminator())
8163 continue;
8164
8165 // If VI is a phi in a block with an EHPad terminator, we can't insert
8166 // after it.
8167 if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
8168 continue;
8169
8170 // If the defining instruction dominates the dbg.value, we do not need
8171 // to move the dbg.value.
8172 if (DT.dominates(VI, DVI))
8173 continue;
8174
8175 // If we depend on multiple instructions and any of them doesn't
8176 // dominate this DVI, we probably can't salvage it: moving it to
8177 // after any of the instructions could cause us to lose the others.
8178 if (VIs.size() > 1) {
8179 LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Unable to find valid location for Debug Value, undefing:\n"
<< *DVI; } } while (false)
8180 dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Unable to find valid location for Debug Value, undefing:\n"
<< *DVI; } } while (false)
8181 << "Unable to find valid location for Debug Value, undefing:\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Unable to find valid location for Debug Value, undefing:\n"
<< *DVI; } } while (false)
8182 << *DVI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Unable to find valid location for Debug Value, undefing:\n"
<< *DVI; } } while (false)
;
8183 DVI->setUndef();
8184 break;
8185 }
8186
8187 LLVM_DEBUG(dbgs() << "Moving Debug Value before :\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Moving Debug Value before :\n"
<< *DVI << ' ' << *VI; } } while (false)
8188 << *DVI << ' ' << *VI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Moving Debug Value before :\n"
<< *DVI << ' ' << *VI; } } while (false)
;
8189 DVI->removeFromParent();
8190 if (isa<PHINode>(VI))
8191 DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
8192 else
8193 DVI->insertAfter(VI);
8194 MadeChange = true;
8195 ++NumDbgValueMoved;
8196 }
8197 }
8198 }
8199 return MadeChange;
8200}
8201
8202// Group scattered pseudo probes in a block to favor SelectionDAG. Scattered
8203// probes can be chained dependencies of other regular DAG nodes and block DAG
8204// combine optimizations.
8205bool CodeGenPrepare::placePseudoProbes(Function &F) {
8206 bool MadeChange = false;
8207 for (auto &Block : F) {
8208 // Move the rest probes to the beginning of the block.
8209 auto FirstInst = Block.getFirstInsertionPt();
8210 while (FirstInst != Block.end() && FirstInst->isDebugOrPseudoInst())
8211 ++FirstInst;
8212 BasicBlock::iterator I(FirstInst);
8213 I++;
8214 while (I != Block.end()) {
8215 if (auto *II = dyn_cast<PseudoProbeInst>(I++)) {
8216 II->moveBefore(&*FirstInst);
8217 MadeChange = true;
8218 }
8219 }
8220 }
8221 return MadeChange;
8222}
8223
8224/// Scale down both weights to fit into uint32_t.
8225static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
8226 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
8227 uint32_t Scale = (NewMax / std::numeric_limits<uint32_t>::max()) + 1;
8228 NewTrue = NewTrue / Scale;
8229 NewFalse = NewFalse / Scale;
8230}
8231
8232/// Some targets prefer to split a conditional branch like:
8233/// \code
8234/// %0 = icmp ne i32 %a, 0
8235/// %1 = icmp ne i32 %b, 0
8236/// %or.cond = or i1 %0, %1
8237/// br i1 %or.cond, label %TrueBB, label %FalseBB
8238/// \endcode
8239/// into multiple branch instructions like:
8240/// \code
8241/// bb1:
8242/// %0 = icmp ne i32 %a, 0
8243/// br i1 %0, label %TrueBB, label %bb2
8244/// bb2:
8245/// %1 = icmp ne i32 %b, 0
8246/// br i1 %1, label %TrueBB, label %FalseBB
8247/// \endcode
8248/// This usually allows instruction selection to do even further optimizations
8249/// and combine the compare with the branch instruction. Currently this is
8250/// applied for targets which have "cheap" jump instructions.
8251///
8252/// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
8253///
8254bool CodeGenPrepare::splitBranchCondition(Function &F, bool &ModifiedDT) {
8255 if (!TM->Options.EnableFastISel || TLI->isJumpExpensive())
8256 return false;
8257
8258 bool MadeChange = false;
8259 for (auto &BB : F) {
8260 // Does this BB end with the following?
8261 // %cond1 = icmp|fcmp|binary instruction ...
8262 // %cond2 = icmp|fcmp|binary instruction ...
8263 // %cond.or = or|and i1 %cond1, cond2
8264 // br i1 %cond.or label %dest1, label %dest2"
8265 Instruction *LogicOp;
8266 BasicBlock *TBB, *FBB;
8267 if (!match(BB.getTerminator(),
8268 m_Br(m_OneUse(m_Instruction(LogicOp)), TBB, FBB)))
8269 continue;
8270
8271 auto *Br1 = cast<BranchInst>(BB.getTerminator());
8272 if (Br1->getMetadata(LLVMContext::MD_unpredictable))
8273 continue;
8274
8275 // The merging of mostly empty BB can cause a degenerate branch.
8276 if (TBB == FBB)
8277 continue;
8278
8279 unsigned Opc;
8280 Value *Cond1, *Cond2;
8281 if (match(LogicOp,
8282 m_LogicalAnd(m_OneUse(m_Value(Cond1)), m_OneUse(m_Value(Cond2)))))
8283 Opc = Instruction::And;
8284 else if (match(LogicOp, m_LogicalOr(m_OneUse(m_Value(Cond1)),
8285 m_OneUse(m_Value(Cond2)))))
8286 Opc = Instruction::Or;
8287 else
8288 continue;
8289
8290 auto IsGoodCond = [](Value *Cond) {
8291 return match(
8292 Cond,
8293 m_CombineOr(m_Cmp(), m_CombineOr(m_LogicalAnd(m_Value(), m_Value()),
8294 m_LogicalOr(m_Value(), m_Value()))));
8295 };
8296 if (!IsGoodCond(Cond1) || !IsGoodCond(Cond2))
8297 continue;
8298
8299 LLVM_DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Before branch condition splitting\n"
; BB.dump(); } } while (false)
;
8300
8301 // Create a new BB.
8302 auto *TmpBB =
8303 BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split",
8304 BB.getParent(), BB.getNextNode());
8305
8306 // Update original basic block by using the first condition directly by the
8307 // branch instruction and removing the no longer needed and/or instruction.
8308 Br1->setCondition(Cond1);
8309 LogicOp->eraseFromParent();
8310
8311 // Depending on the condition we have to either replace the true or the
8312 // false successor of the original branch instruction.
8313 if (Opc == Instruction::And)
8314 Br1->setSuccessor(0, TmpBB);
8315 else
8316 Br1->setSuccessor(1, TmpBB);
8317
8318 // Fill in the new basic block.
8319 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
8320 if (auto *I = dyn_cast<Instruction>(Cond2)) {
8321 I->removeFromParent();
8322 I->insertBefore(Br2);
8323 }
8324
8325 // Update PHI nodes in both successors. The original BB needs to be
8326 // replaced in one successor's PHI nodes, because the branch comes now from
8327 // the newly generated BB (NewBB). In the other successor we need to add one
8328 // incoming edge to the PHI nodes, because both branch instructions target
8329 // now the same successor. Depending on the original branch condition
8330 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
8331 // we perform the correct update for the PHI nodes.
8332 // This doesn't change the successor order of the just created branch
8333 // instruction (or any other instruction).
8334 if (Opc == Instruction::Or)
8335 std::swap(TBB, FBB);
8336
8337 // Replace the old BB with the new BB.
8338 TBB->replacePhiUsesWith(&BB, TmpBB);
8339
8340 // Add another incoming edge form the new BB.
8341 for (PHINode &PN : FBB->phis()) {
8342 auto *Val = PN.getIncomingValueForBlock(&BB);
8343 PN.addIncoming(Val, TmpBB);
8344 }
8345
8346 // Update the branch weights (from SelectionDAGBuilder::
8347 // FindMergedConditions).
8348 if (Opc == Instruction::Or) {
8349 // Codegen X | Y as:
8350 // BB1:
8351 // jmp_if_X TBB
8352 // jmp TmpBB
8353 // TmpBB:
8354 // jmp_if_Y TBB
8355 // jmp FBB
8356 //
8357
8358 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
8359 // The requirement is that
8360 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
8361 // = TrueProb for original BB.
8362 // Assuming the original weights are A and B, one choice is to set BB1's
8363 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
8364 // assumes that
8365 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
8366 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
8367 // TmpBB, but the math is more complicated.
8368 uint64_t TrueWeight, FalseWeight;
8369 if (extractBranchWeights(*Br1, TrueWeight, FalseWeight)) {
8370 uint64_t NewTrueWeight = TrueWeight;
8371 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
8372 scaleWeights(NewTrueWeight, NewFalseWeight);
8373 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
8374 .createBranchWeights(TrueWeight, FalseWeight));
8375
8376 NewTrueWeight = TrueWeight;
8377 NewFalseWeight = 2 * FalseWeight;
8378 scaleWeights(NewTrueWeight, NewFalseWeight);
8379 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
8380 .createBranchWeights(TrueWeight, FalseWeight));
8381 }
8382 } else {
8383 // Codegen X & Y as:
8384 // BB1:
8385 // jmp_if_X TmpBB
8386 // jmp FBB
8387 // TmpBB:
8388 // jmp_if_Y TBB
8389 // jmp FBB
8390 //
8391 // This requires creation of TmpBB after CurBB.
8392
8393 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
8394 // The requirement is that
8395 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
8396 // = FalseProb for original BB.
8397 // Assuming the original weights are A and B, one choice is to set BB1's
8398 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
8399 // assumes that
8400 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
8401 uint64_t TrueWeight, FalseWeight;
8402 if (extractBranchWeights(*Br1, TrueWeight, FalseWeight)) {
8403 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
8404 uint64_t NewFalseWeight = FalseWeight;
8405 scaleWeights(NewTrueWeight, NewFalseWeight);
8406 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
8407 .createBranchWeights(TrueWeight, FalseWeight));
8408
8409 NewTrueWeight = 2 * TrueWeight;
8410 NewFalseWeight = FalseWeight;
8411 scaleWeights(NewTrueWeight, NewFalseWeight);
8412 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
8413 .createBranchWeights(TrueWeight, FalseWeight));
8414 }
8415 }
8416
8417 ModifiedDT = true;
8418 MadeChange = true;
8419
8420 LLVM_DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "After branch condition splitting\n"
; BB.dump(); TmpBB->dump(); } } while (false)
8421 TmpBB->dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "After branch condition splitting\n"
; BB.dump(); TmpBB->dump(); } } while (false)
;
8422 }
8423 return MadeChange;
8424}