Bug Summary

File:llvm/lib/CodeGen/CodeGenPrepare.cpp
Warning:line 3998, column 20
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 -disable-llvm-verifier -discard-value-names -main-file-name CodeGenPrepare.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -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 -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-12/lib/clang/12.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/build-llvm/lib/CodeGen -I /build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/llvm/lib/CodeGen -I /build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-12/lib/clang/12.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/build-llvm/lib/CodeGen -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-09-26-161721-17566-1 -x c++ /build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/llvm/lib/CodeGen/CodeGenPrepare.cpp

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