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

source code of llvm/lib/CodeGen/CodeGenPrepare.cpp