LLVM 19.0.0git
CodeGenPrepare.cpp
Go to the documentation of this file.
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
16#include "llvm/ADT/APInt.h"
17#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/DenseMap.h"
19#include "llvm/ADT/MapVector.h"
21#include "llvm/ADT/STLExtras.h"
24#include "llvm/ADT/Statistic.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"
52#include "llvm/IR/Dominators.h"
53#include "llvm/IR/Function.h"
55#include "llvm/IR/GlobalValue.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"
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"
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"
79#include "llvm/Pass.h"
85#include "llvm/Support/Debug.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
137 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
138 cl::desc("Disable branch optimizations in CodeGenPrepare"));
139
140static cl::opt<bool>
141 DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
142 cl::desc("Disable GC optimizations in CodeGenPrepare"));
143
144static cl::opt<bool>
145 DisableSelectToBranch("disable-cgp-select2branch", cl::Hidden,
146 cl::init(false),
147 cl::desc("Disable select to branch conversion."));
148
149static cl::opt<bool>
150 AddrSinkUsingGEPs("addr-sink-using-gep", cl::Hidden, cl::init(true),
151 cl::desc("Address sinking in CGP using GEPs."));
152
153static cl::opt<bool>
154 EnableAndCmpSinking("enable-andcmp-sinking", cl::Hidden, cl::init(true),
155 cl::desc("Enable sinkinig and/cmp into branches."));
156
158 "disable-cgp-store-extract", cl::Hidden, cl::init(false),
159 cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
160
162 "stress-cgp-store-extract", cl::Hidden, cl::init(false),
163 cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
164
166 "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
167 cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
168 "CodeGenPrepare"));
169
171 "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
172 cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
173 "optimization in CodeGenPrepare"));
174
176 "disable-preheader-prot", cl::Hidden, cl::init(false),
177 cl::desc("Disable protection against removing loop preheaders"));
178
180 "profile-guided-section-prefix", cl::Hidden, cl::init(true),
181 cl::desc("Use profile info to add section prefix for hot/cold functions"));
182
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
194 "bbsections-guided-section-prefix", cl::Hidden, cl::init(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
203 "cgp-freq-ratio-to-skip-merge", cl::Hidden, cl::init(2),
204 cl::desc("Skip merging empty blocks if (frequency of empty block) / "
205 "(frequency of destination block) is greater than this ratio"));
206
208 "force-split-store", cl::Hidden, cl::init(false),
209 cl::desc("Force store splitting no matter what the target query says."));
210
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(true));
216
218 "disable-complex-addr-modes", cl::Hidden, cl::init(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(false),
224 cl::desc("Allow creation of Phis in Address sinking."));
225
227 "addr-sink-new-select", cl::Hidden, cl::init(true),
228 cl::desc("Allow creation of selects in Address sinking."));
229
231 "addr-sink-combine-base-reg", cl::Hidden, cl::init(true),
232 cl::desc("Allow combining of BaseReg field in Address sinking."));
233
235 "addr-sink-combine-base-gv", cl::Hidden, cl::init(true),
236 cl::desc("Allow combining of BaseGV field in Address sinking."));
237
239 "addr-sink-combine-base-offs", cl::Hidden, cl::init(true),
240 cl::desc("Allow combining of BaseOffs field in Address sinking."));
241
243 "addr-sink-combine-scaled-reg", cl::Hidden, cl::init(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(true),
249 cl::desc("Enable splitting large offset of GEP."));
250
252 "cgp-icmp-eq2icmp-st", cl::Hidden, cl::init(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(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(true),
262 cl::desc("Enable converting phi types in CodeGenPrepare"));
263
265 HugeFuncThresholdInCGPP("cgpp-huge-func", cl::init(10000), cl::Hidden,
266 cl::desc("Least BB number of huge function."));
267
269 MaxAddressUsersToScan("cgp-max-address-users-to-scan", cl::init(100),
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(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>;
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.
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.
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.
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
391
392private:
393 template <typename F>
394 void resetIteratorIfInvalidatedWhileCalling(BasicBlock *BB, F f) {
395 // Substituting can cause recursive simplifications, which can invalidate
396 // our iterator. Use a WeakTrackingVH to hold onto it in case this
397 // happens.
398 Value *CurValue = &*CurInstIterator;
399 WeakTrackingVH IterHandle(CurValue);
400
401 f();
402
403 // If the iterator instruction was recursively deleted, start over at the
404 // start of the block.
405 if (IterHandle != CurValue) {
406 CurInstIterator = BB->begin();
407 SunkAddrs.clear();
408 }
409 }
410
411 // Get the DominatorTree, building if necessary.
412 DominatorTree &getDT(Function &F) {
413 if (!DT)
414 DT = std::make_unique<DominatorTree>(F);
415 return *DT;
416 }
417
418 void removeAllAssertingVHReferences(Value *V);
419 bool eliminateAssumptions(Function &F);
420 bool eliminateFallThrough(Function &F, 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 fixupDbgVariableRecord(DbgVariableRecord &I);
449 bool fixupDbgVariableRecordsOnInst(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,
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) {
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.
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(new BranchProbabilityInfo(F, *CGP.LI));
520 CGP.BFI.reset(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)
537INITIALIZE_PASS_END(CodeGenPrepareLegacyPass, DEBUG_TYPE,
538 "Optimize for code generation", false, false)
539
541 return new CodeGenPrepareLegacyPass();
542}
543
546 CodeGenPrepare CGP(TM);
547
548 bool Changed = CGP.run(F, AM);
549 if (!Changed)
550 return PreservedAnalyses::all();
551
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>(F);
566 LI = &AM.getResult<LoopAnalysis>(F);
567 BPI.reset(new BranchProbabilityInfo(F, *LI));
568 BFI.reset(new BlockFrequencyInfo(F, *BPI, *LI));
569 auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
570 PSI = MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
571 BBSectionsProfileReader =
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(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, *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, *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 =
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.get()))
615 EverMadeChange |= bypassSlowDivision(BB, 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;
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(getDT(F));
646
647 bool MadeChange = true;
648 bool FuncIterated = false;
649 while (MadeChange) {
650 MadeChange = false;
651
653 if (FuncIterated && !FreshBBs.contains(&BB))
654 continue;
655
656 ModifyDT ModifiedDTOnIteration = ModifyDT::NotModifyDT;
657 bool Changed = optimizeBlock(BB, 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(&BB);
675 else if (FuncIterated)
676 FreshBBs.erase(&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.get());
695
696#ifndef NDEBUG
697 if (MadeChange && VerifyLoopInfo)
698 LI->verify(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.
722 for (BasicBlock &BB : F) {
724 MadeChange |= ConstantFoldTerminator(&BB, true);
725 if (!MadeChange)
726 continue;
727
728 for (BasicBlock *Succ : Successors)
729 if (pred_empty(Succ))
730 WorkList.insert(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();
738
739 DeleteDeadBlock(BB);
740
741 for (BasicBlock *Succ : Successors)
742 if (pred_empty(Succ))
743 WorkList.insert(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) {
756 for (BasicBlock &BB : F)
757 for (Instruction &I : BB)
758 if (auto *SP = dyn_cast<GCStatepointInst>(&I))
759 Statepoints.push_back(SP);
760 for (auto &I : Statepoints)
761 EverMadeChange |= simplifyOffsetableRelocate(*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
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>(I)) {
784 MadeChange = true;
785 Value *Operand = Assume->getOperand(0);
786 Assume->eraseFromParent();
787
788 resetIteratorIfInvalidatedWhileCalling(&BB, [&]() {
789 RecursivelyDeleteTriviallyDeadInstructions(Operand, TLInfo, 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(V);
801 NewGEPBases.erase(V);
802
803 auto GEP = dyn_cast<GetElementPtrInst>(V);
804 if (!GEP)
805 return;
806
807 LargeOffsetGEPID.erase(GEP);
808
809 auto VecI = LargeOffsetGEPMap.find(GEP->getPointerOperand());
810 if (VecI == LargeOffsetGEPMap.end())
811 return;
812
813 auto &GEPVector = VecI->second;
814 llvm::erase_if(GEPVector, [=](auto &Elt) { return Elt.first == GEP; });
815
816 if (GEPVector.empty())
817 LargeOffsetGEPMap.erase(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(*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.
838 for (auto &Block : llvm::drop_begin(F))
839 Blocks.push_back(&Block);
840
842 for (auto &Block : Blocks) {
843 auto *BB = cast_or_null<BasicBlock>(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(BB))
856 continue;
857
858 BranchInst *Term = dyn_cast<BranchInst>(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(SinglePred);
868
869 if (IsHugeFunc) {
870 // Update FreshBBs to optimize the merged BB.
871 FreshBBs.insert(SinglePred);
872 FreshBBs.erase(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>(Pred))
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>(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.
896 if (BBI != BB->begin()) {
897 --BBI;
898 while (isa<DbgInfoIntrinsic>(BBI)) {
899 if (BBI == BB->begin())
900 break;
901 --BBI;
902 }
903 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
904 return nullptr;
905 }
906
907 // Do not break infinite loops.
908 BasicBlock *DestBB = BI->getSuccessor(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) {
924 SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end());
925 while (!LoopList.empty()) {
926 Loop *L = LoopList.pop_back_val();
927 llvm::append_range(LoopList, *L);
928 if (BasicBlock *Preheader = L->getLoopPreheader())
929 Preheaders.insert(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.
937 for (auto &Block : llvm::drop_begin(F)) {
938 // Delete phi nodes that could block deleting other empty blocks.
940 MadeChange |= DeleteDeadPHIs(&Block, TLInfo);
941 Blocks.push_back(&Block);
942 }
943
944 for (auto &Block : Blocks) {
945 BasicBlock *BB = cast_or_null<BasicBlock>(Block);
946 if (!BB)
947 continue;
948 BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB);
949 if (!DestBB ||
950 !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.count(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() &&
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>(Pred->getTerminator()) &&
976 llvm::is_contained(successors(Pred), 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>(Pred->getTerminator()) ||
990 isa<IndirectBrInst>(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>(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(DestBB)) {
1015 if (DestBBPred == BB)
1016 continue;
1017
1018 if (llvm::all_of(DestBB->phis(), [&](const PHINode &DestPN) {
1019 return DestPN.getIncomingValueForBlock(BB) ==
1020 DestPN.getIncomingValueForBlock(DestBBPred);
1021 }))
1022 SameIncomingValueBBs.insert(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(Pred))
1029 return true;
1030
1031 BlockFrequency PredFreq = BFI->getBlockFreq(Pred);
1032 BlockFrequency BBFreq = BFI->getBlockFreq(BB);
1033
1034 for (auto *SameValueBB : SameIncomingValueBBs)
1035 if (SameValueBB->getUniquePredecessor() == Pred &&
1036 DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB))
1037 BBFreq += BFI->getBlockFreq(SameValueBB);
1038
1039 std::optional<BlockFrequency> Limit = BBFreq.mul(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>(U);
1054 if (UI->getParent() != DestBB || !isa<PHINode>(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>(UI))
1061 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
1062 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
1063 if (Insn && Insn->getParent() == BB &&
1064 Insn->getParent() != UPN->getIncomingBlock(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>(DestBB->begin());
1075 if (!DestBBPN)
1076 return true; // no conflict.
1077
1078 // Collect the preds of BB.
1080 if (const PHINode *BBPN = dyn_cast<PHINode>(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(BBPN->getIncomingBlock(i));
1084 } else {
1085 BBPreds.insert(pred_begin(BB), 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(Pred)) { // Common predecessor?
1092 for (const PHINode &PN : DestBB->phis()) {
1093 const Value *V1 = PN.getIncomingValueForBlock(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>(V2))
1098 if (V2PN->getParent() == BB)
1099 V2 = V2PN->getIncomingValueForBlock(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,
1114 bool IsHuge) {
1115 auto *OldI = dyn_cast<Instruction>(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>(*UI);
1120 if (IsHuge)
1121 FreshBBs.insert(User->getParent());
1122 }
1123 }
1124 Old->replaceAllUsesWith(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>(BB->getTerminator());
1131 BasicBlock *DestBB = BI->getSuccessor(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.
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(SinglePred);
1151 FreshBBs.erase(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, 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>(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(InValPhi->getIncomingValue(i),
1170 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>(BB->begin())) {
1175 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
1176 PN.addIncoming(InVal, BBPN->getIncomingBlock(i));
1177 } else {
1178 for (BasicBlock *Pred : predecessors(BB))
1179 PN.addIncoming(InVal, 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(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
1196 const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
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
1203 for (auto *ThisRelocate : AllRelocateCalls) {
1204 auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
1205 ThisRelocate->getDerivedPtrIndex());
1206 RelocateIdxMap.insert(std::make_pair(K, 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(Key.first, Key.first);
1216
1217 // We're iterating over RelocateIdxMap so we cannot modify it.
1218 auto MaybeBase = RelocateIdxMap.find(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(I);
1225 }
1226}
1227
1228// Accepts a GEP and extracts the operands into a vector provided they're all
1229// small integer constants
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>(GEP->getOperand(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(GEP->getOperand(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
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>(R))
1259 if (RI->getStatepoint() == RelocatedBase->getStatepoint())
1260 if (RI->getBasePtrIndex() == RelocatedBase->getBasePtrIndex()) {
1261 RelocatedBase->moveBefore(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>(ToReplace->getDerivedPtr());
1284 if (!Derived || Derived->getPointerOperand() != Base)
1285 continue;
1286
1288 if (!getGEPSmallConstantIntOffsetV(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(RelocatedBase, Base->getType());
1325 }
1326 Value *Replacement =
1327 Builder.CreateGEP(Derived->getSourceElementType(), ActualRelocatedBase,
1328 ArrayRef(OffsetV));
1329 Replacement->takeName(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(Replacement, ToReplace->getType());
1337 }
1338 ToReplace->replaceAllUsesWith(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>(U))
1368 // Collect all the relocate calls associated with a statepoint
1369 AllRelocateCalls.push_back(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
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(Item.first, 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.
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>(*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>(User)) {
1407 UserBB = PN->getIncomingBlock(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(), CI->getOperand(0),
1435 CI->getType(), "");
1436 InsertedCast->insertBefore(*UserBB, 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(*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.
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>(CI)) {
1466 if (!TLI.isFreeAddrSpaceCast(ASC->getSrcAddressSpace(),
1467 ASC->getDestAddressSpace()))
1468 return false;
1469 }
1470
1471 // If this is a noop copy,
1472 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
1473 EVT DstVT = TLI.getValueType(DL, 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(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(CI->getContext(), SrcVT) ==
1489 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
1490 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
1492 DstVT = TLI.getTypeToTransformTo(CI->getContext(), 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(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(PN->getParent());
1525 if (!L || L->getHeader() != PN->getParent() || !L->getLoopLatch())
1526 return std::nullopt;
1527 auto *IVInc =
1528 dyn_cast<Instruction>(PN->getIncomingValueForBlock(L->getLoopLatch()));
1529 if (!IVInc || LI->getLoopFor(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(IVInc, Step);
1535 return std::nullopt;
1536}
1537
1538static bool isIVIncrement(const Value *V, const LoopInfo *LI) {
1539 auto *I = dyn_cast<Instruction>(V);
1540 if (!I)
1541 return false;
1542 Instruction *LHS = nullptr;
1543 Constant *Step = nullptr;
1544 if (!matchIncrement(I, LHS, Step))
1545 return false;
1546 if (auto *PN = dyn_cast<PHINode>(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(BO, LI))
1558 return false;
1559 const Loop *L = LI->getLoopFor(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(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(*BO->getParent()->getParent());
1569 if (DT.dominates(Cmp->getParent(), 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(Cmp->getParent(), 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(cast<Constant>(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(IID, Arg0, Arg1);
1620 if (BO->getOpcode() != Instruction::Xor) {
1621 Value *Math = Builder.CreateExtractValue(MathOV, 0, "math");
1622 replaceAllUsesWith(BO, Math, FreshBBs, IsHugeFunc);
1623 } else
1624 assert(BO->hasOneUse() &&
1625 "Patterns with XOr should use the BO only in the compare");
1626 Value *OV = Builder.CreateExtractValue(MathOV, 1, "ov");
1627 replaceAllUsesWith(Cmp, OV, FreshBBs, IsHugeFunc);
1628 Cmp->eraseFromParent();
1629 BO->eraseFromParent();
1630 return true;
1631}
1632
1633/// Match special-case patterns that check for unsigned add overflow.
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(0), *B = Cmp->getOperand(1);
1639
1640 // We are not expecting non-canonical/degenerate code. Just bail out.
1641 if (isa<Constant>(A))
1642 return false;
1643
1644 ICmpInst::Predicate Pred = Cmp->getPredicate();
1645 if (Pred == ICmpInst::ICMP_EQ && match(B, m_AllOnes()))
1646 B = ConstantInt::get(B->getType(), 1);
1647 else if (Pred == ICmpInst::ICMP_NE && match(B, m_ZeroInt()))
1648 B = ConstantInt::get(B->getType(), -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(U, m_Add(m_Specific(A), m_Specific(B)))) {
1656 Add = cast<BinaryOperator>(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;
1670 if (!match(Cmp, m_UAddWithOverflow(m_Value(A), m_Value(B), m_BinOp(Add)))) {
1672 return false;
1673 // Set A and B in case we match matchUAddWithOverflowConstantEdgeCases.
1674 A = Add->getOperand(0);
1675 B = Add->getOperand(1);
1676 EdgeCase = true;
1677 }
1678
1680 TLI->getValueType(*DL, Add->getType()),
1681 Add->hasNUsesOrMore(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(Add, A, B, Cmp,
1691 Intrinsic::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(0), *B = Cmp->getOperand(1);
1703 if (isa<Constant>(A) && isa<Constant>(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, 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(B, m_ZeroInt())) {
1714 B = ConstantInt::get(B->getType(), 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(B, m_ZeroInt())) {
1719 std::swap(A, 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>(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(U, m_Sub(m_Specific(A), m_Specific(B)))) {
1733 Sub = cast<BinaryOperator>(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(U, m_Add(m_Specific(A), m_APInt(AddC))) &&
1740 match(B, m_APInt(CmpC)) && *AddC == -(*CmpC)) {
1741 Sub = cast<BinaryOperator>(U);
1742 break;
1743 }
1744 }
1745 if (!Sub)
1746 return false;
1747
1749 TLI->getValueType(*DL, Sub->getType()),
1750 Sub->hasNUsesOrMore(1)))
1751 return false;
1752
1753 if (!replaceMathCmpWithIntrinsic(Sub, Sub->getOperand(0), Sub->getOperand(1),
1754 Cmp, Intrinsic::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) {
1770 return false;
1771
1772 // Avoid sinking soft-FP comparisons, since this can move them into a loop.
1773 if (TLI.useSoftFloat() && isa<FCmpInst>(Cmp))
1774 return false;
1775
1776 // Only insert a cmp in each block once.
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>(*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>(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(Cmp->getOpcode(), Cmp->getPredicate(),
1807 Cmp->getOperand(0), Cmp->getOperand(1), "");
1808 InsertedCmp->insertBefore(*UserBB, 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.
1848 const TargetLowering &TLI) {
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>(U))
1860 continue;
1861 if (isa<SelectInst>(U) && cast<SelectInst>(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(DomBB->getTerminator(), m_Br(m_Value(DomCond), TrueBB, FalseBB)))
1879 return false;
1880 if (CmpBB != FalseBB)
1881 return false;
1882
1883 Value *CmpOp0 = Cmp->getOperand(0), *CmpOp1 = Cmp->getOperand(1);
1884 ICmpInst::Predicate DomPred;
1885 if (!match(DomCond, m_ICmp(DomPred, m_Specific(CmpOp0), m_Specific(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>(U)) {
1899 assert(BI->isConditional() && "Must be conditional");
1900 BI->swapSuccessors();
1901 continue;
1902 }
1903 if (auto *SI = dyn_cast<SelectInst>(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(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.
1918 Value *Op0 = Cmp->getOperand(0);
1919 Value *Op1 = Cmp->getOperand(1);
1920 if (!Op0->getType()->isIntegerTy() || isa<Constant>(Op0) ||
1921 isa<Constant>(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(U, m_Sub(m_Specific(Op1), m_Specific(Op0))))
1934 GoodToSwap++;
1935 else if (match(U, m_Sub(m_Specific(Op0), m_Specific(Op1))))
1936 GoodToSwap--;
1937 }
1938
1939 if (GoodToSwap > 0) {
1940 Cmp->swapOperands();
1941 return true;
1942 }
1943 return false;
1944}
1945
1946static bool foldFCmpToFPClassTest(CmpInst *Cmp, const TargetLowering &TLI,
1947 const DataLayout &DL) {
1948 FCmpInst *FCmp = dyn_cast<FCmpInst>(Cmp);
1949 if (!FCmp)
1950 return false;
1951
1952 // Don't fold if the target offers free fabs and the predicate is legal.
1953 EVT VT = TLI.getValueType(DL, Cmp->getOperand(0)->getType());
1954 if (TLI.isFAbsFree(VT) &&
1956 VT.getSimpleVT()))
1957 return false;
1958
1959 // Reverse the canonicalization if it is a FP class test
1960 auto ShouldReverseTransform = [](FPClassTest ClassTest) {
1961 return ClassTest == fcInf || ClassTest == (fcInf | fcNan);
1962 };
1963 auto [ClassVal, ClassTest] =
1964 fcmpToClassTest(FCmp->getPredicate(), *FCmp->getParent()->getParent(),
1965 FCmp->getOperand(0), FCmp->getOperand(1));
1966 if (!ClassVal)
1967 return false;
1968
1969 if (!ShouldReverseTransform(ClassTest) && !ShouldReverseTransform(~ClassTest))
1970 return false;
1971
1972 IRBuilder<> Builder(Cmp);
1973 Value *IsFPClass = Builder.createIsFPClass(ClassVal, ClassTest);
1974 Cmp->replaceAllUsesWith(IsFPClass);
1976 return true;
1977}
1978
1979bool CodeGenPrepare::optimizeCmp(CmpInst *Cmp, ModifyDT &ModifiedDT) {
1980 if (sinkCmpExpression(Cmp, *TLI))
1981 return true;
1982
1983 if (combineToUAddWithOverflow(Cmp, ModifiedDT))
1984 return true;
1985
1986 if (combineToUSubWithOverflow(Cmp, ModifiedDT))
1987 return true;
1988
1989 if (foldICmpWithDominatingICmp(Cmp, *TLI))
1990 return true;
1991
1993 return true;
1994
1995 if (foldFCmpToFPClassTest(Cmp, *TLI, *DL))
1996 return true;
1997
1998 return false;
1999}
2000
2001/// Duplicate and sink the given 'and' instruction into user blocks where it is
2002/// used in a compare to allow isel to generate better code for targets where
2003/// this operation can be combined.
2004///
2005/// Return true if any changes are made.
2007 SetOfInstrs &InsertedInsts) {
2008 // Double-check that we're not trying to optimize an instruction that was
2009 // already optimized by some other part of this pass.
2010 assert(!InsertedInsts.count(AndI) &&
2011 "Attempting to optimize already optimized and instruction");
2012 (void)InsertedInsts;
2013
2014 // Nothing to do for single use in same basic block.
2015 if (AndI->hasOneUse() &&
2016 AndI->getParent() == cast<Instruction>(*AndI->user_begin())->getParent())
2017 return false;
2018
2019 // Try to avoid cases where sinking/duplicating is likely to increase register
2020 // pressure.
2021 if (!isa<ConstantInt>(AndI->getOperand(0)) &&
2022 !isa<ConstantInt>(AndI->getOperand(1)) &&
2023 AndI->getOperand(0)->hasOneUse() && AndI->getOperand(1)->hasOneUse())
2024 return false;
2025
2026 for (auto *U : AndI->users()) {
2027 Instruction *User = cast<Instruction>(U);
2028
2029 // Only sink 'and' feeding icmp with 0.
2030 if (!isa<ICmpInst>(User))
2031 return false;
2032
2033 auto *CmpC = dyn_cast<ConstantInt>(User->getOperand(1));
2034 if (!CmpC || !CmpC->isZero())
2035 return false;
2036 }
2037
2038 if (!TLI.isMaskAndCmp0FoldingBeneficial(*AndI))
2039 return false;
2040
2041 LLVM_DEBUG(dbgs() << "found 'and' feeding only icmp 0;\n");
2042 LLVM_DEBUG(AndI->getParent()->dump());
2043
2044 // Push the 'and' into the same block as the icmp 0. There should only be
2045 // one (icmp (and, 0)) in each block, since CSE/GVN should have removed any
2046 // others, so we don't need to keep track of which BBs we insert into.
2047 for (Value::user_iterator UI = AndI->user_begin(), E = AndI->user_end();
2048 UI != E;) {
2049 Use &TheUse = UI.getUse();
2050 Instruction *User = cast<Instruction>(*UI);
2051
2052 // Preincrement use iterator so we don't invalidate it.
2053 ++UI;
2054
2055 LLVM_DEBUG(dbgs() << "sinking 'and' use: " << *User << "\n");
2056
2057 // Keep the 'and' in the same place if the use is already in the same block.
2058 Instruction *InsertPt =
2059 User->getParent() == AndI->getParent() ? AndI : User;
2060 Instruction *InsertedAnd = BinaryOperator::Create(
2061 Instruction::And, AndI->getOperand(0), AndI->getOperand(1), "",
2062 InsertPt->getIterator());
2063 // Propagate the debug info.
2064 InsertedAnd->setDebugLoc(AndI->getDebugLoc());
2065
2066 // Replace a use of the 'and' with a use of the new 'and'.
2067 TheUse = InsertedAnd;
2068 ++NumAndUses;
2069 LLVM_DEBUG(User->getParent()->dump());
2070 }
2071
2072 // We removed all uses, nuke the and.
2073 AndI->eraseFromParent();
2074 return true;
2075}
2076
2077/// Check if the candidates could be combined with a shift instruction, which
2078/// includes:
2079/// 1. Truncate instruction
2080/// 2. And instruction and the imm is a mask of the low bits:
2081/// imm & (imm+1) == 0
2083 if (!isa<TruncInst>(User)) {
2084 if (User->getOpcode() != Instruction::And ||
2085 !isa<ConstantInt>(User->getOperand(1)))
2086 return false;
2087
2088 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
2089
2090 if ((Cimm & (Cimm + 1)).getBoolValue())
2091 return false;
2092 }
2093 return true;
2094}
2095
2096/// Sink both shift and truncate instruction to the use of truncate's BB.
2097static bool
2100 const TargetLowering &TLI, const DataLayout &DL) {
2101 BasicBlock *UserBB = User->getParent();
2103 auto *TruncI = cast<TruncInst>(User);
2104 bool MadeChange = false;
2105
2106 for (Value::user_iterator TruncUI = TruncI->user_begin(),
2107 TruncE = TruncI->user_end();
2108 TruncUI != TruncE;) {
2109
2110 Use &TruncTheUse = TruncUI.getUse();
2111 Instruction *TruncUser = cast<Instruction>(*TruncUI);
2112 // Preincrement use iterator so we don't invalidate it.
2113
2114 ++TruncUI;
2115
2116 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
2117 if (!ISDOpcode)
2118 continue;
2119
2120 // If the use is actually a legal node, there will not be an
2121 // implicit truncate.
2122 // FIXME: always querying the result type is just an
2123 // approximation; some nodes' legality is determined by the
2124 // operand or other means. There's no good way to find out though.
2126 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
2127 continue;
2128
2129 // Don't bother for PHI nodes.
2130 if (isa<PHINode>(TruncUser))
2131 continue;
2132
2133 BasicBlock *TruncUserBB = TruncUser->getParent();
2134
2135 if (UserBB == TruncUserBB)
2136 continue;
2137
2138 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
2139 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
2140
2141 if (!InsertedShift && !InsertedTrunc) {
2142 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
2143 assert(InsertPt != TruncUserBB->end());
2144 // Sink the shift
2145 if (ShiftI->getOpcode() == Instruction::AShr)
2146 InsertedShift =
2147 BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "");
2148 else
2149 InsertedShift =
2150 BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "");
2151 InsertedShift->setDebugLoc(ShiftI->getDebugLoc());
2152 InsertedShift->insertBefore(*TruncUserBB, InsertPt);
2153
2154 // Sink the trunc
2155 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
2156 TruncInsertPt++;
2157 // It will go ahead of any debug-info.
2158 TruncInsertPt.setHeadBit(true);
2159 assert(TruncInsertPt != TruncUserBB->end());
2160
2161 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
2162 TruncI->getType(), "");
2163 InsertedTrunc->insertBefore(*TruncUserBB, TruncInsertPt);
2164 InsertedTrunc->setDebugLoc(TruncI->getDebugLoc());
2165
2166 MadeChange = true;
2167
2168 TruncTheUse = InsertedTrunc;
2169 }
2170 }
2171 return MadeChange;
2172}
2173
2174/// Sink the shift *right* instruction into user blocks if the uses could
2175/// potentially be combined with this shift instruction and generate BitExtract
2176/// instruction. It will only be applied if the architecture supports BitExtract
2177/// instruction. Here is an example:
2178/// BB1:
2179/// %x.extract.shift = lshr i64 %arg1, 32
2180/// BB2:
2181/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
2182/// ==>
2183///
2184/// BB2:
2185/// %x.extract.shift.1 = lshr i64 %arg1, 32
2186/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
2187///
2188/// CodeGen will recognize the pattern in BB2 and generate BitExtract
2189/// instruction.
2190/// Return true if any changes are made.
2192 const TargetLowering &TLI,
2193 const DataLayout &DL) {
2194 BasicBlock *DefBB = ShiftI->getParent();
2195
2196 /// Only insert instructions in each block once.
2198
2199 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
2200
2201 bool MadeChange = false;
2202 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
2203 UI != E;) {
2204 Use &TheUse = UI.getUse();
2205 Instruction *User = cast<Instruction>(*UI);
2206 // Preincrement use iterator so we don't invalidate it.
2207 ++UI;
2208
2209 // Don't bother for PHI nodes.
2210 if (isa<PHINode>(User))
2211 continue;
2212
2214 continue;
2215
2216 BasicBlock *UserBB = User->getParent();
2217
2218 if (UserBB == DefBB) {
2219 // If the shift and truncate instruction are in the same BB. The use of
2220 // the truncate(TruncUse) may still introduce another truncate if not
2221 // legal. In this case, we would like to sink both shift and truncate
2222 // instruction to the BB of TruncUse.
2223 // for example:
2224 // BB1:
2225 // i64 shift.result = lshr i64 opnd, imm
2226 // trunc.result = trunc shift.result to i16
2227 //
2228 // BB2:
2229 // ----> We will have an implicit truncate here if the architecture does
2230 // not have i16 compare.
2231 // cmp i16 trunc.result, opnd2
2232 //
2233 if (isa<TruncInst>(User) &&
2234 shiftIsLegal
2235 // If the type of the truncate is legal, no truncate will be
2236 // introduced in other basic blocks.
2237 && (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
2238 MadeChange =
2239 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
2240
2241 continue;
2242 }
2243 // If we have already inserted a shift into this block, use it.
2244 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
2245
2246 if (!InsertedShift) {
2247 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
2248 assert(InsertPt != UserBB->end());
2249
2250 if (ShiftI->getOpcode() == Instruction::AShr)
2251 InsertedShift =
2252 BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "");
2253 else
2254 InsertedShift =
2255 BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "");
2256 InsertedShift->insertBefore(*UserBB, InsertPt);
2257 InsertedShift->setDebugLoc(ShiftI->getDebugLoc());
2258
2259 MadeChange = true;
2260 }
2261
2262 // Replace a use of the shift with a use of the new shift.
2263 TheUse = InsertedShift;
2264 }
2265
2266 // If we removed all uses, or there are none, nuke the shift.
2267 if (ShiftI->use_empty()) {
2268 salvageDebugInfo(*ShiftI);
2269 ShiftI->eraseFromParent();
2270 MadeChange = true;
2271 }
2272
2273 return MadeChange;
2274}
2275
2276/// If counting leading or trailing zeros is an expensive operation and a zero
2277/// input is defined, add a check for zero to avoid calling the intrinsic.
2278///
2279/// We want to transform:
2280/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
2281///
2282/// into:
2283/// entry:
2284/// %cmpz = icmp eq i64 %A, 0
2285/// br i1 %cmpz, label %cond.end, label %cond.false
2286/// cond.false:
2287/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
2288/// br label %cond.end
2289/// cond.end:
2290/// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
2291///
2292/// If the transform is performed, return true and set ModifiedDT to true.
2293static bool despeculateCountZeros(IntrinsicInst *CountZeros,
2294 LoopInfo &LI,
2295 const TargetLowering *TLI,
2296 const DataLayout *DL, ModifyDT &ModifiedDT,
2298 bool IsHugeFunc) {
2299 // If a zero input is undefined, it doesn't make sense to despeculate that.
2300 if (match(CountZeros->getOperand(1), m_One()))
2301 return false;
2302
2303 // If it's cheap to speculate, there's nothing to do.
2304 Type *Ty = CountZeros->getType();
2305 auto IntrinsicID = CountZeros->getIntrinsicID();
2306 if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz(Ty)) ||
2307 (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz(Ty)))
2308 return false;
2309
2310 // Only handle legal scalar cases. Anything else requires too much work.
2311 unsigned SizeInBits = Ty->getScalarSizeInBits();
2312 if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSizeInBits())
2313 return false;
2314
2315 // Bail if the value is never zero.
2316 Use &Op = CountZeros->getOperandUse(0);
2317 if (isKnownNonZero(Op, *DL))
2318 return false;
2319
2320 // The intrinsic will be sunk behind a compare against zero and branch.
2321 BasicBlock *StartBlock = CountZeros->getParent();
2322 BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
2323 if (IsHugeFunc)
2324 FreshBBs.insert(CallBlock);
2325
2326 // Create another block after the count zero intrinsic. A PHI will be added
2327 // in this block to select the result of the intrinsic or the bit-width
2328 // constant if the input to the intrinsic is zero.
2329 BasicBlock::iterator SplitPt = std::next(BasicBlock::iterator(CountZeros));
2330 // Any debug-info after CountZeros should not be included.
2331 SplitPt.setHeadBit(true);
2332 BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
2333 if (IsHugeFunc)
2334 FreshBBs.insert(EndBlock);
2335
2336 // Update the LoopInfo. The new blocks are in the same loop as the start
2337 // block.
2338 if (Loop *L = LI.getLoopFor(StartBlock)) {
2339 L->addBasicBlockToLoop(CallBlock, LI);
2340 L->addBasicBlockToLoop(EndBlock, LI);
2341 }
2342
2343 // Set up a builder to create a compare, conditional branch, and PHI.
2344 IRBuilder<> Builder(CountZeros->getContext());
2345 Builder.SetInsertPoint(StartBlock->getTerminator());
2346 Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
2347
2348 // Replace the unconditional branch that was created by the first split with
2349 // a compare against zero and a conditional branch.
2350 Value *Zero = Constant::getNullValue(Ty);
2351 // Avoid introducing branch on poison. This also replaces the ctz operand.
2353 Op = Builder.CreateFreeze(Op, Op->getName() + ".fr");
2354 Value *Cmp = Builder.CreateICmpEQ(Op, Zero, "cmpz");
2355 Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
2356 StartBlock->getTerminator()->eraseFromParent();
2357
2358 // Create a PHI in the end block to select either the output of the intrinsic
2359 // or the bit width of the operand.
2360 Builder.SetInsertPoint(EndBlock, EndBlock->begin());
2361 PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
2362 replaceAllUsesWith(CountZeros, PN, FreshBBs, IsHugeFunc);
2363 Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
2364 PN->addIncoming(BitWidth, StartBlock);
2365 PN->addIncoming(CountZeros, CallBlock);
2366
2367 // We are explicitly handling the zero case, so we can set the intrinsic's
2368 // undefined zero argument to 'true'. This will also prevent reprocessing the
2369 // intrinsic; we only despeculate when a zero input is defined.
2370 CountZeros->setArgOperand(1, Builder.getTrue());
2371 ModifiedDT = ModifyDT::ModifyBBDT;
2372 return true;
2373}
2374
2375bool CodeGenPrepare::optimizeCallInst(CallInst *CI, ModifyDT &ModifiedDT) {
2376 BasicBlock *BB = CI->getParent();
2377
2378 // Lower inline assembly if we can.
2379 // If we found an inline asm expession, and if the target knows how to
2380 // lower it to normal LLVM code, do so now.
2381 if (CI->isInlineAsm()) {
2382 if (TLI->ExpandInlineAsm(CI)) {
2383 // Avoid invalidating the iterator.
2384 CurInstIterator = BB->begin();
2385 // Avoid processing instructions out of order, which could cause
2386 // reuse before a value is defined.
2387 SunkAddrs.clear();
2388 return true;
2389 }
2390 // Sink address computing for memory operands into the block.
2391 if (optimizeInlineAsmInst(CI))
2392 return true;
2393 }
2394
2395 // Align the pointer arguments to this call if the target thinks it's a good
2396 // idea
2397 unsigned MinSize;
2398 Align PrefAlign;
2399 if (TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
2400 for (auto &Arg : CI->args()) {
2401 // We want to align both objects whose address is used directly and
2402 // objects whose address is used in casts and GEPs, though it only makes
2403 // sense for GEPs if the offset is a multiple of the desired alignment and
2404 // if size - offset meets the size threshold.
2405 if (!Arg->getType()->isPointerTy())
2406 continue;
2407 APInt Offset(DL->getIndexSizeInBits(
2408 cast<PointerType>(Arg->getType())->getAddressSpace()),
2409 0);
2411 uint64_t Offset2 = Offset.getLimitedValue();
2412 if (!isAligned(PrefAlign, Offset2))
2413 continue;
2414 AllocaInst *AI;
2415 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlign() < PrefAlign &&
2416 DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
2417 AI->setAlignment(PrefAlign);
2418 // Global variables can only be aligned if they are defined in this
2419 // object (i.e. they are uniquely initialized in this object), and
2420 // over-aligning global variables that have an explicit section is
2421 // forbidden.
2422 GlobalVariable *GV;
2423 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
2424 GV->getPointerAlignment(*DL) < PrefAlign &&
2425 DL->getTypeAllocSize(GV->getValueType()) >= MinSize + Offset2)
2426 GV->setAlignment(PrefAlign);
2427 }
2428 }
2429 // If this is a memcpy (or similar) then we may be able to improve the
2430 // alignment.
2431 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
2432 Align DestAlign = getKnownAlignment(MI->getDest(), *DL);
2433 MaybeAlign MIDestAlign = MI->getDestAlign();
2434 if (!MIDestAlign || DestAlign > *MIDestAlign)
2435 MI->setDestAlignment(DestAlign);
2436 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
2437 MaybeAlign MTISrcAlign = MTI->getSourceAlign();
2438 Align SrcAlign = getKnownAlignment(MTI->getSource(), *DL);
2439 if (!MTISrcAlign || SrcAlign > *MTISrcAlign)
2440 MTI->setSourceAlignment(SrcAlign);
2441 }
2442 }
2443
2444 // If we have a cold call site, try to sink addressing computation into the
2445 // cold block. This interacts with our handling for loads and stores to
2446 // ensure that we can fold all uses of a potential addressing computation
2447 // into their uses. TODO: generalize this to work over profiling data
2448 if (CI->hasFnAttr(Attribute::Cold) && !OptSize &&
2449 !llvm::shouldOptimizeForSize(BB, PSI, BFI.get()))
2450 for (auto &Arg : CI->args()) {
2451 if (!Arg->getType()->isPointerTy())
2452 continue;
2453 unsigned AS = Arg->getType()->getPointerAddressSpace();
2454 if (optimizeMemoryInst(CI, Arg, Arg->getType(), AS))
2455 return true;
2456 }
2457
2458 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
2459 if (II) {
2460 switch (II->getIntrinsicID()) {
2461 default:
2462 break;
2463 case Intrinsic::assume:
2464 llvm_unreachable("llvm.assume should have been removed already");
2465 case Intrinsic::allow_runtime_check:
2466 case Intrinsic::allow_ubsan_check:
2467 case Intrinsic::experimental_widenable_condition: {
2468 // Give up on future widening opportunities so that we can fold away dead
2469 // paths and merge blocks before going into block-local instruction
2470 // selection.
2471 if (II->use_empty()) {
2472 II->eraseFromParent();
2473 return true;
2474 }
2475 Constant *RetVal = ConstantInt::getTrue(II->getContext());
2476 resetIteratorIfInvalidatedWhileCalling(BB, [&]() {
2477 replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
2478 });
2479 return true;
2480 }
2481 case Intrinsic::objectsize:
2482 llvm_unreachable("llvm.objectsize.* should have been lowered already");
2483 case Intrinsic::is_constant:
2484 llvm_unreachable("llvm.is.constant.* should have been lowered already");
2485 case Intrinsic::aarch64_stlxr:
2486 case Intrinsic::aarch64_stxr: {
2487 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
2488 if (!ExtVal || !ExtVal->hasOneUse() ||
2489 ExtVal->getParent() == CI->getParent())
2490 return false;
2491 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
2492 ExtVal->moveBefore(CI);
2493 // Mark this instruction as "inserted by CGP", so that other
2494 // optimizations don't touch it.
2495 InsertedInsts.insert(ExtVal);
2496 return true;
2497 }
2498
2499 case Intrinsic::launder_invariant_group:
2500 case Intrinsic::strip_invariant_group: {
2501 Value *ArgVal = II->getArgOperand(0);
2502 auto it = LargeOffsetGEPMap.find(II);
2503 if (it != LargeOffsetGEPMap.end()) {
2504 // Merge entries in LargeOffsetGEPMap to reflect the RAUW.
2505 // Make sure not to have to deal with iterator invalidation
2506 // after possibly adding ArgVal to LargeOffsetGEPMap.
2507 auto GEPs = std::move(it->second);
2508 LargeOffsetGEPMap[ArgVal].append(GEPs.begin(), GEPs.end());
2509 LargeOffsetGEPMap.erase(II);
2510 }
2511
2512 replaceAllUsesWith(II, ArgVal, FreshBBs, IsHugeFunc);
2513 II->eraseFromParent();
2514 return true;
2515 }
2516 case Intrinsic::cttz:
2517 case Intrinsic::ctlz:
2518 // If counting zeros is expensive, try to avoid it.
2519 return despeculateCountZeros(II, *LI, TLI, DL, ModifiedDT, FreshBBs,
2520 IsHugeFunc);
2521 case Intrinsic::fshl:
2522 case Intrinsic::fshr:
2523 return optimizeFunnelShift(II);
2524 case Intrinsic::dbg_assign:
2525 case Intrinsic::dbg_value:
2526 return fixupDbgValue(II);
2527 case Intrinsic::masked_gather:
2528 return optimizeGatherScatterInst(II, II->getArgOperand(0));
2529 case Intrinsic::masked_scatter:
2530 return optimizeGatherScatterInst(II, II->getArgOperand(1));
2531 }
2532
2534 Type *AccessTy;
2535 if (TLI->getAddrModeArguments(II, PtrOps, AccessTy))
2536 while (!PtrOps.empty()) {
2537 Value *PtrVal = PtrOps.pop_back_val();
2538 unsigned AS = PtrVal->getType()->getPointerAddressSpace();
2539 if (optimizeMemoryInst(II, PtrVal, AccessTy, AS))
2540 return true;
2541 }
2542 }
2543
2544 // From here on out we're working with named functions.
2545 if (!CI->getCalledFunction())
2546 return false;
2547
2548 // Lower all default uses of _chk calls. This is very similar
2549 // to what InstCombineCalls does, but here we are only lowering calls
2550 // to fortified library functions (e.g. __memcpy_chk) that have the default
2551 // "don't know" as the objectsize. Anything else should be left alone.
2552 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
2553 IRBuilder<> Builder(CI);
2554 if (Value *V = Simplifier.optimizeCall(CI, Builder)) {
2555 replaceAllUsesWith(CI, V, FreshBBs, IsHugeFunc);
2556 CI->eraseFromParent();
2557 return true;
2558 }
2559
2560 return false;
2561}
2562
2564 const CallInst *CI) {
2565 assert(CI && CI->use_empty());
2566
2567 if (const auto *II = dyn_cast<IntrinsicInst>(CI))
2568 switch (II->getIntrinsicID()) {
2569 case Intrinsic::memset:
2570 case Intrinsic::memcpy:
2571 case Intrinsic::memmove:
2572 return true;
2573 default:
2574 return false;
2575 }
2576
2577 LibFunc LF;
2578 Function *Callee = CI->getCalledFunction();
2579 if (Callee && TLInfo && TLInfo->getLibFunc(*Callee, LF))
2580 switch (LF) {
2581 case LibFunc_strcpy:
2582 case LibFunc_strncpy:
2583 case LibFunc_strcat:
2584 case LibFunc_strncat:
2585 return true;
2586 default:
2587 return false;
2588 }
2589
2590 return false;
2591}
2592
2593/// Look for opportunities to duplicate return instructions to the predecessor
2594/// to enable tail call optimizations. The case it is currently looking for is
2595/// the following one. Known intrinsics or library function that may be tail
2596/// called are taken into account as well.
2597/// @code
2598/// bb0:
2599/// %tmp0 = tail call i32 @f0()
2600/// br label %return
2601/// bb1:
2602/// %tmp1 = tail call i32 @f1()
2603/// br label %return
2604/// bb2:
2605/// %tmp2 = tail call i32 @f2()
2606/// br label %return
2607/// return:
2608/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
2609/// ret i32 %retval
2610/// @endcode
2611///
2612/// =>
2613///
2614/// @code
2615/// bb0:
2616/// %tmp0 = tail call i32 @f0()
2617/// ret i32 %tmp0
2618/// bb1:
2619/// %tmp1 = tail call i32 @f1()
2620/// ret i32 %tmp1
2621/// bb2:
2622/// %tmp2 = tail call i32 @f2()
2623/// ret i32 %tmp2
2624/// @endcode
2625bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB,
2626 ModifyDT &ModifiedDT) {
2627 if (!BB->getTerminator())
2628 return false;
2629
2630 ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator());
2631 if (!RetI)
2632 return false;
2633
2634 assert(LI->getLoopFor(BB) == nullptr && "A return block cannot be in a loop");
2635
2636 PHINode *PN = nullptr;
2637 ExtractValueInst *EVI = nullptr;
2638 BitCastInst *BCI = nullptr;
2639 Value *V = RetI->getReturnValue();
2640 if (V) {
2641 BCI = dyn_cast<BitCastInst>(V);
2642 if (BCI)
2643 V = BCI->getOperand(0);
2644
2645 EVI = dyn_cast<ExtractValueInst>(V);
2646 if (EVI) {
2647 V = EVI->getOperand(0);
2648 if (!llvm::all_of(EVI->indices(), [](unsigned idx) { return idx == 0; }))
2649 return false;
2650 }
2651
2652 PN = dyn_cast<PHINode>(V);
2653 }
2654
2655 if (PN && PN->getParent() != BB)
2656 return false;
2657
2658 auto isLifetimeEndOrBitCastFor = [](const Instruction *Inst) {
2659 const BitCastInst *BC = dyn_cast<BitCastInst>(Inst);
2660 if (BC && BC->hasOneUse())
2661 Inst = BC->user_back();
2662
2663 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst))
2664 return II->getIntrinsicID() == Intrinsic::lifetime_end;
2665 return false;
2666 };
2667
2668 // Make sure there are no instructions between the first instruction
2669 // and return.
2670 const Instruction *BI = BB->getFirstNonPHI();
2671 // Skip over debug and the bitcast.
2672 while (isa<DbgInfoIntrinsic>(BI) || BI == BCI || BI == EVI ||
2673 isa<PseudoProbeInst>(BI) || isLifetimeEndOrBitCastFor(BI))
2674 BI = BI->getNextNode();
2675 if (BI != RetI)
2676 return false;
2677
2678 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
2679 /// call.
2680 const Function *F = BB->getParent();
2681 SmallVector<BasicBlock *, 4> TailCallBBs;
2682 if (PN) {
2683 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
2684 // Look through bitcasts.
2685 Value *IncomingVal = PN->getIncomingValue(I)->stripPointerCasts();
2686 CallInst *CI = dyn_cast<CallInst>(IncomingVal);
2687 BasicBlock *PredBB = PN->getIncomingBlock(I);
2688 // Make sure the phi value is indeed produced by the tail call.
2689 if (CI && CI->hasOneUse() && CI->getParent() == PredBB &&
2690 TLI->mayBeEmittedAsTailCall(CI) &&
2691 attributesPermitTailCall(F, CI, RetI, *TLI)) {
2692 TailCallBBs.push_back(PredBB);
2693 } else {
2694 // Consider the cases in which the phi value is indirectly produced by
2695 // the tail call, for example when encountering memset(), memmove(),
2696 // strcpy(), whose return value may have been optimized out. In such
2697 // cases, the value needs to be the first function argument.
2698 //
2699 // bb0:
2700 // tail call void @llvm.memset.p0.i64(ptr %0, i8 0, i64 %1)
2701 // br label %return
2702 // return:
2703 // %phi = phi ptr [ %0, %bb0 ], [ %2, %entry ]
2704 if (PredBB && PredBB->getSingleSuccessor() == BB)
2705 CI = dyn_cast_or_null<CallInst>(
2706 PredBB->getTerminator()->getPrevNonDebugInstruction(true));
2707
2708 if (CI && CI->use_empty() &&
2709 isIntrinsicOrLFToBeTailCalled(TLInfo, CI) &&
2710 IncomingVal == CI->getArgOperand(0) &&
2711 TLI->mayBeEmittedAsTailCall(CI) &&
2712 attributesPermitTailCall(F, CI, RetI, *TLI))
2713 TailCallBBs.push_back(PredBB);
2714 }
2715 }
2716 } else {
2718 for (BasicBlock *Pred : predecessors(BB)) {
2719 if (!VisitedBBs.insert(Pred).second)
2720 continue;
2721 if (Instruction *I = Pred->rbegin()->getPrevNonDebugInstruction(true)) {
2722 CallInst *CI = dyn_cast<CallInst>(I);
2723 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI) &&
2724 attributesPermitTailCall(F, CI, RetI, *TLI)) {
2725 // Either we return void or the return value must be the first
2726 // argument of a known intrinsic or library function.
2727 if (!V || isa<UndefValue>(V) ||
2728 (isIntrinsicOrLFToBeTailCalled(TLInfo, CI) &&
2729 V == CI->getArgOperand(0))) {
2730 TailCallBBs.push_back(Pred);
2731 }
2732 }
2733 }
2734 }
2735 }
2736
2737 bool Changed = false;
2738 for (auto const &TailCallBB : TailCallBBs) {
2739 // Make sure the call instruction is followed by an unconditional branch to
2740 // the return block.
2741 BranchInst *BI = dyn_cast<BranchInst>(TailCallBB->getTerminator());
2742 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
2743 continue;
2744
2745 // Duplicate the return into TailCallBB.
2746 (void)FoldReturnIntoUncondBranch(RetI, BB, TailCallBB);
2748 BFI->getBlockFreq(BB) >= BFI->getBlockFreq(TailCallBB));
2749 BFI->setBlockFreq(BB,
2750 (BFI->getBlockFreq(BB) - BFI->getBlockFreq(TailCallBB)));
2751 ModifiedDT = ModifyDT::ModifyBBDT;
2752 Changed = true;
2753 ++NumRetsDup;
2754 }
2755
2756 // If we eliminated all predecessors of the block, delete the block now.
2757 if (Changed && !BB->hasAddressTaken() && pred_empty(BB))
2758 BB->eraseFromParent();
2759
2760 return Changed;
2761}
2762
2763//===----------------------------------------------------------------------===//
2764// Memory Optimization
2765//===----------------------------------------------------------------------===//
2766
2767namespace {
2768
2769/// This is an extended version of TargetLowering::AddrMode
2770/// which holds actual Value*'s for register values.
2771struct ExtAddrMode : public TargetLowering::AddrMode {
2772 Value *BaseReg = nullptr;
2773 Value *ScaledReg = nullptr;
2774 Value *OriginalValue = nullptr;
2775 bool InBounds = true;
2776
2777 enum FieldName {
2778 NoField = 0x00,
2779 BaseRegField = 0x01,
2780 BaseGVField = 0x02,
2781 BaseOffsField = 0x04,
2782 ScaledRegField = 0x08,
2783 ScaleField = 0x10,
2784 MultipleFields = 0xff
2785 };
2786
2787 ExtAddrMode() = default;
2788
2789 void print(raw_ostream &OS) const;
2790 void dump() const;
2791
2792 FieldName compare(const ExtAddrMode &other) {
2793 // First check that the types are the same on each field, as differing types
2794 // is something we can't cope with later on.
2795 if (BaseReg && other.BaseReg &&
2796 BaseReg->getType() != other.BaseReg->getType())
2797 return MultipleFields;
2798 if (BaseGV && other.BaseGV && BaseGV->getType() != other.BaseGV->getType())
2799 return MultipleFields;
2800 if (ScaledReg && other.ScaledReg &&
2801 ScaledReg->getType() != other.ScaledReg->getType())
2802 return MultipleFields;
2803
2804 // Conservatively reject 'inbounds' mismatches.
2805 if (InBounds != other.InBounds)
2806 return MultipleFields;
2807
2808 // Check each field to see if it differs.
2809 unsigned Result = NoField;
2810 if (BaseReg != other.BaseReg)
2811 Result |= BaseRegField;
2812 if (BaseGV != other.BaseGV)
2813 Result |= BaseGVField;
2814 if (BaseOffs != other.BaseOffs)
2815 Result |= BaseOffsField;
2816 if (ScaledReg != other.ScaledReg)
2817 Result |= ScaledRegField;
2818 // Don't count 0 as being a different scale, because that actually means
2819 // unscaled (which will already be counted by having no ScaledReg).
2820 if (Scale && other.Scale && Scale != other.Scale)
2821 Result |= ScaleField;
2822
2823 if (llvm::popcount(Result) > 1)
2824 return MultipleFields;
2825 else
2826 return static_cast<FieldName>(Result);
2827 }
2828
2829 // An AddrMode is trivial if it involves no calculation i.e. it is just a base
2830 // with no offset.
2831 bool isTrivial() {
2832 // An AddrMode is (BaseGV + BaseReg + BaseOffs + ScaleReg * Scale) so it is
2833 // trivial if at most one of these terms is nonzero, except that BaseGV and
2834 // BaseReg both being zero actually means a null pointer value, which we
2835 // consider to be 'non-zero' here.
2836 return !BaseOffs && !Scale && !(BaseGV && BaseReg);
2837 }
2838
2839 Value *GetFieldAsValue(FieldName Field, Type *IntPtrTy) {
2840 switch (Field) {
2841 default:
2842 return nullptr;
2843 case BaseRegField:
2844 return BaseReg;
2845 case BaseGVField:
2846 return BaseGV;
2847 case ScaledRegField:
2848 return ScaledReg;
2849 case BaseOffsField:
2850 return ConstantInt::get(IntPtrTy, BaseOffs);
2851 }
2852 }
2853
2854 void SetCombinedField(FieldName Field, Value *V,
2855 const SmallVectorImpl<ExtAddrMode> &AddrModes) {
2856 switch (Field) {
2857 default:
2858 llvm_unreachable("Unhandled fields are expected to be rejected earlier");
2859 break;
2860 case ExtAddrMode::BaseRegField:
2861 BaseReg = V;
2862 break;
2863 case ExtAddrMode::BaseGVField:
2864 // A combined BaseGV is an Instruction, not a GlobalValue, so it goes
2865 // in the BaseReg field.
2866 assert(BaseReg == nullptr);
2867 BaseReg = V;
2868 BaseGV = nullptr;
2869 break;
2870 case ExtAddrMode::ScaledRegField:
2871 ScaledReg = V;
2872 // If we have a mix of scaled and unscaled addrmodes then we want scale
2873 // to be the scale and not zero.
2874 if (!Scale)
2875 for (const ExtAddrMode &AM : AddrModes)
2876 if (AM.Scale) {
2877 Scale = AM.Scale;
2878 break;
2879 }
2880 break;
2881 case ExtAddrMode::BaseOffsField:
2882 // The offset is no longer a constant, so it goes in ScaledReg with a
2883 // scale of 1.
2884 assert(ScaledReg == nullptr);
2885 ScaledReg = V;
2886 Scale = 1;
2887 BaseOffs = 0;
2888 break;
2889 }
2890 }
2891};
2892
2893#ifndef NDEBUG
2894static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
2895 AM.print(OS);
2896 return OS;
2897}
2898#endif
2899
2900#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2901void ExtAddrMode::print(raw_ostream &OS) const {
2902 bool NeedPlus = false;
2903 OS << "[";
2904 if (InBounds)
2905 OS << "inbounds ";
2906 if (BaseGV) {
2907 OS << "GV:";
2908 BaseGV->printAsOperand(OS, /*PrintType=*/false);
2909 NeedPlus = true;
2910 }
2911
2912 if (BaseOffs) {
2913 OS << (NeedPlus ? " + " : "") << BaseOffs;
2914 NeedPlus = true;
2915 }
2916
2917 if (BaseReg) {
2918 OS << (NeedPlus ? " + " : "") << "Base:";
2919 BaseReg->printAsOperand(OS, /*PrintType=*/false);
2920 NeedPlus = true;
2921 }
2922 if (Scale) {
2923 OS << (NeedPlus ? " + " : "") << Scale << "*";
2924 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
2925 }
2926
2927 OS << ']';
2928}
2929
2930LLVM_DUMP_METHOD void ExtAddrMode::dump() const {
2931 print(dbgs());
2932 dbgs() << '\n';
2933}
2934#endif
2935
2936} // end anonymous namespace
2937
2938namespace {
2939
2940/// This class provides transaction based operation on the IR.
2941/// Every change made through this class is recorded in the internal state and
2942/// can be undone (rollback) until commit is called.
2943/// CGP does not check if instructions could be speculatively executed when
2944/// moved. Preserving the original location would pessimize the debugging
2945/// experience, as well as negatively impact the quality of sample PGO.
2946class TypePromotionTransaction {
2947 /// This represents the common interface of the individual transaction.
2948 /// Each class implements the logic for doing one specific modification on
2949 /// the IR via the TypePromotionTransaction.
2950 class TypePromotionAction {
2951 protected:
2952 /// The Instruction modified.
2953 Instruction *Inst;
2954
2955 public:
2956 /// Constructor of the action.
2957 /// The constructor performs the related action on the IR.
2958 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
2959
2960 virtual ~TypePromotionAction() = default;
2961
2962 /// Undo the modification done by this action.
2963 /// When this method is called, the IR must be in the same state as it was
2964 /// before this action was applied.
2965 /// \pre Undoing the action works if and only if the IR is in the exact same
2966 /// state as it was directly after this action was applied.
2967 virtual void undo() = 0;
2968
2969 /// Advocate every change made by this action.
2970 /// When the results on the IR of the action are to be kept, it is important
2971 /// to call this function, otherwise hidden information may be kept forever.
2972 virtual void commit() {
2973 // Nothing to be done, this action is not doing anything.
2974 }
2975 };
2976
2977 /// Utility to remember the position of an instruction.
2978 class InsertionHandler {
2979 /// Position of an instruction.
2980 /// Either an instruction:
2981 /// - Is the first in a basic block: BB is used.
2982 /// - Has a previous instruction: PrevInst is used.
2983 union {
2984 Instruction *PrevInst;
2985 BasicBlock *BB;
2986 } Point;
2987 std::optional<DbgRecord::self_iterator> BeforeDbgRecord = std::nullopt;
2988
2989 /// Remember whether or not the instruction had a previous instruction.
2990 bool HasPrevInstruction;
2991
2992 public:
2993 /// Record the position of \p Inst.
2994 InsertionHandler(Instruction *Inst) {
2995 HasPrevInstruction = (Inst != &*(Inst->getParent()->begin()));
2996 BasicBlock *BB = Inst->getParent();
2997
2998 // Record where we would have to re-insert the instruction in the sequence
2999 // of DbgRecords, if we ended up reinserting.
3000 if (BB->IsNewDbgInfoFormat)
3001 BeforeDbgRecord = Inst->getDbgReinsertionPosition();
3002
3003 if (HasPrevInstruction) {
3004 Point.PrevInst = &*std::prev(Inst->getIterator());
3005 } else {
3006 Point.BB = BB;
3007 }
3008 }
3009
3010 /// Insert \p Inst at the recorded position.
3011 void insert(Instruction *Inst) {
3012 if (HasPrevInstruction) {
3013 if (Inst->getParent())
3014 Inst->removeFromParent();
3015 Inst->insertAfter(&*Point.PrevInst);
3016 } else {
3017 BasicBlock::iterator Position = Point.BB->getFirstInsertionPt();
3018 if (Inst->getParent())
3019 Inst->moveBefore(*Point.BB, Position);
3020 else
3021 Inst->insertBefore(*Point.BB, Position);
3022 }
3023
3024 Inst->getParent()->reinsertInstInDbgRecords(Inst, BeforeDbgRecord);
3025 }
3026 };
3027
3028 /// Move an instruction before another.
3029 class InstructionMoveBefore : public TypePromotionAction {
3030 /// Original position of the instruction.
3031 InsertionHandler Position;
3032
3033 public:
3034 /// Move \p Inst before \p Before.
3035 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
3036 : TypePromotionAction(Inst), Position(Inst) {
3037 LLVM_DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before
3038 << "\n");
3039 Inst->moveBefore(Before);
3040 }
3041
3042 /// Move the instruction back to its original position.
3043 void undo() override {
3044 LLVM_DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
3045 Position.insert(Inst);
3046 }
3047 };
3048
3049 /// Set the operand of an instruction with a new value.
3050 class OperandSetter : public TypePromotionAction {
3051 /// Original operand of the instruction.
3052 Value *Origin;
3053
3054 /// Index of the modified instruction.
3055 unsigned Idx;
3056
3057 public:
3058 /// Set \p Idx operand of \p Inst with \p NewVal.
3059 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
3060 : TypePromotionAction(Inst), Idx(Idx) {
3061 LLVM_DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
3062 << "for:" << *Inst << "\n"
3063 << "with:" << *NewVal << "\n");
3064 Origin = Inst->getOperand(Idx);
3065 Inst->setOperand(Idx, NewVal);
3066 }
3067
3068 /// Restore the original value of the instruction.
3069 void undo() override {
3070 LLVM_DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
3071 << "for: " << *Inst << "\n"
3072 << "with: " << *Origin << "\n");
3073 Inst->setOperand(Idx, Origin);
3074 }
3075 };
3076
3077 /// Hide the operands of an instruction.
3078 /// Do as if this instruction was not using any of its operands.
3079 class OperandsHider : public TypePromotionAction {
3080 /// The list of original operands.
3081 SmallVector<Value *, 4> OriginalValues;
3082
3083 public:
3084 /// Remove \p Inst from the uses of the operands of \p Inst.
3085 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
3086 LLVM_DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
3087 unsigned NumOpnds = Inst->getNumOperands();
3088 OriginalValues.reserve(NumOpnds);
3089 for (unsigned It = 0; It < NumOpnds; ++It) {
3090 // Save the current operand.
3091 Value *Val = Inst->getOperand(It);
3092 OriginalValues.push_back(Val);
3093 // Set a dummy one.
3094 // We could use OperandSetter here, but that would imply an overhead
3095 // that we are not willing to pay.
3096 Inst->setOperand(It, UndefValue::get(Val->getType()));
3097 }
3098 }
3099
3100 /// Restore the original list of uses.
3101 void undo() override {
3102 LLVM_DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
3103 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
3104 Inst->setOperand(It, OriginalValues[It]);
3105 }
3106 };
3107
3108 /// Build a truncate instruction.
3109 class TruncBuilder : public TypePromotionAction {
3110 Value *Val;
3111
3112 public:
3113 /// Build a truncate instruction of \p Opnd producing a \p Ty
3114 /// result.
3115 /// trunc Opnd to Ty.
3116 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
3117 IRBuilder<> Builder(Opnd);
3118 Builder.SetCurrentDebugLocation(DebugLoc());
3119 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
3120 LLVM_DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
3121 }
3122
3123 /// Get the built value.
3124 Value *getBuiltValue() { return Val; }
3125
3126 /// Remove the built instruction.
3127 void undo() override {
3128 LLVM_DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
3129 if (Instruction *IVal = dyn_cast<Instruction>(Val))
3130 IVal->eraseFromParent();
3131 }
3132 };
3133
3134 /// Build a sign extension instruction.
3135 class SExtBuilder : public TypePromotionAction {
3136 Value *Val;
3137
3138 public:
3139 /// Build a sign extension instruction of \p Opnd producing a \p Ty
3140 /// result.
3141 /// sext Opnd to Ty.
3142 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
3143 : TypePromotionAction(InsertPt) {
3144 IRBuilder<> Builder(InsertPt);
3145 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
3146 LLVM_DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
3147 }
3148
3149 /// Get the built value.
3150 Value *getBuiltValue() { return Val; }
3151
3152 /// Remove the built instruction.
3153 void undo() override {
3154 LLVM_DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
3155 if (Instruction *IVal = dyn_cast<Instruction>(Val))
3156 IVal->eraseFromParent();
3157 }
3158 };
3159
3160 /// Build a zero extension instruction.
3161 class ZExtBuilder : public TypePromotionAction {
3162 Value *Val;
3163
3164 public:
3165 /// Build a zero extension instruction of \p Opnd producing a \p Ty
3166 /// result.
3167 /// zext Opnd to Ty.
3168 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
3169 : TypePromotionAction(InsertPt) {
3170 IRBuilder<> Builder(InsertPt);
3171 Builder.SetCurrentDebugLocation(DebugLoc());
3172 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
3173 LLVM_DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
3174 }
3175
3176 /// Get the built value.
3177 Value *getBuiltValue() { return Val; }
3178
3179 /// Remove the built instruction.
3180 void undo() override {
3181 LLVM_DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
3182 if (Instruction *IVal = dyn_cast<Instruction>(Val))
3183 IVal->eraseFromParent();
3184 }
3185 };
3186
3187 /// Mutate an instruction to another type.
3188 class TypeMutator : public TypePromotionAction {
3189 /// Record the original type.
3190 Type *OrigTy;
3191
3192 public:
3193 /// Mutate the type of \p Inst into \p NewTy.
3194 TypeMutator(Instruction *Inst, Type *NewTy)
3195 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
3196 LLVM_DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
3197 << "\n");
3198 Inst->mutateType(NewTy);
3199 }
3200
3201 /// Mutate the instruction back to its original type.
3202 void undo() override {
3203 LLVM_DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
3204 << "\n");
3205 Inst->mutateType(OrigTy);
3206 }
3207 };
3208
3209 /// Replace the uses of an instruction by another instruction.
3210 class UsesReplacer : public TypePromotionAction {
3211 /// Helper structure to keep track of the replaced uses.
3212 struct InstructionAndIdx {
3213 /// The instruction using the instruction.
3214 Instruction *Inst;
3215
3216 /// The index where this instruction is used for Inst.
3217 unsigned Idx;
3218
3219 InstructionAndIdx(Instruction *Inst, unsigned Idx)
3220 : Inst(Inst), Idx(Idx) {}
3221 };
3222
3223 /// Keep track of the original uses (pair Instruction, Index).
3225 /// Keep track of the debug users.
3227 /// And non-instruction debug-users too.
3228 SmallVector<DbgVariableRecord *, 1> DbgVariableRecords;
3229
3230 /// Keep track of the new value so that we can undo it by replacing
3231 /// instances of the new value with the original value.
3232 Value *New;
3233
3235
3236 public:
3237 /// Replace all the use of \p Inst by \p New.
3238 UsesReplacer(Instruction *Inst, Value *New)
3239 : TypePromotionAction(Inst), New(New) {
3240 LLVM_DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
3241 << "\n");
3242 // Record the original uses.
3243 for (Use &U : Inst->uses()) {
3244 Instruction *UserI = cast<Instruction>(U.getUser());
3245 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
3246 }
3247 // Record the debug uses separately. They are not in the instruction's
3248 // use list, but they are replaced by RAUW.
3249 findDbgValues(DbgValues, Inst, &DbgVariableRecords);
3250
3251 // Now, we can replace the uses.
3252 Inst->replaceAllUsesWith(New);
3253 }
3254
3255 /// Reassign the original uses of Inst to Inst.
3256 void undo() override {
3257 LLVM_DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
3258 for (InstructionAndIdx &Use : OriginalUses)
3259 Use.Inst->setOperand(Use.Idx, Inst);
3260 // RAUW has replaced all original uses with references to the new value,
3261 // including the debug uses. Since we are undoing the replacements,
3262 // the original debug uses must also be reinstated to maintain the
3263 // correctness and utility of debug value instructions.
3264 for (auto *DVI : DbgValues)
3265 DVI->replaceVariableLocationOp(New, Inst);
3266 // Similar story with DbgVariableRecords, the non-instruction
3267 // representation of dbg.values.
3268 for (DbgVariableRecord *DVR : DbgVariableRecords)
3269 DVR->replaceVariableLocationOp(New, Inst);
3270 }
3271 };
3272
3273 /// Remove an instruction from the IR.
3274 class InstructionRemover : public TypePromotionAction {
3275 /// Original position of the instruction.
3276 InsertionHandler Inserter;
3277
3278 /// Helper structure to hide all the link to the instruction. In other
3279 /// words, this helps to do as if the instruction was removed.
3280 OperandsHider Hider;
3281
3282 /// Keep track of the uses replaced, if any.
3283 UsesReplacer *Replacer = nullptr;
3284
3285 /// Keep track of instructions removed.
3286 SetOfInstrs &RemovedInsts;
3287
3288 public:
3289 /// Remove all reference of \p Inst and optionally replace all its
3290 /// uses with New.
3291 /// \p RemovedInsts Keep track of the instructions removed by this Action.
3292 /// \pre If !Inst->use_empty(), then New != nullptr
3293 InstructionRemover(Instruction *Inst, SetOfInstrs &RemovedInsts,
3294 Value *New = nullptr)
3295 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
3296 RemovedInsts(RemovedInsts) {
3297 if (New)
3298 Replacer = new UsesReplacer(Inst, New);
3299 LLVM_DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
3300 RemovedInsts.insert(Inst);
3301 /// The instructions removed here will be freed after completing
3302 /// optimizeBlock() for all blocks as we need to keep track of the
3303 /// removed instructions during promotion.
3304 Inst->removeFromParent();
3305 }
3306
3307 ~InstructionRemover() override { delete Replacer; }
3308
3309 InstructionRemover &operator=(const InstructionRemover &other) = delete;
3310 InstructionRemover(const InstructionRemover &other) = delete;
3311
3312 /// Resurrect the instruction and reassign it to the proper uses if
3313 /// new value was provided when build this action.
3314 void undo() override {
3315 LLVM_DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
3316 Inserter.insert(Inst);
3317 if (Replacer)
3318 Replacer->undo();
3319 Hider.undo();
3320 RemovedInsts.erase(Inst);
3321 }
3322 };
3323
3324public:
3325 /// Restoration point.
3326 /// The restoration point is a pointer to an action instead of an iterator
3327 /// because the iterator may be invalidated but not the pointer.
3328 using ConstRestorationPt = const TypePromotionAction *;
3329
3330 TypePromotionTransaction(SetOfInstrs &RemovedInsts)
3331 : RemovedInsts(RemovedInsts) {}
3332
3333 /// Advocate every changes made in that transaction. Return true if any change
3334 /// happen.
3335 bool commit();
3336
3337 /// Undo all the changes made after the given point.
3338 void rollback(ConstRestorationPt Point);
3339
3340 /// Get the current restoration point.
3341 ConstRestorationPt getRestorationPoint() const;
3342
3343 /// \name API for IR modification with state keeping to support rollback.
3344 /// @{
3345 /// Same as Instruction::setOperand.
3346 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
3347
3348 /// Same as Instruction::eraseFromParent.
3349 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
3350
3351 /// Same as Value::replaceAllUsesWith.
3352 void replaceAllUsesWith(Instruction *Inst, Value *New);
3353
3354 /// Same as Value::mutateType.
3355 void mutateType(Instruction *Inst, Type *NewTy);
3356
3357 /// Same as IRBuilder::createTrunc.
3358 Value *createTrunc(Instruction *Opnd, Type *Ty);
3359
3360 /// Same as IRBuilder::createSExt.
3361 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
3362
3363 /// Same as IRBuilder::createZExt.
3364 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
3365
3366private:
3367 /// The ordered list of actions made so far.
3369
3370 using CommitPt =
3372
3373 SetOfInstrs &RemovedInsts;
3374};
3375
3376} // end anonymous namespace
3377
3378void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
3379 Value *NewVal) {
3380 Actions.push_back(std::make_unique<TypePromotionTransaction::OperandSetter>(
3381 Inst, Idx, NewVal));
3382}
3383
3384void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
3385 Value *NewVal) {
3386 Actions.push_back(
3387 std::make_unique<TypePromotionTransaction::InstructionRemover>(
3388 Inst, RemovedInsts, NewVal));
3389}
3390
3391void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
3392 Value *New) {
3393 Actions.push_back(
3394 std::make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
3395}
3396
3397void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
3398 Actions.push_back(
3399 std::make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
3400}
3401
3402Value *TypePromotionTransaction::createTrunc(Instruction *Opnd, Type *Ty) {
3403 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
3404 Value *Val = Ptr->getBuiltValue();
3405 Actions.push_back(std::move(Ptr));
3406 return Val;
3407}
3408
3409Value *TypePromotionTransaction::createSExt(Instruction *Inst, Value *Opnd,
3410 Type *Ty) {
3411 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
3412 Value *Val = Ptr->getBuiltValue();
3413 Actions.push_back(std::move(Ptr));
3414 return Val;
3415}
3416
3417Value *TypePromotionTransaction::createZExt(Instruction *Inst, Value *Opnd,
3418 Type *Ty) {
3419 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
3420 Value *Val = Ptr->getBuiltValue();
3421 Actions.push_back(std::move(Ptr));
3422 return Val;
3423}
3424
3425TypePromotionTransaction::ConstRestorationPt
3426TypePromotionTransaction::getRestorationPoint() const {
3427 return !Actions.empty() ? Actions.back().get() : nullptr;
3428}
3429
3430bool TypePromotionTransaction::commit() {
3431 for (std::unique_ptr<TypePromotionAction> &Action : Actions)
3432 Action->commit();
3433 bool Modified = !Actions.empty();
3434 Actions.clear();
3435 return Modified;
3436}
3437
3438void TypePromotionTransaction::rollback(
3439 TypePromotionTransaction::ConstRestorationPt Point) {
3440 while (!Actions.empty() && Point != Actions.back().get()) {
3441 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
3442 Curr->undo();
3443 }
3444}
3445
3446namespace {
3447
3448/// A helper class for matching addressing modes.
3449///
3450/// This encapsulates the logic for matching the target-legal addressing modes.
3451class AddressingModeMatcher {
3452 SmallVectorImpl<Instruction *> &AddrModeInsts;
3453 const TargetLowering &TLI;
3454 const TargetRegisterInfo &TRI;
3455 const DataLayout &DL;
3456 const LoopInfo &LI;
3457 const std::function<const DominatorTree &()> getDTFn;
3458
3459 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
3460 /// the memory instruction that we're computing this address for.
3461 Type *AccessTy;
3462 unsigned AddrSpace;
3463 Instruction *MemoryInst;
3464
3465 /// This is the addressing mode that we're building up. This is
3466 /// part of the return value of this addressing mode matching stuff.
3468
3469 /// The instructions inserted by other CodeGenPrepare optimizations.
3470 const SetOfInstrs &InsertedInsts;
3471
3472 /// A map from the instructions to their type before promotion.
3473 InstrToOrigTy &PromotedInsts;
3474
3475 /// The ongoing transaction where every action should be registered.
3476 TypePromotionTransaction &TPT;
3477
3478 // A GEP which has too large offset to be folded into the addressing mode.
3479 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP;
3480
3481 /// This is set to true when we should not do profitability checks.
3482 /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
3483 bool IgnoreProfitability;
3484
3485 /// True if we are optimizing for size.
3486 bool OptSize = false;
3487
3488 ProfileSummaryInfo *PSI;
3490
3491 AddressingModeMatcher(
3493 const TargetRegisterInfo &TRI, const LoopInfo &LI,
3494 const std::function<const DominatorTree &()> getDTFn, Type *AT,
3495 unsigned AS, Instruction *MI, ExtAddrMode &AM,
3496 const SetOfInstrs &InsertedInsts, InstrToOrigTy &PromotedInsts,
3497 TypePromotionTransaction &TPT,
3498 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP,
3499 bool OptSize, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI)
3500 : AddrModeInsts(AMI), TLI(TLI), TRI(TRI),
3501 DL(MI->getModule()->getDataLayout()), LI(LI), getDTFn(getDTFn),
3502 AccessTy(AT), AddrSpace(AS), MemoryInst(MI), AddrMode(AM),
3503 InsertedInsts(InsertedInsts), PromotedInsts(PromotedInsts), TPT(TPT),
3504 LargeOffsetGEP(LargeOffsetGEP), OptSize(OptSize), PSI(PSI), BFI(BFI) {
3505 IgnoreProfitability = false;
3506 }
3507
3508public:
3509 /// Find the maximal addressing mode that a load/store of V can fold,
3510 /// give an access type of AccessTy. This returns a list of involved
3511 /// instructions in AddrModeInsts.
3512 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
3513 /// optimizations.
3514 /// \p PromotedInsts maps the instructions to their type before promotion.
3515 /// \p The ongoing transaction where every action should be registered.
3516 static ExtAddrMode
3517 Match(Value *V, Type *AccessTy, unsigned AS, Instruction *MemoryInst,
3518 SmallVectorImpl<Instruction *> &AddrModeInsts,
3519 const TargetLowering &TLI, const LoopInfo &LI,
3520 const std::function<const DominatorTree &()> getDTFn,
3521 const TargetRegisterInfo &TRI, const SetOfInstrs &InsertedInsts,
3522 InstrToOrigTy &PromotedInsts, TypePromotionTransaction &TPT,
3523 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP,
3524 bool OptSize, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI) {
3526
3527 bool Success = AddressingModeMatcher(AddrModeInsts, TLI, TRI, LI, getDTFn,
3528 AccessTy, AS, MemoryInst, Result,
3529 InsertedInsts, PromotedInsts, TPT,
3530 LargeOffsetGEP, OptSize, PSI, BFI)
3531 .matchAddr(V, 0);
3532 (void)Success;
3533 assert(Success && "Couldn't select *anything*?");
3534 return Result;
3535 }
3536
3537private:
3538 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
3539 bool matchAddr(Value *Addr, unsigned Depth);
3540 bool matchOperationAddr(User *AddrInst, unsigned Opcode, unsigned Depth,
3541 bool *MovedAway = nullptr);
3542 bool isProfitableToFoldIntoAddressingMode(Instruction *I,
3543 ExtAddrMode &AMBefore,
3544 ExtAddrMode &AMAfter);
3545 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
3546 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
3547 Value *PromotedOperand) const;
3548};
3549
3550class PhiNodeSet;
3551
3552/// An iterator for PhiNodeSet.
3553class PhiNodeSetIterator {
3554 PhiNodeSet *const Set;
3555 size_t CurrentIndex = 0;
3556
3557public:
3558 /// The constructor. Start should point to either a valid element, or be equal
3559 /// to the size of the underlying SmallVector of the PhiNodeSet.
3560 PhiNodeSetIterator(PhiNodeSet *const Set, size_t Start);
3561 PHINode *operator*() const;
3562 PhiNodeSetIterator &operator++();
3563 bool operator==(const PhiNodeSetIterator &RHS) const;
3564 bool operator!=(const PhiNodeSetIterator &RHS) const;
3565};
3566
3567/// Keeps a set of PHINodes.
3568///
3569/// This is a minimal set implementation for a specific use case:
3570/// It is very fast when there are very few elements, but also provides good
3571/// performance when there are many. It is similar to SmallPtrSet, but also
3572/// provides iteration by insertion order, which is deterministic and stable
3573/// across runs. It is also similar to SmallSetVector, but provides removing
3574/// elements in O(1) time. This is achieved by not actually removing the element
3575/// from the underlying vector, so comes at the cost of using more memory, but
3576/// that is fine, since PhiNodeSets are used as short lived objects.
3577class PhiNodeSet {
3578 friend class PhiNodeSetIterator;
3579
3581 using iterator = PhiNodeSetIterator;
3582
3583 /// Keeps the elements in the order of their insertion in the underlying
3584 /// vector. To achieve constant time removal, it never deletes any element.
3586
3587 /// Keeps the elements in the underlying set implementation. This (and not the
3588 /// NodeList defined above) is the source of truth on whether an element
3589 /// is actually in the collection.
3590 MapType NodeMap;
3591
3592 /// Points to the first valid (not deleted) element when the set is not empty
3593 /// and the value is not zero. Equals to the size of the underlying vector
3594 /// when the set is empty. When the value is 0, as in the beginning, the
3595 /// first element may or may not be valid.
3596 size_t FirstValidElement = 0;
3597
3598public:
3599 /// Inserts a new element to the collection.
3600 /// \returns true if the element is actually added, i.e. was not in the
3601 /// collection before the operation.
3602 bool insert(PHINode *Ptr) {
3603 if (NodeMap.insert(std::make_pair(Ptr, NodeList.size())).second) {
3604 NodeList.push_back(Ptr);
3605 return true;
3606 }
3607 return false;
3608 }
3609
3610 /// Removes the element from the collection.
3611 /// \returns whether the element is actually removed, i.e. was in the
3612 /// collection before the operation.
3613 bool erase(PHINode *Ptr) {
3614 if (NodeMap.erase(Ptr)) {
3615 SkipRemovedElements(FirstValidElement);
3616 return true;
3617 }
3618 return false;
3619 }
3620
3621 /// Removes all elements and clears the collection.
3622 void clear() {
3623 NodeMap.clear();
3624 NodeList.clear();
3625 FirstValidElement = 0;
3626 }
3627
3628 /// \returns an iterator that will iterate the elements in the order of
3629 /// insertion.
3630 iterator begin() {
3631 if (FirstValidElement == 0)
3632 SkipRemovedElements(FirstValidElement);
3633 return PhiNodeSetIterator(this, FirstValidElement);
3634 }
3635
3636 /// \returns an iterator that points to the end of the collection.
3637 iterator end() { return PhiNodeSetIterator(this, NodeList.size()); }
3638
3639 /// Returns the number of elements in the collection.
3640 size_t size() const { return NodeMap.size(); }
3641
3642 /// \returns 1 if the given element is in the collection, and 0 if otherwise.
3643 size_t count(PHINode *Ptr) const { return NodeMap.count(Ptr); }
3644
3645private:
3646 /// Updates the CurrentIndex so that it will point to a valid element.
3647 ///
3648 /// If the element of NodeList at CurrentIndex is valid, it does not
3649 /// change it. If there are no more valid elements, it updates CurrentIndex
3650 /// to point to the end of the NodeList.
3651 void SkipRemovedElements(size_t &CurrentIndex) {
3652 while (CurrentIndex < NodeList.size()) {
3653 auto it = NodeMap.find(NodeList[CurrentIndex]);
3654 // If the element has been deleted and added again later, NodeMap will
3655 // point to a different index, so CurrentIndex will still be invalid.
3656 if (it != NodeMap.end() && it->second == CurrentIndex)
3657 break;
3658 ++CurrentIndex;
3659 }
3660 }
3661};
3662
3663PhiNodeSetIterator::PhiNodeSetIterator(PhiNodeSet *const Set, size_t Start)
3664 : Set(Set), CurrentIndex(Start) {}
3665
3666PHINode *PhiNodeSetIterator::operator*() const {
3667 assert(CurrentIndex < Set->NodeList.size() &&
3668 "PhiNodeSet access out of range");
3669 return Set->NodeList[CurrentIndex];
3670}
3671
3672PhiNodeSetIterator &PhiNodeSetIterator::operator++() {
3673 assert(CurrentIndex < Set->NodeList.size() &&
3674 "PhiNodeSet access out of range");
3675 ++CurrentIndex;
3676 Set->SkipRemovedElements(CurrentIndex);
3677 return *this;
3678}
3679
3680bool PhiNodeSetIterator::operator==(const PhiNodeSetIterator &RHS) const {
3681 return CurrentIndex == RHS.CurrentIndex;
3682}
3683
3684bool PhiNodeSetIterator::operator!=(const PhiNodeSetIterator &RHS) const {
3685 return !((*this) == RHS);
3686}
3687
3688/// Keep track of simplification of Phi nodes.
3689/// Accept the set of all phi nodes and erase phi node from this set
3690/// if it is simplified.
3691class SimplificationTracker {
3693 const SimplifyQuery &SQ;
3694 // Tracks newly created Phi nodes. The elements are iterated by insertion
3695 // order.
3696 PhiNodeSet AllPhiNodes;
3697 // Tracks newly created Select nodes.
3698 SmallPtrSet<SelectInst *, 32> AllSelectNodes;
3699
3700public:
3701 SimplificationTracker(const SimplifyQuery &sq) : SQ(sq) {}
3702
3703 Value *Get(Value *V) {
3704 do {
3705 auto SV = Storage.find(V);
3706 if (SV == Storage.end())
3707 return V;
3708 V = SV->second;
3709 } while (true);
3710 }
3711
3712 Value *Simplify(Value *Val) {
3713 SmallVector<Value *, 32> WorkList;
3715 WorkList.push_back(Val);
3716 while (!WorkList.empty()) {
3717 auto *P = WorkList.pop_back_val();
3718 if (!Visited.insert(P).second)
3719 continue;
3720 if (auto *PI = dyn_cast<Instruction>(P))
3721 if (Value *V = simplifyInstruction(cast<Instruction>(PI), SQ)) {
3722 for (auto *U : PI->users())
3723 WorkList.push_back(cast<Value>(U));
3724 Put(PI, V);
3725 PI->replaceAllUsesWith(V);
3726 if (auto *PHI = dyn_cast<PHINode>(PI))
3727 AllPhiNodes.erase(PHI);
3728 if (auto *Select = dyn_cast<SelectInst>(PI))
3729 AllSelectNodes.erase(Select);
3730 PI->eraseFromParent();
3731 }
3732 }
3733 return Get(Val);
3734 }
3735
3736 void Put(Value *From, Value *To) { Storage.insert({From, To}); }
3737
3738 void ReplacePhi(PHINode *From, PHINode *To) {
3739 Value *OldReplacement = Get(From);
3740 while (OldReplacement != From) {
3741 From = To;
3742 To = dyn_cast<PHINode>(OldReplacement);
3743 OldReplacement = Get(From);
3744 }
3745 assert(To && Get(To) == To && "Replacement PHI node is already replaced.");
3746 Put(From, To);
3747 From->replaceAllUsesWith(To);
3748 AllPhiNodes.erase(From);
3749 From->eraseFromParent();
3750 }
3751
3752 PhiNodeSet &newPhiNodes() { return AllPhiNodes; }
3753
3754 void insertNewPhi(PHINode *PN) { AllPhiNodes.insert(PN); }
3755
3756 void insertNewSelect(SelectInst *SI) { AllSelectNodes.insert(SI); }
3757
3758 unsigned countNewPhiNodes() const { return AllPhiNodes.size(); }
3759
3760 unsigned countNewSelectNodes() const { return AllSelectNodes.size(); }
3761
3762 void destroyNewNodes(Type *CommonType) {
3763 // For safe erasing, replace the uses with dummy value first.
3764 auto *Dummy = PoisonValue::get(CommonType);
3765 for (auto *I : AllPhiNodes) {
3766 I->replaceAllUsesWith(Dummy);
3767 I->eraseFromParent();
3768 }
3769 AllPhiNodes.clear();
3770 for (auto *I : AllSelectNodes) {
3771 I->replaceAllUsesWith(Dummy);
3772 I->eraseFromParent();
3773 }
3774 AllSelectNodes.clear();
3775 }
3776};
3777
3778/// A helper class for combining addressing modes.
3779class AddressingModeCombiner {
3780 typedef DenseMap<Value *, Value *> FoldAddrToValueMapping;
3781 typedef std::pair<PHINode *, PHINode *> PHIPair;
3782
3783private:
3784 /// The addressing modes we've collected.
3786
3787 /// The field in which the AddrModes differ, when we have more than one.
3788 ExtAddrMode::FieldName DifferentField = ExtAddrMode::NoField;
3789
3790 /// Are the AddrModes that we have all just equal to their original values?
3791 bool AllAddrModesTrivial = true;
3792
3793 /// Common Type for all different fields in addressing modes.
3794 Type *CommonType = nullptr;
3795
3796 /// SimplifyQuery for simplifyInstruction utility.
3797 const SimplifyQuery &SQ;
3798
3799 /// Original Address.
3800 Value *Original;
3801
3802 /// Common value among addresses
3803 Value *CommonValue = nullptr;
3804
3805public:
3806 AddressingModeCombiner(const SimplifyQuery &_SQ, Value *OriginalValue)
3807 : SQ(_SQ), Original(OriginalValue) {}
3808
3809 ~AddressingModeCombiner() { eraseCommonValueIfDead(); }
3810
3811 /// Get the combined AddrMode
3812 const ExtAddrMode &getAddrMode() const { return AddrModes[0]; }
3813
3814 /// Add a new AddrMode if it's compatible with the AddrModes we already
3815 /// have.
3816 /// \return True iff we succeeded in doing so.
3817 bool addNewAddrMode(ExtAddrMode &NewAddrMode) {
3818 // Take note of if we have any non-trivial AddrModes, as we need to detect
3819 // when all AddrModes are trivial as then we would introduce a phi or select
3820 // which just duplicates what's already there.
3821 AllAddrModesTrivial = AllAddrModesTrivial && NewAddrMode.isTrivial();
3822
3823 // If this is the first addrmode then everything is fine.
3824 if (AddrModes.empty()) {
3825 AddrModes.emplace_back(NewAddrMode);
3826 return true;
3827 }
3828
3829 // Figure out how different this is from the other address modes, which we
3830 // can do just by comparing against the first one given that we only care
3831 // about the cumulative difference.
3832 ExtAddrMode::FieldName ThisDifferentField =
3833 AddrModes[0].compare(NewAddrMode);
3834 if (DifferentField == ExtAddrMode::NoField)
3835 DifferentField = ThisDifferentField;
3836 else if (DifferentField != ThisDifferentField)
3837 DifferentField = ExtAddrMode::MultipleFields;
3838
3839 // If NewAddrMode differs in more than one dimension we cannot handle it.
3840 bool CanHandle = DifferentField != ExtAddrMode::MultipleFields;
3841
3842 // If Scale Field is different then we reject.
3843 CanHandle = CanHandle && DifferentField != ExtAddrMode::ScaleField;
3844
3845 // We also must reject the case when base offset is different and
3846 // scale reg is not null, we cannot handle this case due to merge of
3847 // different offsets will be used as ScaleReg.
3848 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseOffsField ||
3849 !NewAddrMode.ScaledReg);
3850
3851 // We also must reject the case when GV is different and BaseReg installed
3852 // due to we want to use base reg as a merge of GV values.
3853 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseGVField ||
3854 !NewAddrMode.HasBaseReg);
3855
3856 // Even if NewAddMode is the same we still need to collect it due to
3857 // original value is different. And later we will need all original values
3858 // as anchors during finding the common Phi node.
3859 if (CanHandle)
3860 AddrModes.emplace_back(NewAddrMode);
3861 else
3862 AddrModes.clear();
3863
3864 return CanHandle;
3865 }
3866
3867 /// Combine the addressing modes we've collected into a single
3868 /// addressing mode.
3869 /// \return True iff we successfully combined them or we only had one so
3870 /// didn't need to combine them anyway.
3871 bool combineAddrModes() {
3872 // If we have no AddrModes then they can't be combined.
3873 if (AddrModes.size() == 0)
3874 return false;
3875
3876 // A single AddrMode can trivially be combined.
3877 if (AddrModes.size() == 1 || DifferentField == ExtAddrMode::NoField)
3878 return true;
3879
3880 // If the AddrModes we collected are all just equal to the value they are
3881 // derived from then combining them wouldn't do anything useful.
3882 if (AllAddrModesTrivial)
3883 return false;
3884
3885 if (!addrModeCombiningAllowed())
3886 return false;
3887
3888 // Build a map between <original value, basic block where we saw it> to
3889 // value of base register.
3890 // Bail out if there is no common type.
3891 FoldAddrToValueMapping Map;
3892 if (!initializeMap(Map))
3893 return false;
3894
3895 CommonValue = findCommon(Map);
3896 if (CommonValue)
3897 AddrModes[0].SetCombinedField(DifferentField, CommonValue, AddrModes);
3898 return CommonValue != nullptr;
3899 }
3900
3901private:
3902 /// `CommonValue` may be a placeholder inserted by us.
3903 /// If the placeholder is not used, we should remove this dead instruction.
3904 void eraseCommonValueIfDead() {
3905 if (CommonValue && CommonValue->getNumUses() == 0)
3906 if (Instruction *CommonInst = dyn_cast<Instruction>(CommonValue))
3907 CommonInst->eraseFromParent();
3908 }
3909
3910 /// Initialize Map with anchor values. For address seen
3911 /// we set the value of different field saw in this address.
3912 /// At the same time we find a common type for different field we will
3913 /// use to create new Phi/Select nodes. Keep it in CommonType field.
3914 /// Return false if there is no common type found.
3915 bool initializeMap(FoldAddrToValueMapping &Map) {
3916 // Keep track of keys where the value is null. We will need to replace it
3917 // with constant null when we know the common type.
3918 SmallVector<Value *, 2> NullValue;
3919 Type *IntPtrTy = SQ.DL.getIntPtrType(AddrModes[0].OriginalValue->getType());
3920 for (auto &AM : AddrModes) {
3921 Value *DV = AM.GetFieldAsValue(DifferentField, IntPtrTy);
3922 if (DV) {
3923 auto *Type = DV->getType();
3924 if (CommonType && CommonType != Type)
3925 return false;
3926 CommonType = Type;
3927 Map[AM.OriginalValue] = DV;
3928 } else {
3929 NullValue.push_back(AM.OriginalValue);
3930 }
3931 }
3932 assert(CommonType && "At least one non-null value must be!");
3933 for (auto *V : NullValue)
3934 Map[V] = Constant::getNullValue(CommonType);
3935 return true;
3936 }
3937
3938 /// We have mapping between value A and other value B where B was a field in
3939 /// addressing mode represented by A. Also we have an original value C
3940 /// representing an address we start with. Traversing from C through phi and
3941 /// selects we ended up with A's in a map. This utility function tries to find
3942 /// a value V which is a field in addressing mode C and traversing through phi
3943 /// nodes and selects we will end up in corresponded values B in a map.
3944 /// The utility will create a new Phi/Selects if needed.
3945 // The simple example looks as follows:
3946 // BB1:
3947 // p1 = b1 + 40
3948 // br cond BB2, BB3
3949 // BB2:
3950 // p2 = b2 + 40
3951 // br BB3
3952 // BB3:
3953 // p = phi [p1, BB1], [p2, BB2]
3954 // v = load p
3955 // Map is
3956 // p1 -> b1
3957 // p2 -> b2
3958 // Request is
3959 // p -> ?
3960 // The function tries to find or build phi [b1, BB1], [b2, BB2] in BB3.
3961 Value *findCommon(FoldAddrToValueMapping &Map) {
3962 // Tracks the simplification of newly created phi nodes. The reason we use
3963 // this mapping is because we will add new created Phi nodes in AddrToBase.
3964 // Simplification of Phi nodes is recursive, so some Phi node may
3965 // be simplified after we added it to AddrToBase. In reality this
3966 // simplification is possible only if original phi/selects were not
3967 // simplified yet.
3968 // Using this mapping we can find the current value in AddrToBase.
3969 SimplificationTracker ST(SQ);
3970
3971 // First step, DFS to create PHI nodes for all intermediate blocks.
3972 // Also fill traverse order for the second step.
3973 SmallVector<Value *, 32> TraverseOrder;
3974 InsertPlaceholders(Map, TraverseOrder, ST);
3975
3976 // Second Step, fill new nodes by merged values and simplify if possible.
3977 FillPlaceholders(Map, TraverseOrder, ST);
3978
3979 if (!AddrSinkNewSelects && ST.countNewSelectNodes() > 0) {
3980 ST.destroyNewNodes(CommonType);
3981 return nullptr;
3982 }
3983
3984 // Now we'd like to match New Phi nodes to existed ones.
3985 unsigned PhiNotMatchedCount = 0;
3986 if (!MatchPhiSet(ST, AddrSinkNewPhis, PhiNotMatchedCount)) {
3987 ST.destroyNewNodes(CommonType);
3988 return nullptr;
3989 }
3990
3991 auto *Result = ST.Get(Map.find(Original)->second);
3992 if (Result) {
3993 NumMemoryInstsPhiCreated += ST.countNewPhiNodes() + PhiNotMatchedCount;
3994 NumMemoryInstsSelectCreated += ST.countNewSelectNodes();
3995 }
3996 return Result;
3997 }
3998
3999 /// Try to match PHI node to Candidate.
4000 /// Matcher tracks the matched Phi nodes.
4001 bool MatchPhiNode(PHINode *PHI, PHINode *Candidate,
4003 PhiNodeSet &PhiNodesToMatch) {
4004 SmallVector<PHIPair, 8> WorkList;
4005 Matcher.insert({PHI, Candidate});
4006 SmallSet<PHINode *, 8> MatchedPHIs;
4007 MatchedPHIs.insert(PHI);
4008 WorkList.push_back({PHI, Candidate});
4009 SmallSet<PHIPair, 8> Visited;
4010 while (!WorkList.empty()) {
4011 auto Item = WorkList.pop_back_val();
4012 if (!Visited.insert(Item).second)
4013 continue;
4014 // We iterate over all incoming values to Phi to compare them.
4015 // If values are different and both of them Phi and the first one is a
4016 // Phi we added (subject to match) and both of them is in the same basic
4017 // block then we can match our pair if values match. So we state that
4018 // these values match and add it to work list to verify that.
4019 for (auto *B : Item.first->blocks()) {
4020 Value *FirstValue = Item.first->getIncomingValueForBlock(B);
4021 Value *SecondValue = Item.second->getIncomingValueForBlock(B);
4022 if (FirstValue == SecondValue)
4023 continue;
4024
4025 PHINode *FirstPhi = dyn_cast<PHINode>(FirstValue);
4026 PHINode *SecondPhi = dyn_cast<PHINode>(SecondValue);
4027
4028 // One of them is not Phi or
4029 // The first one is not Phi node from the set we'd like to match or
4030 // Phi nodes from different basic blocks then
4031 // we will not be able to match.
4032 if (!FirstPhi || !SecondPhi || !PhiNodesToMatch.count(FirstPhi) ||
4033 FirstPhi->getParent() != SecondPhi->getParent())
4034 return false;
4035
4036 // If we already matched them then continue.
4037 if (Matcher.count({FirstPhi, SecondPhi}))
4038 continue;
4039 // So the values are different and does not match. So we need them to
4040 // match. (But we register no more than one match per PHI node, so that
4041 // we won't later try to replace them twice.)
4042 if (MatchedPHIs.insert(FirstPhi).second)
4043 Matcher.insert({FirstPhi, SecondPhi});
4044 // But me must check it.
4045 WorkList.push_back({FirstPhi, SecondPhi});
4046 }
4047 }
4048 return true;
4049 }
4050
4051 /// For the given set of PHI nodes (in the SimplificationTracker) try
4052 /// to find their equivalents.
4053 /// Returns false if this matching fails and creation of new Phi is disabled.
4054 bool MatchPhiSet(SimplificationTracker &ST, bool AllowNewPhiNodes,
4055 unsigned &PhiNotMatchedCount) {
4056 // Matched and PhiNodesToMatch iterate their elements in a deterministic
4057 // order, so the replacements (ReplacePhi) are also done in a deterministic
4058 // order.
4060 SmallPtrSet<PHINode *, 8> WillNotMatch;
4061 PhiNodeSet &PhiNodesToMatch = ST.newPhiNodes();
4062 while (PhiNodesToMatch.size()) {
4063 PHINode *PHI = *PhiNodesToMatch.begin();
4064
4065 // Add us, if no Phi nodes in the basic block we do not match.
4066 WillNotMatch.clear();
4067 WillNotMatch.insert(PHI);
4068
4069 // Traverse all Phis until we found equivalent or fail to do that.
4070 bool IsMatched = false;
4071 for (auto &P : PHI->getParent()->phis()) {
4072 // Skip new Phi nodes.
4073 if (PhiNodesToMatch.count(&P))
4074 continue;
4075 if ((IsMatched = MatchPhiNode(PHI, &P, Matched, PhiNodesToMatch)))
4076 break;
4077 // If it does not match, collect all Phi nodes from matcher.
4078 // if we end up with no match, them all these Phi nodes will not match
4079 // later.
4080 for (auto M : Matched)
4081 WillNotMatch.insert(M.first);
4082 Matched.clear();
4083 }
4084 if (IsMatched) {
4085 // Replace all matched values and erase them.
4086 for (auto MV : Matched)
4087 ST.ReplacePhi(MV.first, MV.second);
4088 Matched.clear();
4089 continue;
4090 }
4091 // If we are not allowed to create new nodes then bail out.
4092 if (!AllowNewPhiNodes)
4093 return false;
4094 // Just remove all seen values in matcher. They will not match anything.
4095 PhiNotMatchedCount += WillNotMatch.size();
4096 for (auto *P : WillNotMatch)
4097 PhiNodesToMatch.erase(P);
4098 }
4099 return true;
4100 }
4101 /// Fill the placeholders with values from predecessors and simplify them.
4102 void FillPlaceholders(FoldAddrToValueMapping &Map,
4103 SmallVectorImpl<Value *> &TraverseOrder,
4104 SimplificationTracker &ST) {
4105 while (!TraverseOrder.empty()) {
4106 Value *Current = TraverseOrder.pop_back_val();
4107 assert(Map.contains(Current) && "No node to fill!!!");
4108 Value *V = Map[Current];
4109
4110 if (SelectInst *Select = dyn_cast<SelectInst>(V)) {
4111 // CurrentValue also must be Select.
4112 auto *CurrentSelect = cast<SelectInst>(Current);
4113 auto *TrueValue = CurrentSelect->getTrueValue();
4114 assert(Map.contains(TrueValue) && "No True Value!");
4115 Select->setTrueValue(ST.Get(Map[TrueValue]));
4116 auto *FalseValue = CurrentSelect->getFalseValue();
4117 assert(Map.contains(FalseValue) && "No False Value!");
4118 Select->setFalseValue(ST.Get(Map[FalseValue]));
4119 } else {
4120 // Must be a Phi node then.
4121 auto *PHI = cast<PHINode>(V);
4122 // Fill the Phi node with values from predecessors.
4123 for (auto *B : predecessors(PHI->getParent())) {
4124 Value *PV = cast<PHINode>(Current)->getIncomingValueForBlock(B);
4125 assert(Map.contains(PV) && "No predecessor Value!");
4126 PHI->addIncoming(ST.Get(Map[PV]), B);
4127 }
4128 }
4129 Map[Current] = ST.Simplify(V);
4130 }
4131 }
4132
4133 /// Starting from original value recursively iterates over def-use chain up to
4134 /// known ending values represented in a map. For each traversed phi/select
4135 /// inserts a placeholder Phi or Select.
4136 /// Reports all new created Phi/Select nodes by adding them to set.
4137 /// Also reports and order in what values have been traversed.
4138 void InsertPlaceholders(FoldAddrToValueMapping &Map,
4139 SmallVectorImpl<Value *> &TraverseOrder,
4140 SimplificationTracker &ST) {
4141 SmallVector<Value *, 32> Worklist;
4142 assert((isa<PHINode>(Original) || isa<SelectInst>(Original)) &&
4143 "Address must be a Phi or Select node");
4144 auto *Dummy = PoisonValue::get(CommonType);
4145 Worklist.push_back(Original);
4146 while (!Worklist.empty()) {
4147 Value *Current = Worklist.pop_back_val();
4148 // if it is already visited or it is an ending value then skip it.
4149 if (Map.contains(Current))
4150 continue;
4151 TraverseOrder.push_back(Current);
4152
4153 // CurrentValue must be a Phi node or select. All others must be covered
4154 // by anchors.
4155 if (SelectInst *CurrentSelect = dyn_cast<SelectInst>(Current)) {
4156 // Is it OK to get metadata from OrigSelect?!
4157 // Create a Select placeholder with dummy value.
4159 SelectInst::Create(CurrentSelect->getCondition(), Dummy, Dummy,
4160 CurrentSelect->getName(),
4161 CurrentSelect->getIterator(), CurrentSelect);
4162 Map[Current] = Select;
4163 ST.insertNewSelect(Select);
4164 // We are interested in True and False values.
4165 Worklist.push_back(CurrentSelect->getTrueValue());
4166 Worklist.push_back(CurrentSelect->getFalseValue());
4167 } else {
4168 // It must be a Phi node then.
4169 PHINode *CurrentPhi = cast<PHINode>(Current);
4170 unsigned PredCount = CurrentPhi->getNumIncomingValues();
4171 PHINode *PHI =
4172 PHINode::Create(CommonType, PredCount, "sunk_phi", CurrentPhi->getIterator());
4173 Map[Current] = PHI;
4174 ST.insertNewPhi(PHI);
4175 append_range(Worklist, CurrentPhi->incoming_values());
4176 }
4177 }
4178 }
4179
4180 bool addrModeCombiningAllowed() {
4182 return false;
4183 switch (DifferentField) {
4184 default:
4185 return false;
4186 case ExtAddrMode::BaseRegField:
4188 case ExtAddrMode::BaseGVField:
4189 return AddrSinkCombineBaseGV;
4190 case ExtAddrMode::BaseOffsField:
4192 case ExtAddrMode::ScaledRegField:
4194 }
4195 }
4196};
4197} // end anonymous namespace
4198
4199/// Try adding ScaleReg*Scale to the current addressing mode.
4200/// Return true and update AddrMode if this addr mode is legal for the target,
4201/// false if not.
4202bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
4203 unsigned Depth) {
4204 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
4205 // mode. Just process that directly.
4206 if (Scale == 1)
4207 return matchAddr(ScaleReg, Depth);
4208
4209 // If the scale is 0, it takes nothing to add this.
4210 if (Scale == 0)
4211 return true;
4212
4213 // If we already have a scale of this value, we can add to it, otherwise, we
4214 // need an available scale field.
4215 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
4216 return false;
4217
4218 ExtAddrMode TestAddrMode = AddrMode;
4219
4220 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
4221 // [A+B + A*7] -> [B+A*8].
4222 TestAddrMode.Scale += Scale;
4223 TestAddrMode.ScaledReg = ScaleReg;
4224
4225 // If the new address isn't legal, bail out.
4226 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
4227 return false;
4228
4229 // It was legal, so commit it.
4230 AddrMode = TestAddrMode;
4231
4232 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
4233 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
4234 // X*Scale + C*Scale to addr mode. If we found available IV increment, do not
4235 // go any further: we can reuse it and cannot eliminate it.
4236 ConstantInt *CI = nullptr;
4237 Value *AddLHS = nullptr;
4238 if (isa<Instruction>(ScaleReg) && // not a constant expr.
4239 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI))) &&
4240 !isIVIncrement(ScaleReg, &LI) && CI->getValue().isSignedIntN(64)) {
4241 TestAddrMode.InBounds = false;
4242 TestAddrMode.ScaledReg = AddLHS;
4243 TestAddrMode.BaseOffs += CI->getSExtValue() * TestAddrMode.Scale;
4244
4245 // If this addressing mode is legal, commit it and remember that we folded
4246 // this instruction.
4247 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
4248 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
4249 AddrMode = TestAddrMode;
4250 return true;
4251 }
4252 // Restore status quo.
4253 TestAddrMode = AddrMode;
4254 }
4255
4256 // If this is an add recurrence with a constant step, return the increment
4257 // instruction and the canonicalized step.
4258 auto GetConstantStep =
4259 [this](const Value *V) -> std::optional<std::pair<Instruction *, APInt>> {
4260 auto *PN = dyn_cast<PHINode>(V);
4261 if (!PN)
4262 return std::nullopt;
4263 auto IVInc = getIVIncrement(PN, &LI);
4264 if (!IVInc)
4265 return std::nullopt;
4266 // TODO: The result of the intrinsics above is two-complement. However when
4267 // IV inc is expressed as add or sub, iv.next is potentially a poison value.
4268 // If it has nuw or nsw flags, we need to make sure that these flags are
4269 // inferrable at the point of memory instruction. Otherwise we are replacing
4270 // well-defined two-complement computation with poison. Currently, to avoid
4271 // potentially complex analysis needed to prove this, we reject such cases.
4272 if (auto *OIVInc = dyn_cast<OverflowingBinaryOperator>(IVInc->first))
4273 if (OIVInc->hasNoSignedWrap() || OIVInc->hasNoUnsignedWrap())
4274 return std::nullopt;
4275 if (auto *ConstantStep = dyn_cast<ConstantInt>(IVInc->second))
4276 return std::make_pair(IVInc->first, ConstantStep->getValue());
4277 return std::nullopt;
4278 };
4279
4280 // Try to account for the following special case:
4281 // 1. ScaleReg is an inductive variable;
4282 // 2. We use it with non-zero offset;
4283 // 3. IV's increment is available at the point of memory instruction.
4284 //
4285 // In this case, we may reuse the IV increment instead of the IV Phi to
4286 // achieve the following advantages:
4287 // 1. If IV step matches the offset, we will have no need in the offset;
4288 // 2. Even if they don't match, we will reduce the overlap of living IV
4289 // and IV increment, that will potentially lead to better register
4290 // assignment.
4291 if (AddrMode.BaseOffs) {
4292 if (auto IVStep = GetConstantStep(ScaleReg)) {
4293 Instruction *IVInc = IVStep->first;
4294 // The following assert is important to ensure a lack of infinite loops.
4295 // This transforms is (intentionally) the inverse of the one just above.
4296 // If they don't agree on the definition of an increment, we'd alternate
4297 // back and forth indefinitely.
4298 assert(isIVIncrement(IVInc, &LI) && "implied by GetConstantStep");
4299 APInt Step = IVStep->second;
4300 APInt Offset = Step * AddrMode.Scale;
4301 if (Offset.isSignedIntN(64)) {
4302 TestAddrMode.InBounds = false;
4303 TestAddrMode.ScaledReg = IVInc;
4304 TestAddrMode.BaseOffs -= Offset.getLimitedValue();
4305 // If this addressing mode is legal, commit it..
4306 // (Note that we defer the (expensive) domtree base legality check
4307 // to the very last possible point.)
4308 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace) &&
4309 getDTFn().dominates(IVInc, MemoryInst)) {
4310 AddrModeInsts.push_back(cast<Instruction>(IVInc));
4311 AddrMode = TestAddrMode;
4312 return true;
4313 }
4314 // Restore status quo.
4315 TestAddrMode = AddrMode;
4316 }
4317 }
4318 }
4319
4320 // Otherwise, just return what we have.
4321 return true;
4322}
4323
4324/// This is a little filter, which returns true if an addressing computation
4325/// involving I might be folded into a load/store accessing it.
4326/// This doesn't need to be perfect, but needs to accept at least
4327/// the set of instructions that MatchOperationAddr can.
4329 switch (I->getOpcode()) {
4330 case Instruction::BitCast:
4331 case Instruction::AddrSpaceCast:
4332 // Don't touch identity bitcasts.
4333 if (I->getType() == I->getOperand(0)->getType())
4334 return false;
4335 return I->getType()->isIntOrPtrTy();
4336 case Instruction::PtrToInt:
4337 // PtrToInt is always a noop, as we know that the int type is pointer sized.
4338 return true;
4339 case Instruction::IntToPtr:
4340 // We know the input is intptr_t, so this is foldable.
4341 return true;
4342 case Instruction::Add:
4343 return true;
4344 case Instruction::Mul:
4345 case Instruction::Shl:
4346 // Can only handle X*C and X << C.
4347 return isa<ConstantInt>(I->getOperand(1));
4348 case Instruction::GetElementPtr:
4349 return true;
4350 default:
4351 return false;
4352 }
4353}
4354
4355/// Check whether or not \p Val is a legal instruction for \p TLI.
4356/// \note \p Val is assumed to be the product of some type promotion.
4357/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
4358/// to be legal, as the non-promoted value would have had the same state.
4360 const DataLayout &DL, Value *Val) {
4361 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
4362 if (!PromotedInst)
4363 return false;
4364 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
4365 // If the ISDOpcode is undefined, it was undefined before the promotion.
4366 if (!ISDOpcode)
4367 return true;
4368 // Otherwise, check if the promoted instruction is legal or not.
4369 return TLI.isOperationLegalOrCustom(
4370 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
4371}
4372
4373namespace {
4374
4375/// Hepler class to perform type promotion.
4376class TypePromotionHelper {
4377 /// Utility function to add a promoted instruction \p ExtOpnd to
4378 /// \p PromotedInsts and record the type of extension we have seen.
4379 static void addPromotedInst(InstrToOrigTy &PromotedInsts,
4380 Instruction *ExtOpnd, bool IsSExt) {
4381 ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension;
4382 InstrToOrigTy::iterator It = PromotedInsts.find(ExtOpnd);
4383 if (It != PromotedInsts.end()) {
4384 // If the new extension is same as original, the information in
4385 // PromotedInsts[ExtOpnd] is still correct.
4386 if (It->second.getInt() == ExtTy)
4387 return;
4388
4389 // Now the new extension is different from old extension, we make
4390 // the type information invalid by setting extension type to
4391 // BothExtension.
4392 ExtTy = BothExtension;
4393 }
4394 PromotedInsts[ExtOpnd] = TypeIsSExt(ExtOpnd->getType(), ExtTy);
4395 }
4396
4397 /// Utility function to query the original type of instruction \p Opnd
4398 /// with a matched extension type. If the extension doesn't match, we
4399 /// cannot use the information we had on the original type.
4400 /// BothExtension doesn't match any extension type.
4401 static const Type *getOrigType(const InstrToOrigTy &PromotedInsts,
4402 Instruction *Opnd, bool IsSExt) {
4403 ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension;
4404 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
4405 if (It != PromotedInsts.end() && It->second.getInt() == ExtTy)
4406 return It->second.getPointer();
4407 return nullptr;
4408 }
4409
4410 /// Utility function to check whether or not a sign or zero extension
4411 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
4412 /// either using the operands of \p Inst or promoting \p Inst.
4413 /// The type of the extension is defined by \p IsSExt.
4414 /// In other words, check if:
4415 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
4416 /// #1 Promotion applies:
4417 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
4418 /// #2 Operand reuses:
4419 /// ext opnd1 to ConsideredExtType.
4420 /// \p PromotedInsts maps the instructions to their type before promotion.
4421 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
4422 const InstrToOrigTy &PromotedInsts, bool IsSExt);
4423
4424 /// Utility function to determine if \p OpIdx should be promoted when
4425 /// promoting \p Inst.
4426 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
4427 return !(isa<SelectInst>(Inst) && OpIdx == 0);
4428 }
4429
4430 /// Utility function to promote the operand of \p Ext when this
4431 /// operand is a promotable trunc or sext or zext.
4432 /// \p PromotedInsts maps the instructions to their type before promotion.
4433 /// \p CreatedInstsCost[out] contains the cost of all instructions
4434 /// created to promote the operand of Ext.
4435 /// Newly added extensions are inserted in \p Exts.
4436 /// Newly added truncates are inserted in \p Truncs.
4437 /// Should never be called directly.
4438 /// \return The promoted value which is used instead of Ext.
4439 static Value *promoteOperandForTruncAndAnyExt(
4440 Instruction *Ext, TypePromotionTransaction &TPT,
4441 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4444
4445 /// Utility function to promote the operand of \p Ext when this
4446 /// operand is promotable and is not a supported trunc or sext.
4447 /// \p PromotedInsts maps the instructions to their type before promotion.
4448 /// \p CreatedInstsCost[out] contains the cost of all the instructions
4449 /// created to promote the operand of Ext.
4450 /// Newly added extensions are inserted in \p Exts.
4451 /// Newly added truncates are inserted in \p Truncs.
4452 /// Should never be called directly.
4453 /// \return The promoted value which is used instead of Ext.
4454 static Value *promoteOperandForOther(Instruction *Ext,
4455 TypePromotionTransaction &TPT,
4456 InstrToOrigTy &PromotedInsts,
4457 unsigned &CreatedInstsCost,
4460 const TargetLowering &TLI, bool IsSExt);
4461
4462 /// \see promoteOperandForOther.
4463 static Value *signExtendOperandForOther(
4464 Instruction *Ext, TypePromotionTransaction &TPT,
4465 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4467 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
4468 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
4469 Exts, Truncs, TLI, true);
4470 }
4471
4472 /// \see promoteOperandForOther.
4473 static Value *zeroExtendOperandForOther(
4474 Instruction *Ext, TypePromotionTransaction &TPT,
4475 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4477 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
4478 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
4479 Exts, Truncs, TLI, false);
4480 }
4481
4482public:
4483 /// Type for the utility function that promotes the operand of Ext.
4484 using Action = Value *(*)(Instruction *Ext, TypePromotionTransaction &TPT,
4485 InstrToOrigTy &PromotedInsts,
4486 unsigned &CreatedInstsCost,
4489 const TargetLowering &TLI);
4490
4491 /// Given a sign/zero extend instruction \p Ext, return the appropriate
4492 /// action to promote the operand of \p Ext instead of using Ext.
4493 /// \return NULL if no promotable action is possible with the current
4494 /// sign extension.
4495 /// \p InsertedInsts keeps track of all the instructions inserted by the
4496 /// other CodeGenPrepare optimizations. This information is important
4497 /// because we do not want to promote these instructions as CodeGenPrepare
4498 /// will reinsert them later. Thus creating an infinite loop: create/remove.
4499 /// \p PromotedInsts maps the instructions to their type before promotion.
4500 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
4501 const TargetLowering &TLI,
4502 const InstrToOrigTy &PromotedInsts);
4503};
4504
4505} // end anonymous namespace
4506
4507bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
4508 Type *ConsideredExtType,
4509 const InstrToOrigTy &PromotedInsts,
4510 bool IsSExt) {
4511 // The promotion helper does not know how to deal with vector types yet.
4512 // To be able to fix that, we would need to fix the places where we
4513 // statically extend, e.g., constants and such.
4514 if (Inst->getType()->isVectorTy())
4515 return false;
4516
4517 // We can always get through zext.
4518 if (isa<ZExtInst>(Inst))
4519 return true;
4520
4521 // sext(sext) is ok too.
4522 if (IsSExt && isa<SExtInst>(Inst))
4523 return true;
4524
4525 // We can get through binary operator, if it is legal. In other words, the
4526 // binary operator must have a nuw or nsw flag.
4527 if (const auto *BinOp = dyn_cast<BinaryOperator>(Inst))
4528 if (isa<OverflowingBinaryOperator>(BinOp) &&
4529 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
4530 (IsSExt && BinOp->hasNoSignedWrap())))
4531 return true;
4532
4533 // ext(and(opnd, cst)) --> and(ext(opnd), ext(cst))
4534 if ((Inst->getOpcode() == Instruction::And ||
4535 Inst->getOpcode() == Instruction::Or))
4536 return true;
4537
4538 // ext(xor(opnd, cst)) --> xor(ext(opnd), ext(cst))
4539 if (Inst->getOpcode() == Instruction::Xor) {
4540 // Make sure it is not a NOT.
4541 if (const auto *Cst = dyn_cast<ConstantInt>(Inst->getOperand(1)))
4542 if (!Cst->getValue().isAllOnes())
4543 return true;
4544 }
4545
4546 // zext(shrl(opnd, cst)) --> shrl(zext(opnd), zext(cst))
4547 // It may change a poisoned value into a regular value, like
4548 // zext i32 (shrl i8 %val, 12) --> shrl i32 (zext i8 %val), 12
4549 // poisoned value regular value
4550 // It should be OK since undef covers valid value.
4551 if (Inst->getOpcode() == Instruction::LShr && !IsSExt)
4552 return true;
4553
4554 // and(ext(shl(opnd, cst)), cst) --> and(shl(ext(opnd), ext(cst)), cst)
4555 // It may change a poisoned value into a regular value, like
4556 // zext i32 (shl i8 %val, 12) --> shl i32 (zext i8 %val), 12
4557 // poisoned value regular value
4558 // It should be OK since undef covers valid value.
4559 if (Inst->getOpcode() == Instruction::Shl && Inst->hasOneUse()) {
4560 const auto *ExtInst = cast<const Instruction>(*Inst->user_begin());
4561 if (ExtInst->hasOneUse()) {
4562 const auto *AndInst = dyn_cast<const Instruction>(*ExtInst->user_begin());
4563 if (AndInst && AndInst->getOpcode() == Instruction::And) {
4564 const auto *Cst = dyn_cast<ConstantInt>(AndInst->getOperand(1));
4565 if (Cst &&
4566 Cst->getValue().isIntN(Inst->getType()->getIntegerBitWidth()))
4567 return true;
4568 }
4569 }
4570 }
4571
4572 // Check if we can do the following simplification.
4573 // ext(trunc(opnd)) --> ext(opnd)
4574 if (!isa<TruncInst>(Inst))
4575 return false;
4576
4577 Value *OpndVal = Inst->getOperand(0);
4578 // Check if we can use this operand in the extension.
4579 // If the type is larger than the result type of the extension, we cannot.
4580 if (!OpndVal->getType()->isIntegerTy() ||
4581 OpndVal->getType()->getIntegerBitWidth() >
4582 ConsideredExtType->getIntegerBitWidth())
4583 return false;
4584
4585 // If the operand of the truncate is not an instruction, we will not have
4586 // any information on the dropped bits.
4587 // (Actually we could for constant but it is not worth the extra logic).
4588 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
4589 if (!Opnd)
4590 return false;
4591
4592 // Check if the source of the type is narrow enough.
4593 // I.e., check that trunc just drops extended bits of the same kind of
4594 // the extension.
4595 // #1 get the type of the operand and check the kind of the extended bits.
4596 const Type *OpndType = getOrigType(PromotedInsts, Opnd, IsSExt);
4597 if (OpndType)
4598 ;
4599 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
4600 OpndType = Opnd->getOperand(0)->getType();
4601 else
4602 return false;
4603
4604 // #2 check that the truncate just drops extended bits.
4605 return Inst->getType()->getIntegerBitWidth() >=
4606 OpndType->getIntegerBitWidth();
4607}
4608
4609TypePromotionHelper::Action TypePromotionHelper::getAction(
4610 Instruction *Ext, const SetOfInstrs &InsertedInsts,
4611 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
4612 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
4613 "Unexpected instruction type");
4614 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
4615 Type *ExtTy = Ext->getType();
4616 bool IsSExt = isa<SExtInst>(Ext);
4617 // If the operand of the extension is not an instruction, we cannot
4618 // get through.
4619 // If it, check we can get through.
4620 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
4621 return nullptr;
4622
4623 // Do not promote if the operand has been added by codegenprepare.
4624 // Otherwise, it means we are undoing an optimization that is likely to be
4625 // redone, thus causing potential infinite loop.
4626 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
4627 return nullptr;
4628
4629 // SExt or Trunc instructions.
4630 // Return the related handler.
4631 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
4632 isa<ZExtInst>(ExtOpnd))
4633 return promoteOperandForTruncAndAnyExt;
4634
4635 // Regular instruction.
4636 // Abort early if we will have to insert non-free instructions.
4637 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
4638 return nullptr;
4639 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
4640}
4641
4642Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
4643 Instruction *SExt, TypePromotionTransaction &TPT,
4644 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4646 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
4647 // By construction, the operand of SExt is an instruction. Otherwise we cannot
4648 // get through it and this method should not be called.
4649 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
4650 Value *ExtVal = SExt;
4651 bool HasMergedNonFreeExt = false;
4652 if (isa<ZExtInst>(SExtOpnd)) {
4653 // Replace s|zext(zext(opnd))
4654 // => zext(opnd).
4655 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
4656 Value *ZExt =
4657 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
4658 TPT.replaceAllUsesWith(SExt, ZExt);
4659 TPT.eraseInstruction(SExt);
4660 ExtVal = ZExt;
4661 } else {
4662 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
4663 // => z|sext(opnd).
4664 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
4665 }
4666 CreatedInstsCost = 0;
4667
4668 // Remove dead code.
4669 if (SExtOpnd->use_empty())
4670 TPT.eraseInstruction(SExtOpnd);
4671
4672 // Check if the extension is still needed.
4673 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
4674 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
4675 if (ExtInst) {
4676 if (Exts)
4677 Exts->push_back(ExtInst);
4678 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
4679 }
4680 return ExtVal;
4681 }
4682
4683 // At this point we have: ext ty opnd to ty.
4684 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
4685 Value *NextVal = ExtInst->getOperand(0);
4686 TPT.eraseInstruction(ExtInst, NextVal);
4687 return NextVal;
4688}
4689
4690Value *TypePromotionHelper::promoteOperandForOther(
4691 Instruction *Ext, TypePromotionTransaction &TPT,
4692 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4695 bool IsSExt) {
4696 // By construction, the operand of Ext is an instruction. Otherwise we cannot
4697 // get through it and this method should not be called.
4698 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
4699 CreatedInstsCost = 0;
4700 if (!ExtOpnd->hasOneUse()) {
4701 // ExtOpnd will be promoted.
4702 // All its uses, but Ext, will need to use a truncated value of the
4703 // promoted version.
4704 // Create the truncate now.
4705 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
4706 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
4707 // Insert it just after the definition.
4708 ITrunc->moveAfter(ExtOpnd);
4709 if (Truncs)
4710 Truncs->push_back(ITrunc);
4711 }
4712
4713 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
4714 // Restore the operand of Ext (which has been replaced by the previous call
4715 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
4716 TPT.setOperand(Ext, 0, ExtOpnd);
4717 }
4718
4719 // Get through the Instruction:
4720 // 1. Update its type.
4721 // 2. Replace the uses of Ext by Inst.
4722 // 3. Extend each operand that needs to be extended.
4723
4724 // Remember the original type of the instruction before promotion.
4725 // This is useful to know that the high bits are sign extended bits.
4726 addPromotedInst(PromotedInsts, ExtOpnd, IsSExt);
4727 // Step #1.
4728 TPT.mutateType(ExtOpnd, Ext->getType());
4729 // Step #2.
4730 TPT.replaceAllUsesWith(Ext, ExtOpnd);
4731 // Step #3.
4732 LLVM_DEBUG(dbgs() << "Propagate Ext to operands\n");
4733 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
4734 ++OpIdx) {
4735 LLVM_DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
4736 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
4737 !shouldExtOperand(ExtOpnd, OpIdx)) {
4738 LLVM_DEBUG(dbgs() << "No need to propagate\n");
4739 continue;
4740 }
4741 // Check if we can statically extend the operand.
4742 Value *Opnd = ExtOpnd->getOperand(OpIdx);
4743 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
4744 LLVM_DEBUG(dbgs() << "Statically extend\n");
4745 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
4746 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
4747 : Cst->getValue().zext(BitWidth);
4748 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
4749 continue;
4750 }
4751 // UndefValue are typed, so we have to statically sign extend them.
4752 if (isa<UndefValue>(Opnd)) {
4753 LLVM_DEBUG(dbgs() << "Statically extend\n");
4754 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
4755 continue;
4756 }
4757
4758 // Otherwise we have to explicitly sign extend the operand.
4759 Value *ValForExtOpnd = IsSExt
4760 ? TPT.createSExt(ExtOpnd, Opnd, Ext->getType())
4761 : TPT.createZExt(ExtOpnd, Opnd, Ext->getType());
4762 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
4763 Instruction *InstForExtOpnd = dyn_cast<Instruction>(ValForExtOpnd);
4764 if (!InstForExtOpnd)
4765 continue;
4766
4767 if (Exts)
4768 Exts->push_back(InstForExtOpnd);
4769
4770 CreatedInstsCost += !TLI.isExtFree(InstForExtOpnd);
4771 }
4772 LLVM_DEBUG(dbgs() << "Extension is useless now\n");
4773 TPT.eraseInstruction(Ext);
4774 return ExtOpnd;
4775}
4776
4777/// Check whether or not promoting an instruction to a wider type is profitable.
4778/// \p NewCost gives the cost of extension instructions created by the
4779/// promotion.
4780/// \p OldCost gives the cost of extension instructions before the promotion
4781/// plus the number of instructions that have been
4782/// matched in the addressing mode the promotion.
4783/// \p PromotedOperand is the value that has been promoted.
4784/// \return True if the promotion is profitable, false otherwise.
4785bool AddressingModeMatcher::isPromotionProfitable(
4786 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
4787 LLVM_DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost
4788 << '\n');
4789 // The cost of the new extensions is greater than the cost of the
4790 // old extension plus what we folded.
4791 // This is not profitable.
4792 if (NewCost > OldCost)
4793 return false;
4794 if (NewCost < OldCost)
4795 return true;
4796 // The promotion is neutral but it may help folding the sign extension in
4797 // loads for instance.
4798 // Check that we did not create an illegal instruction.
4799 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
4800}
4801
4802/// Given an instruction or constant expr, see if we can fold the operation
4803/// into the addressing mode. If so, update the addressing mode and return
4804/// true, otherwise return false without modifying AddrMode.
4805/// If \p MovedAway is not NULL, it contains the information of whether or
4806/// not AddrInst has to be folded into the addressing mode on success.
4807/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
4808/// because it has been moved away.
4809/// Thus AddrInst must not be added in the matched instructions.
4810/// This state can happen when AddrInst is a sext, since it may be moved away.
4811/// Therefore, AddrInst may not be valid when MovedAway is true and it must
4812/// not be referenced anymore.
4813bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
4814 unsigned Depth,
4815 bool *MovedAway) {
4816 // Avoid exponential behavior on extremely deep expression trees.
4817 if (Depth >= 5)
4818 return false;
4819
4820 // By default, all matched instructions stay in place.
4821 if (MovedAway)
4822 *MovedAway = false;
4823
4824 switch (Opcode) {
4825 case Instruction::PtrToInt:
4826 // PtrToInt is always a noop, as we know that the int type is pointer sized.
4827 return matchAddr(AddrInst->getOperand(0), Depth);
4828 case Instruction::IntToPtr: {
4829 auto AS = AddrInst->getType()->getPointerAddressSpace();
4830 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
4831 // This inttoptr is a no-op if the integer type is pointer sized.
4832 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
4833 return matchAddr(AddrInst->getOperand(0), Depth);
4834 return false;
4835 }
4836 case Instruction::BitCast:
4837 // BitCast is always a noop, and we can handle it as long as it is
4838 // int->int or pointer->pointer (we don't want int<->fp or something).
4839 if (AddrInst->getOperand(0)->getType()->isIntOrPtrTy() &&
4840 // Don't touch identity bitcasts. These were probably put here by LSR,
4841 // and we don't want to mess around with them. Assume it knows what it
4842 // is doing.
4843 AddrInst->getOperand(0)->getType() != AddrInst->getType())
4844 return matchAddr(AddrInst->getOperand(0), Depth);
4845 return false;
4846 case Instruction::AddrSpaceCast: {
4847 unsigned SrcAS =
4848 AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
4849 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
4850 if (TLI.getTargetMachine().isNoopAddrSpaceCast(SrcAS, DestAS))
4851 return matchAddr(AddrInst->getOperand(0), Depth);
4852 return false;
4853 }
4854 case Instruction::Add: {
4855 // Check to see if we can merge in one operand, then the other. If so, we
4856 // win.
4857 ExtAddrMode BackupAddrMode = AddrMode;
4858 unsigned OldSize = AddrModeInsts.size();
4859 // Start a transaction at this point.
4860 // The LHS may match but not the RHS.
4861 // Therefore, we need a higher level restoration point to undo partially
4862 // matched operation.
4863 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4864 TPT.getRestorationPoint();
4865
4866 // Try to match an integer constant second to increase its chance of ending
4867 // up in `BaseOffs`, resp. decrease its chance of ending up in `BaseReg`.
4868 int First = 0, Second = 1;
4869 if (isa<ConstantInt>(AddrInst->getOperand(First))
4870 && !isa<ConstantInt>(AddrInst->getOperand(Second)))
4871 std::swap(First, Second);
4872 AddrMode.InBounds = false;
4873 if (matchAddr(AddrInst->getOperand(First), Depth + 1) &&
4874 matchAddr(AddrInst->getOperand(Second), Depth + 1))
4875 return true;
4876
4877 // Restore the old addr mode info.
4878 AddrMode = BackupAddrMode;
4879 AddrModeInsts.resize(OldSize);
4880 TPT.rollback(LastKnownGood);
4881
4882 // Otherwise this was over-aggressive. Try merging operands in the opposite
4883 // order.
4884 if (matchAddr(AddrInst->getOperand(Second), Depth + 1) &&
4885 matchAddr(AddrInst->getOperand(First), Depth + 1))
4886 return true;
4887
4888 // Otherwise we definitely can't merge the ADD in.
4889 AddrMode = BackupAddrMode;
4890 AddrModeInsts.resize(OldSize);
4891 TPT.rollback(LastKnownGood);
4892 break;
4893 }
4894 // case Instruction::Or:
4895 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
4896 // break;
4897 case Instruction::Mul:
4898 case Instruction::Shl: {
4899 // Can only handle X*C and X << C.
4900 AddrMode.InBounds = false;
4901 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
4902 if (!RHS || RHS->getBitWidth() > 64)
4903 return false;
4904 int64_t Scale = Opcode == Instruction::Shl
4905 ? 1LL << RHS->getLimitedValue(RHS->getBitWidth() - 1)
4906 : RHS->getSExtValue();
4907
4908 return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
4909 }
4910 case Instruction::GetElementPtr: {
4911 // Scan the GEP. We check it if it contains constant offsets and at most
4912 // one variable offset.
4913 int VariableOperand = -1;
4914 unsigned VariableScale = 0;
4915
4916 int64_t ConstantOffset = 0;
4917 gep_type_iterator GTI = gep_type_begin(AddrInst);
4918 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
4919 if (StructType *STy = GTI.getStructTypeOrNull()) {
4920 const StructLayout *SL = DL.getStructLayout(STy);
4921 unsigned Idx =
4922 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
4923 ConstantOffset += SL->getElementOffset(Idx);
4924 } else {
4926 if (TS.isNonZero()) {
4927 // The optimisations below currently only work for fixed offsets.
4928 if (TS.isScalable())
4929 return false;
4930 int64_t TypeSize = TS.getFixedValue();
4931 if (ConstantInt *CI =
4932 dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
4933 const APInt &CVal = CI->getValue();
4934 if (CVal.getSignificantBits() <= 64) {
4935 ConstantOffset += CVal.getSExtValue() * TypeSize;
4936 continue;
4937 }
4938 }
4939 // We only allow one variable index at the moment.
4940 if (VariableOperand != -1)
4941 return false;
4942
4943 // Remember the variable index.
4944 VariableOperand = i;
4945 VariableScale = TypeSize;
4946 }
4947 }
4948 }
4949
4950 // A common case is for the GEP to only do a constant offset. In this case,
4951 // just add it to the disp field and check validity.
4952 if (VariableOperand == -1) {
4953 AddrMode.BaseOffs += ConstantOffset;
4954 if (matchAddr(AddrInst->getOperand(0), Depth + 1)) {
4955 if (!cast<GEPOperator>(AddrInst)->isInBounds())
4956 AddrMode.InBounds = false;
4957 return true;
4958 }
4959 AddrMode.BaseOffs -= ConstantOffset;
4960
4961 if (EnableGEPOffsetSplit && isa<GetElementPtrInst>(AddrInst) &&
4962 TLI.shouldConsiderGEPOffsetSplit() && Depth == 0 &&
4963 ConstantOffset > 0) {
4964 // Record GEPs with non-zero offsets as candidates for splitting in
4965 // the event that the offset cannot fit into the r+i addressing mode.
4966 // Simple and common case that only one GEP is used in calculating the
4967 // address for the memory access.
4968 Value *Base = AddrInst->getOperand(0);
4969 auto *BaseI = dyn_cast<Instruction>(Base);
4970 auto *GEP = cast<GetElementPtrInst>(AddrInst);
4971 if (isa<Argument>(Base) || isa<GlobalValue>(Base) ||
4972 (BaseI && !isa<CastInst>(BaseI) &&
4973 !isa<GetElementPtrInst>(BaseI))) {
4974 // Make sure the parent block allows inserting non-PHI instructions
4975 // before the terminator.
4976 BasicBlock *Parent = BaseI ? BaseI->getParent()
4977 : &GEP->getFunction()->getEntryBlock();
4978 if (!Parent->getTerminator()->isEHPad())
4979 LargeOffsetGEP = std::make_pair(GEP, ConstantOffset);
4980 }
4981 }
4982
4983 return false;
4984 }
4985
4986 // Save the valid addressing mode in case we can't match.
4987 ExtAddrMode BackupAddrMode = AddrMode;
4988 unsigned OldSize = AddrModeInsts.size();
4989
4990 // See if the scale and offset amount is valid for this target.
4991 AddrMode.BaseOffs += ConstantOffset;
4992 if (!cast<GEPOperator>(AddrInst)->isInBounds())
4993 AddrMode.InBounds = false;
4994
4995 // Match the base operand of the GEP.
4996 if (!matchAddr(AddrInst->getOperand(0), Depth + 1)) {
4997 // If it couldn't be matched, just stuff the value in a register.
4998 if (AddrMode.HasBaseReg) {
4999 AddrMode = BackupAddrMode;
5000 AddrModeInsts.resize(OldSize);
5001 return false;
5002 }
5003 AddrMode.HasBaseReg = true;
5004 AddrMode.BaseReg = AddrInst->getOperand(0);
5005 }
5006
5007 // Match the remaining variable portion of the GEP.
5008 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
5009 Depth)) {
5010 // If it couldn't be matched, try stuffing the base into a register
5011 // instead of matching it, and retrying the match of the scale.
5012 AddrMode = BackupAddrMode;
5013 AddrModeInsts.resize(OldSize);
5014 if (AddrMode.HasBaseReg)
5015 return false;
5016 AddrMode.HasBaseReg = true;
5017 AddrMode.BaseReg = AddrInst->getOperand(0);
5018 AddrMode.BaseOffs += ConstantOffset;
5019 if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
5020 VariableScale, Depth)) {
5021 // If even that didn't work, bail.
5022 AddrMode = BackupAddrMode;
5023 AddrModeInsts.resize(OldSize);
5024 return false;
5025 }
5026 }
5027
5028 return true;
5029 }
5030 case Instruction::SExt:
5031 case Instruction::ZExt: {
5032 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
5033 if (!Ext)
5034 return false;
5035
5036 // Try to move this ext out of the way of the addressing mode.
5037 // Ask for a method for doing so.
5038 TypePromotionHelper::Action TPH =
5039 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
5040 if (!TPH)
5041 return false;
5042
5043 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5044 TPT.getRestorationPoint();
5045 unsigned CreatedInstsCost = 0;
5046 unsigned ExtCost = !TLI.isExtFree(Ext);
5047 Value *PromotedOperand =
5048 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
5049 // SExt has been moved away.
5050 // Thus either it will be rematched later in the recursive calls or it is
5051 // gone. Anyway, we must not fold it into the addressing mode at this point.
5052 // E.g.,
5053 // op = add opnd, 1
5054 // idx = ext op
5055 // addr = gep base, idx
5056 // is now:
5057 // promotedOpnd = ext opnd <- no match here
5058 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
5059 // addr = gep base, op <- match
5060 if (MovedAway)
5061 *MovedAway = true;
5062
5063 assert(PromotedOperand &&
5064 "TypePromotionHelper should have filtered out those cases");
5065
5066 ExtAddrMode BackupAddrMode = AddrMode;
5067 unsigned OldSize = AddrModeInsts.size();
5068
5069 if (!matchAddr(PromotedOperand, Depth) ||
5070 // The total of the new cost is equal to the cost of the created
5071 // instructions.
5072 // The total of the old cost is equal to the cost of the extension plus
5073 // what we have saved in the addressing mode.
5074 !isPromotionProfitable(CreatedInstsCost,
5075 ExtCost + (AddrModeInsts.size() - OldSize),
5076 PromotedOperand)) {
5077 AddrMode = BackupAddrMode;
5078 AddrModeInsts.resize(OldSize);
5079 LLVM_DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
5080 TPT.rollback(LastKnownGood);
5081 return false;
5082 }
5083 return true;
5084 }
5085 }
5086 return false;
5087}
5088
5089/// If we can, try to add the value of 'Addr' into the current addressing mode.
5090/// If Addr can't be added to AddrMode this returns false and leaves AddrMode
5091/// unmodified. This assumes that Addr is either a pointer type or intptr_t
5092/// for the target.
5093///
5094bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
5095 // Start a transaction at this point that we will rollback if the matching
5096 // fails.
5097 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5098 TPT.getRestorationPoint();
5099 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
5100 if (CI->getValue().isSignedIntN(64)) {
5101 // Fold in immediates if legal for the target.
5102 AddrMode.BaseOffs += CI->getSExtValue();
5103 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
5104 return true;
5105 AddrMode.BaseOffs -= CI->getSExtValue();
5106 }
5107 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
5108 // If this is a global variable, try to fold it into the addressing mode.
5109 if (!AddrMode.BaseGV) {
5110 AddrMode.BaseGV = GV;
5111 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
5112 return true;
5113 AddrMode.BaseGV = nullptr;
5114 }
5115 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
5116 ExtAddrMode BackupAddrMode = AddrMode;
5117 unsigned OldSize = AddrModeInsts.size();
5118
5119 // Check to see if it is possible to fold this operation.
5120 bool MovedAway = false;
5121 if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
5122 // This instruction may have been moved away. If so, there is nothing
5123 // to check here.
5124 if (MovedAway)
5125 return true;
5126 // Okay, it's possible to fold this. Check to see if it is actually
5127 // *profitable* to do so. We use a simple cost model to avoid increasing
5128 // register pressure too much.
5129 if (I->hasOneUse() ||
5130 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
5131 AddrModeInsts.push_back(I);
5132 return true;
5133 }
5134
5135 // It isn't profitable to do this, roll back.
5136 AddrMode = BackupAddrMode;
5137 AddrModeInsts.resize(OldSize);
5138 TPT.rollback(LastKnownGood);
5139 }
5140 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
5141 if (matchOperationAddr(CE, CE->getOpcode(), Depth))
5142 return true;
5143 TPT.rollback(LastKnownGood);
5144 } else if (isa<ConstantPointerNull>(Addr)) {
5145 // Null pointer gets folded without affecting the addressing mode.
5146 return true;
5147 }
5148
5149 // Worse case, the target should support [reg] addressing modes. :)
5150 if (!