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