LLVM 24.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"
46#include "llvm/Config/llvm-config.h"
47#include "llvm/IR/Argument.h"
48#include "llvm/IR/Attributes.h"
49#include "llvm/IR/BasicBlock.h"
50#include "llvm/IR/CFG.h"
51#include "llvm/IR/Constant.h"
52#include "llvm/IR/Constants.h"
53#include "llvm/IR/CycleInfo.h"
54#include "llvm/IR/DataLayout.h"
55#include "llvm/IR/DebugInfo.h"
57#include "llvm/IR/Dominators.h"
58#include "llvm/IR/Function.h"
60#include "llvm/IR/GlobalValue.h"
62#include "llvm/IR/IRBuilder.h"
63#include "llvm/IR/InlineAsm.h"
64#include "llvm/IR/InstrTypes.h"
65#include "llvm/IR/Instruction.h"
68#include "llvm/IR/Intrinsics.h"
69#include "llvm/IR/IntrinsicsAArch64.h"
70#include "llvm/IR/LLVMContext.h"
71#include "llvm/IR/MDBuilder.h"
72#include "llvm/IR/Module.h"
73#include "llvm/IR/Operator.h"
76#include "llvm/IR/Statepoint.h"
77#include "llvm/IR/Type.h"
78#include "llvm/IR/Use.h"
79#include "llvm/IR/User.h"
80#include "llvm/IR/Value.h"
81#include "llvm/IR/ValueHandle.h"
82#include "llvm/IR/ValueMap.h"
84#include "llvm/Pass.h"
90#include "llvm/Support/Debug.h"
100#include <algorithm>
101#include <cassert>
102#include <cstdint>
103#include <iterator>
104#include <limits>
105#include <memory>
106#include <optional>
107#include <utility>
108#include <vector>
109
110using namespace llvm;
111using namespace llvm::PatternMatch;
112
113#define DEBUG_TYPE "codegenprepare"
114
115STATISTIC(NumBlocksElim, "Number of blocks eliminated");
116STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
117STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
118STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
119 "sunken Cmps");
120STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
121 "of sunken Casts");
122STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
123 "computations were sunk");
124STATISTIC(NumMemoryInstsPhiCreated,
125 "Number of phis created when address "
126 "computations were sunk to memory instructions");
127STATISTIC(NumMemoryInstsSelectCreated,
128 "Number of select created when address "
129 "computations were sunk to memory instructions");
130STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
131STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
132STATISTIC(NumAndsAdded,
133 "Number of and mask instructions added to form ext loads");
134STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized");
135STATISTIC(NumRetsDup, "Number of return instructions duplicated");
136STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
137STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
138STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
139
141 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
142 cl::desc("Disable branch optimizations in CodeGenPrepare"));
143
144static cl::opt<bool>
145 DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
146 cl::desc("Disable GC optimizations in CodeGenPrepare"));
147
148static cl::opt<bool>
149 DisableSelectToBranch("disable-cgp-select2branch", cl::Hidden,
150 cl::init(false),
151 cl::desc("Disable select to branch conversion."));
152
153static cl::opt<bool>
154 AddrSinkUsingGEPs("addr-sink-using-gep", cl::Hidden, cl::init(true),
155 cl::desc("Address sinking in CGP using GEPs."));
156
157static cl::opt<bool>
158 EnableAndCmpSinking("enable-andcmp-sinking", cl::Hidden, cl::init(true),
159 cl::desc("Enable sinking and/cmp into branches."));
160
162 "disable-cgp-store-extract", cl::Hidden, cl::init(false),
163 cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
164
166 "stress-cgp-store-extract", cl::Hidden, cl::init(false),
167 cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
168
170 "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
171 cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
172 "CodeGenPrepare"));
173
175 "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
176 cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
177 "optimization in CodeGenPrepare"));
178
180 "disable-preheader-prot", cl::Hidden, cl::init(false),
181 cl::desc("Disable protection against removing loop preheaders"));
182
184 "profile-guided-section-prefix", cl::Hidden, cl::init(true),
185 cl::desc("Use profile info to add section prefix for hot/cold functions"));
186
188 "profile-unknown-in-special-section", cl::Hidden,
189 cl::desc("In profiling mode like sampleFDO, if a function doesn't have "
190 "profile, we cannot tell the function is cold for sure because "
191 "it may be a function newly added without ever being sampled. "
192 "With the flag enabled, compiler can put such profile unknown "
193 "functions into a special section, so runtime system can choose "
194 "to handle it in a different way than .text section, to save "
195 "RAM for example. "));
196
198 "bbsections-guided-section-prefix", cl::Hidden, cl::init(true),
199 cl::desc("Use the basic-block-sections profile to determine the text "
200 "section prefix for hot functions. Functions with "
201 "basic-block-sections profile will be placed in `.text.hot` "
202 "regardless of their FDO profile info. Other functions won't be "
203 "impacted, i.e., their prefixes will be decided by FDO/sampleFDO "
204 "profiles."));
205
207 "cgp-freq-ratio-to-skip-merge", cl::Hidden, cl::init(2),
208 cl::desc("Skip merging empty blocks if (frequency of empty block) / "
209 "(frequency of destination block) is greater than this ratio"));
210
212 "force-split-store", cl::Hidden, cl::init(false),
213 cl::desc("Force store splitting no matter what the target query says."));
214
216 "cgp-type-promotion-merge", cl::Hidden,
217 cl::desc("Enable merging of redundant sexts when one is dominating"
218 " the other."),
219 cl::init(true));
220
222 "disable-complex-addr-modes", cl::Hidden, cl::init(false),
223 cl::desc("Disables combining addressing modes with different parts "
224 "in optimizeMemoryInst."));
225
226static cl::opt<bool>
227 AddrSinkNewPhis("addr-sink-new-phis", cl::Hidden, cl::init(false),
228 cl::desc("Allow creation of Phis in Address sinking."));
229
231 "addr-sink-new-select", cl::Hidden, cl::init(true),
232 cl::desc("Allow creation of selects in Address sinking."));
233
235 "addr-sink-combine-base-reg", cl::Hidden, cl::init(true),
236 cl::desc("Allow combining of BaseReg field in Address sinking."));
237
239 "addr-sink-combine-base-gv", cl::Hidden, cl::init(true),
240 cl::desc("Allow combining of BaseGV field in Address sinking."));
241
243 "addr-sink-combine-base-offs", cl::Hidden, cl::init(true),
244 cl::desc("Allow combining of BaseOffs field in Address sinking."));
245
247 "addr-sink-combine-scaled-reg", cl::Hidden, cl::init(true),
248 cl::desc("Allow combining of ScaledReg field in Address sinking."));
249
250static cl::opt<bool>
251 EnableGEPOffsetSplit("cgp-split-large-offset-gep", cl::Hidden,
252 cl::init(true),
253 cl::desc("Enable splitting large offset of GEP."));
254
256 "cgp-icmp-eq2icmp-st", cl::Hidden, cl::init(false),
257 cl::desc("Enable ICMP_EQ to ICMP_S(L|G)T conversion."));
258
259static cl::opt<bool>
260 VerifyBFIUpdates("cgp-verify-bfi-updates", cl::Hidden, cl::init(false),
261 cl::desc("Enable BFI update verification for "
262 "CodeGenPrepare."));
263
264static cl::opt<bool>
265 OptimizePhiTypes("cgp-optimize-phi-types", cl::Hidden, cl::init(true),
266 cl::desc("Enable converting phi types in CodeGenPrepare"));
267
269 HugeFuncThresholdInCGPP("cgpp-huge-func", cl::init(10000), cl::Hidden,
270 cl::desc("Least BB number of huge function."));
271
273 MaxAddressUsersToScan("cgp-max-address-users-to-scan", cl::init(100),
275 cl::desc("Max number of address users to look at"));
276
277static cl::opt<bool>
278 DisableDeletePHIs("disable-cgp-delete-phis", cl::Hidden, cl::init(false),
279 cl::desc("Disable elimination of dead PHI nodes."));
280
281namespace {
282
283enum ExtType {
284 ZeroExtension, // Zero extension has been seen.
285 SignExtension, // Sign extension has been seen.
286 BothExtension // This extension type is used if we saw sext after
287 // ZeroExtension had been set, or if we saw zext after
288 // SignExtension had been set. It makes the type
289 // information of a promoted instruction invalid.
290};
291
292enum ModifyDT {
293 NotModifyDT, // Not Modify any DT.
294 ModifyBBDT, // Modify the Basic Block Dominator Tree.
295 ModifyInstDT // Modify the Instruction Dominator in a Basic Block,
296 // This usually means we move/delete/insert instruction
297 // in a Basic Block. So we should re-iterate instructions
298 // in such Basic Block.
299};
300
301using SetOfInstrs = SmallPtrSet<Instruction *, 16>;
302using TypeIsSExt = PointerIntPair<Type *, 2, ExtType>;
303using InstrToOrigTy = DenseMap<Instruction *, TypeIsSExt>;
305using ValueToSExts = MapVector<Value *, SExts>;
306
307class TypePromotionTransaction;
308
309class CodeGenPrepare {
310 friend class CodeGenPrepareLegacyPass;
311 const TargetMachine *TM = nullptr;
312 const TargetSubtargetInfo *SubtargetInfo = nullptr;
313 const TargetLowering *TLI = nullptr;
314 const TargetRegisterInfo *TRI = nullptr;
315 const TargetTransformInfo *TTI = nullptr;
316 const BasicBlockSectionsProfileReader *BBSectionsProfileReader = nullptr;
317 const TargetLibraryInfo *TLInfo = nullptr;
318 DomTreeUpdater *DTU = nullptr;
319 LoopInfo *LI = nullptr;
320 BlockFrequencyInfo *BFI;
321 BranchProbabilityInfo *BPI;
322 ProfileSummaryInfo *PSI = nullptr;
323
324 /// As we scan instructions optimizing them, this is the next instruction
325 /// to optimize. Transforms that can invalidate this should update it.
326 BasicBlock::iterator CurInstIterator;
327
328 /// Keeps track of non-local addresses that have been sunk into a block.
329 /// This allows us to avoid inserting duplicate code for blocks with
330 /// multiple load/stores of the same address. The usage of WeakTrackingVH
331 /// enables SunkAddrs to be treated as a cache whose entries can be
332 /// invalidated if a sunken address computation has been erased.
333 ValueMap<Value *, WeakTrackingVH> SunkAddrs;
334
335 /// Keeps track of all instructions inserted for the current function.
336 SetOfInstrs InsertedInsts;
337
338 /// Keeps track of the type of the related instruction before their
339 /// promotion for the current function.
340 InstrToOrigTy PromotedInsts;
341
342 /// Keep track of instructions removed during promotion.
343 SetOfInstrs RemovedInsts;
344
345 /// Keep track of sext chains based on their initial value.
346 DenseMap<Value *, Instruction *> SeenChainsForSExt;
347
348 /// Keep track of GEPs accessing the same data structures such as structs or
349 /// arrays that are candidates to be split later because of their large
350 /// size.
351 MapVector<AssertingVH<Value>,
353 LargeOffsetGEPMap;
354
355 /// Keep track of new GEP base after splitting the GEPs having large offset.
356 SmallSet<AssertingVH<Value>, 2> NewGEPBases;
357
358 /// Map serial numbers to Large offset GEPs.
359 DenseMap<AssertingVH<GetElementPtrInst>, int> LargeOffsetGEPID;
360
361 /// Keep track of SExt promoted.
362 ValueToSExts ValToSExtendedUses;
363
364 /// True if the function has the OptSize attribute.
365 bool OptSize;
366
367 /// DataLayout for the Function being processed.
368 const DataLayout *DL = nullptr;
369
370public:
371 CodeGenPrepare() = default;
372 CodeGenPrepare(const TargetMachine *TM) : TM(TM){};
373 /// If encounter huge function, we need to limit the build time.
374 bool IsHugeFunc = false;
375
376 /// FreshBBs is like worklist, it collected the updated BBs which need
377 /// to be optimized again.
378 /// Note: Consider building time in this pass, when a BB updated, we need
379 /// to insert such BB into FreshBBs for huge function.
380 SmallPtrSet<BasicBlock *, 32> FreshBBs;
381
382 void releaseMemory() {
383 // Clear per function information.
384 InsertedInsts.clear();
385 PromotedInsts.clear();
386 FreshBBs.clear();
387 }
388
390
391private:
392 template <typename F>
393 void resetIteratorIfInvalidatedWhileCalling(BasicBlock *BB, F f) {
394 // Substituting can cause recursive simplifications, which can invalidate
395 // our iterator. Use a WeakTrackingVH to hold onto it in case this
396 // happens.
397 Value *CurValue = &*CurInstIterator;
398 WeakTrackingVH IterHandle(CurValue);
399
400 f();
401
402 // If the iterator instruction was recursively deleted, start over at the
403 // start of the block.
404 if (IterHandle != CurValue) {
405 CurInstIterator = BB->begin();
406 SunkAddrs.clear();
407 }
408 }
409
410 // Get the DominatorTree, updating it if necessary.
411 DominatorTree &getDT() { return DTU->getDomTree(); }
412
413 void removeAllAssertingVHReferences(Value *V);
414 bool eliminateAssumptions(Function &F);
415 bool eliminateFallThrough(Function &F);
416 bool eliminateMostlyEmptyBlocks(Function &F, bool &ResetLI);
417 BasicBlock *findDestBlockOfMergeableEmptyBlock(BasicBlock *BB);
418 bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
419 bool eliminateMostlyEmptyBlock(BasicBlock *BB);
420 bool isMergingEmptyBlockProfitable(BasicBlock *BB, BasicBlock *DestBB,
421 bool isPreheader);
422 bool makeBitReverse(Instruction &I);
423 bool optimizeBlock(BasicBlock &BB, ModifyDT &ModifiedDT);
424 bool optimizeInst(Instruction *I, ModifyDT &ModifiedDT);
425 bool optimizeMemoryInst(Instruction *MemoryInst, Value *Addr, Type *AccessTy,
426 unsigned AddrSpace);
427 bool optimizeGatherScatterInst(Instruction *MemoryInst, Value *Ptr);
428 bool optimizeMulWithOverflow(Instruction *I, bool IsSigned,
429 ModifyDT &ModifiedDT);
430 bool optimizeInlineAsmInst(CallInst *CS);
431 bool optimizeCallInst(CallInst *CI, ModifyDT &ModifiedDT);
432 bool optimizeExt(Instruction *&I);
433 bool optimizeExtUses(Instruction *I);
434 bool optimizeLoadExt(LoadInst *Load);
435 bool optimizeShiftInst(BinaryOperator *BO);
436 bool optimizeFunnelShift(IntrinsicInst *Fsh);
437 bool optimizeSelectInst(SelectInst *SI);
438 bool optimizeShuffleVectorInst(ShuffleVectorInst *SVI);
439 bool optimizeSwitchType(SwitchInst *SI);
440 bool optimizeSwitchPhiConstants(SwitchInst *SI);
441 bool optimizeSwitchInst(SwitchInst *SI);
442 bool optimizeExtractElementInst(Instruction *Inst);
443 bool dupRetToEnableTailCallOpts(BasicBlock *BB, ModifyDT &ModifiedDT);
444 bool fixupDbgVariableRecord(DbgVariableRecord &I);
445 bool fixupDbgVariableRecordsOnInst(Instruction &I);
446 bool placeDbgValues(Function &F);
447 bool placePseudoProbes(Function &F);
448 bool canFormExtLd(const SmallVectorImpl<Instruction *> &MovedExts,
449 LoadInst *&LI, Instruction *&Inst, bool HasPromoted);
450 bool tryToPromoteExts(TypePromotionTransaction &TPT,
451 const SmallVectorImpl<Instruction *> &Exts,
452 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
453 unsigned CreatedInstsCost = 0);
454 bool mergeSExts(Function &F);
455 bool splitLargeGEPOffsets();
456 bool optimizePhiType(PHINode *Inst, SmallPtrSetImpl<PHINode *> &Visited,
457 SmallPtrSetImpl<Instruction *> &DeletedInstrs);
458 bool optimizePhiTypes(Function &F);
459 bool performAddressTypePromotion(
460 Instruction *&Inst, bool AllowPromotionWithoutCommonHeader,
461 bool HasPromoted, TypePromotionTransaction &TPT,
462 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts);
463 bool splitBranchCondition(Function &F);
464 bool simplifyOffsetableRelocate(GCStatepointInst &I);
465
466 bool tryToSinkFreeOperands(Instruction *I);
467 bool replaceMathCmpWithIntrinsic(BinaryOperator *BO, Value *Arg0, Value *Arg1,
468 CmpInst *Cmp, Intrinsic::ID IID);
469 bool optimizeCmp(CmpInst *Cmp, ModifyDT &ModifiedDT);
470 bool optimizeURem(Instruction *Rem);
471 bool combineToUSubWithOverflow(CmpInst *Cmp, ModifyDT &ModifiedDT);
472 bool combineToUAddWithOverflow(CmpInst *Cmp, ModifyDT &ModifiedDT);
473 bool unfoldPowerOf2Test(CmpInst *Cmp);
474 void verifyBFIUpdates(Function &F);
475 bool _run(Function &F);
476};
477
478class CodeGenPrepareLegacyPass : public FunctionPass {
479public:
480 static char ID; // Pass identification, replacement for typeid
481
482 CodeGenPrepareLegacyPass() : FunctionPass(ID) {}
483
484 bool runOnFunction(Function &F) override;
485
486 StringRef getPassName() const override { return "CodeGen Prepare"; }
487
488 void getAnalysisUsage(AnalysisUsage &AU) const override {
489 // FIXME: When we can selectively preserve passes, preserve the domtree.
490 AU.addRequired<ProfileSummaryInfoWrapperPass>();
491 AU.addRequired<TargetLibraryInfoWrapperPass>();
492 AU.addRequired<TargetPassConfig>();
493 AU.addRequired<TargetTransformInfoWrapperPass>();
494 AU.addRequired<DominatorTreeWrapperPass>();
495 AU.addRequired<LoopInfoWrapperPass>();
496 AU.addRequired<BranchProbabilityInfoWrapperPass>();
497 AU.addRequired<BlockFrequencyInfoWrapperPass>();
498 AU.addUsedIfAvailable<BasicBlockSectionsProfileReaderWrapperPass>();
499 }
500};
501
502} // end anonymous namespace
503
504char CodeGenPrepareLegacyPass::ID = 0;
505
506bool CodeGenPrepareLegacyPass::runOnFunction(Function &F) {
507 if (skipFunction(F))
508 return false;
509 auto TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
510 CodeGenPrepare CGP(TM);
511 CGP.DL = &F.getDataLayout();
512 CGP.SubtargetInfo = TM->getSubtargetImpl(F);
513 CGP.TLI = CGP.SubtargetInfo->getTargetLowering();
514 CGP.TRI = CGP.SubtargetInfo->getRegisterInfo();
515 CGP.TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
516 CGP.TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
517 CGP.LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
518 CGP.BPI = &getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
519 CGP.BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
520 CGP.PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
521 auto BBSPRWP =
522 getAnalysisIfAvailable<BasicBlockSectionsProfileReaderWrapperPass>();
523 CGP.BBSectionsProfileReader = BBSPRWP ? &BBSPRWP->getBBSPR() : nullptr;
524 DomTreeUpdater DTUpdater(
525 &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
526 DomTreeUpdater::UpdateStrategy::Lazy);
527 CGP.DTU = &DTUpdater;
528
529 return CGP._run(F);
530}
531
532INITIALIZE_PASS_BEGIN(CodeGenPrepareLegacyPass, DEBUG_TYPE,
533 "Optimize for code generation", false, false)
541INITIALIZE_PASS_END(CodeGenPrepareLegacyPass, DEBUG_TYPE,
542 "Optimize for code generation", false, false)
543
545 return new CodeGenPrepareLegacyPass();
546}
547
550 CodeGenPrepare CGP(TM);
551
552 bool Changed = CGP.run(F, AM);
553 if (!Changed)
554 return PreservedAnalyses::all();
555
559 return PA;
560}
561
562bool CodeGenPrepare::run(Function &F, FunctionAnalysisManager &AM) {
563 DL = &F.getDataLayout();
564 SubtargetInfo = TM->getSubtargetImpl(F);
565 TLI = SubtargetInfo->getTargetLowering();
566 TRI = SubtargetInfo->getRegisterInfo();
567 TLInfo = &AM.getResult<TargetLibraryAnalysis>(F);
569 LI = &AM.getResult<LoopAnalysis>(F);
572 auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
573 PSI = MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
574 if (!PSI)
575 reportFatalUsageError("this pass requires the profile-summary module "
576 "analysis to be available");
577 BBSectionsProfileReader =
580 DomTreeUpdater::UpdateStrategy::Lazy);
581 DTU = &DTUpdater;
582 return _run(F);
583}
584
585bool CodeGenPrepare::_run(Function &F) {
586 bool EverMadeChange = false;
587
588 OptSize = F.hasOptSize();
589 // Use the basic-block-sections profile to promote hot functions to .text.hot
590 // if requested.
591 if (BBSectionsGuidedSectionPrefix && BBSectionsProfileReader &&
592 BBSectionsProfileReader->isFunctionHot(F.getName())) {
593 (void)F.setSectionPrefix("hot");
594 } else if (ProfileGuidedSectionPrefix) {
595 // The hot attribute overwrites profile count based hotness while profile
596 // counts based hotness overwrite the cold attribute.
597 // This is a conservative behabvior.
598 if (F.hasFnAttribute(Attribute::Hot) ||
599 PSI->isFunctionHotInCallGraph(&F, *BFI))
600 (void)F.setSectionPrefix("hot");
601 // If PSI shows this function is not hot, we will placed the function
602 // into unlikely section if (1) PSI shows this is a cold function, or
603 // (2) the function has a attribute of cold.
604 else if (PSI->isFunctionColdInCallGraph(&F, *BFI) ||
605 F.hasFnAttribute(Attribute::Cold))
606 (void)F.setSectionPrefix("unlikely");
607 else if (ProfileUnknownInSpecialSection && PSI->hasPartialSampleProfile() &&
608 PSI->isFunctionHotnessUnknown(F))
609 (void)F.setSectionPrefix("unknown");
610 }
611
612 /// This optimization identifies DIV instructions that can be
613 /// profitably bypassed and carried out with a shorter, faster divide.
614 if (!OptSize && !PSI->hasHugeWorkingSetSize() && TLI->isSlowDivBypassed()) {
615 const DenseMap<unsigned int, unsigned int> &BypassWidths =
617 BasicBlock *BB = &*F.begin();
618 while (BB != nullptr) {
619 // bypassSlowDivision may create new BBs, but we don't want to reapply the
620 // optimization to those blocks.
621 BasicBlock *Next = BB->getNextNode();
622 if (!llvm::shouldOptimizeForSize(BB, PSI, BFI))
623 EverMadeChange |= bypassSlowDivision(BB, BypassWidths, DTU, LI, BPI);
624 BB = Next;
625 }
626 }
627
628 // Get rid of @llvm.assume builtins before attempting to eliminate empty
629 // blocks, since there might be blocks that only contain @llvm.assume calls
630 // (plus arguments that we can get rid of).
631 EverMadeChange |= eliminateAssumptions(F);
632
633 auto resetLoopInfo = [this]() {
634 LI->releaseMemory();
635 LI->analyze(DTU->getDomTree());
636 };
637
638 // Eliminate blocks that contain only PHI nodes and an
639 // unconditional branch.
640 bool ResetLI = false;
641 EverMadeChange |= eliminateMostlyEmptyBlocks(F, ResetLI);
642 if (ResetLI)
643 resetLoopInfo();
644
646 EverMadeChange |= splitBranchCondition(F);
647
648 // Split some critical edges where one of the sources is an indirect branch,
649 // to help generate sane code for PHIs involving such edges.
650 bool Split = SplitIndirectBrCriticalEdges(F, /*IgnoreBlocksWithoutPHI=*/true,
651 BPI, BFI, DTU);
652 EverMadeChange |= Split;
653 if (Split)
654 resetLoopInfo();
655
656#ifndef NDEBUG
657 if (VerifyDomInfo)
658 assert(getDT().verify(DominatorTree::VerificationLevel::Fast) &&
659 "Incorrect DominatorTree updates in CGP");
660
661 if (VerifyLoopInfo)
662 LI->verify();
663#endif
664
665 // If we are optimzing huge function, we need to consider the build time.
666 // Because the basic algorithm's complex is near O(N!).
667 IsHugeFunc = F.size() > HugeFuncThresholdInCGPP;
668
669 bool MadeChange = true;
670 bool FuncIterated = false;
671 while (MadeChange) {
672 MadeChange = false;
673
674 // This is required because optimizeBlock() calls getDT() inside the loop
675 // below, which flushes pending updates and may delete dead blocks, leading
676 // to iterator invalidation.
677 DTU->flush();
678
679 for (BasicBlock &BB : llvm::make_early_inc_range(F)) {
680 if (FuncIterated && !FreshBBs.contains(&BB))
681 continue;
682
683 ModifyDT ModifiedDTOnIteration = ModifyDT::NotModifyDT;
684 bool Changed = optimizeBlock(BB, ModifiedDTOnIteration);
685
686 MadeChange |= Changed;
687 if (IsHugeFunc) {
688 // If the BB is updated, it may still has chance to be optimized.
689 // This usually happen at sink optimization.
690 // For example:
691 //
692 // bb0:
693 // %and = and i32 %a, 4
694 // %cmp = icmp eq i32 %and, 0
695 //
696 // If the %cmp sink to other BB, the %and will has chance to sink.
697 if (Changed)
698 FreshBBs.insert(&BB);
699 else if (FuncIterated)
700 FreshBBs.erase(&BB);
701 } else {
702 // For small/normal functions, we restart BB iteration if the dominator
703 // tree of the Function was changed.
704 if (ModifiedDTOnIteration != ModifyDT::NotModifyDT)
705 break;
706 }
707 }
708 // We have iterated all the BB in the (only work for huge) function.
709 FuncIterated = IsHugeFunc;
710
711 if (EnableTypePromotionMerge && !ValToSExtendedUses.empty())
712 MadeChange |= mergeSExts(F);
713 if (!LargeOffsetGEPMap.empty())
714 MadeChange |= splitLargeGEPOffsets();
715 MadeChange |= optimizePhiTypes(F);
716
717 if (MadeChange)
718 eliminateFallThrough(F);
719
720#ifndef NDEBUG
721 if (VerifyDomInfo)
722 assert(getDT().verify(DominatorTree::VerificationLevel::Fast) &&
723 "Incorrect DominatorTree updates in CGP");
724
725 if (VerifyLoopInfo)
726 LI->verify();
727#endif
728
729 // Really free removed instructions during promotion.
730 for (Instruction *I : RemovedInsts)
731 I->deleteValue();
732
733 EverMadeChange |= MadeChange;
734 SeenChainsForSExt.clear();
735 ValToSExtendedUses.clear();
736 RemovedInsts.clear();
737 LargeOffsetGEPMap.clear();
738 LargeOffsetGEPID.clear();
739 }
740
741 NewGEPBases.clear();
742 SunkAddrs.clear();
743
744 // LoopInfo is not needed anymore and ConstantFoldTerminator can break it.
745 LI = nullptr;
746
747 if (!DisableBranchOpts) {
748 MadeChange = false;
749 // Use a set vector to get deterministic iteration order. The order the
750 // blocks are removed may affect whether or not PHI nodes in successors
751 // are removed.
752 SmallSetVector<BasicBlock *, 8> WorkList;
753 for (BasicBlock &BB : F) {
755 MadeChange |= ConstantFoldTerminator(&BB, true, nullptr, DTU);
756 if (!MadeChange)
757 continue;
758
759 for (BasicBlock *Succ : Successors)
760 if (pred_empty(Succ))
761 WorkList.insert(Succ);
762 }
763
764 // Delete the dead blocks and any of their dead successors.
765 MadeChange |= !WorkList.empty();
766 while (!WorkList.empty()) {
767 BasicBlock *BB = WorkList.pop_back_val();
769
770 DeleteDeadBlock(BB, DTU);
771
772 for (BasicBlock *Succ : Successors)
773 if (pred_empty(Succ))
774 WorkList.insert(Succ);
775 }
776
777 // Flush pending DT updates in order to finalise deletion of dead blocks.
778 DTU->flush();
779
780 // Merge pairs of basic blocks with unconditional branches, connected by
781 // a single edge.
782 if (EverMadeChange || MadeChange)
783 MadeChange |= eliminateFallThrough(F);
784
785 EverMadeChange |= MadeChange;
786 }
787
788 if (!DisableGCOpts) {
790 for (BasicBlock &BB : F)
791 for (Instruction &I : BB)
792 if (auto *SP = dyn_cast<GCStatepointInst>(&I))
793 Statepoints.push_back(SP);
794 for (auto &I : Statepoints)
795 EverMadeChange |= simplifyOffsetableRelocate(*I);
796 }
797
798 // Do this last to clean up use-before-def scenarios introduced by other
799 // preparatory transforms.
800 EverMadeChange |= placeDbgValues(F);
801 EverMadeChange |= placePseudoProbes(F);
802
803#ifndef NDEBUG
805 verifyBFIUpdates(F);
806#endif
807
808 return EverMadeChange;
809}
810
811bool CodeGenPrepare::eliminateAssumptions(Function &F) {
812 bool MadeChange = false;
813 for (BasicBlock &BB : F) {
814 CurInstIterator = BB.begin();
815 while (CurInstIterator != BB.end()) {
816 Instruction *I = &*(CurInstIterator++);
817 if (auto *Assume = dyn_cast<AssumeInst>(I)) {
818 MadeChange = true;
819 Value *Operand = Assume->getOperand(0);
820 Assume->eraseFromParent();
821
822 resetIteratorIfInvalidatedWhileCalling(&BB, [&]() {
823 RecursivelyDeleteTriviallyDeadInstructions(Operand, TLInfo, nullptr);
824 });
825 }
826 }
827 }
828 return MadeChange;
829}
830
831/// An instruction is about to be deleted, so remove all references to it in our
832/// GEP-tracking data strcutures.
833void CodeGenPrepare::removeAllAssertingVHReferences(Value *V) {
834 LargeOffsetGEPMap.erase(V);
835 NewGEPBases.erase(V);
836
838 if (!GEP)
839 return;
840
841 LargeOffsetGEPID.erase(GEP);
842
843 auto VecI = LargeOffsetGEPMap.find(GEP->getPointerOperand());
844 if (VecI == LargeOffsetGEPMap.end())
845 return;
846
847 auto &GEPVector = VecI->second;
848 llvm::erase_if(GEPVector, [=](auto &Elt) { return Elt.first == GEP; });
849
850 if (GEPVector.empty())
851 LargeOffsetGEPMap.erase(VecI);
852}
853
854// Verify BFI has been updated correctly by recomputing BFI and comparing them.
855[[maybe_unused]] void CodeGenPrepare::verifyBFIUpdates(Function &F) {
856 DominatorTree NewDT(F);
857 CycleInfo NewCI;
858 NewCI.compute(F);
859 BranchProbabilityInfo NewBPI(F, NewCI, TLInfo);
860 BlockFrequencyInfo NewBFI(F, NewBPI, NewCI);
861 NewBFI.verifyMatch(*BFI);
862}
863
864/// Merge basic blocks which are connected by a single edge, where one of the
865/// basic blocks has a single successor pointing to the other basic block,
866/// which has a single predecessor.
867bool CodeGenPrepare::eliminateFallThrough(Function &F) {
868 bool Changed = false;
869 SmallPtrSet<BasicBlock *, 8> Preds;
870 // Scan all of the blocks in the function, except for the entry block.
871 for (auto &Block : llvm::drop_begin(F)) {
872 auto *BB = &Block;
873 if (DTU->isBBPendingDeletion(BB))
874 continue;
875 // If the destination block has a single pred, then this is a trivial
876 // edge, just collapse it.
877 BasicBlock *SinglePred = BB->getSinglePredecessor();
878
879 // Don't merge if BB's address is taken.
880 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken())
881 continue;
882
883 if (isa<UncondBrInst>(SinglePred->getTerminator())) {
884 Changed = true;
885 LLVM_DEBUG(dbgs() << "To merge:\n" << *BB << "\n\n\n");
886
887 // Merge BB into SinglePred and delete it.
888 MergeBlockIntoPredecessor(BB, DTU, LI);
889 Preds.insert(SinglePred);
890
891 if (IsHugeFunc) {
892 // Update FreshBBs to optimize the merged BB.
893 FreshBBs.insert(SinglePred);
894 FreshBBs.erase(BB);
895 }
896 }
897 }
898
899 // (Repeatedly) merging blocks into their predecessors can create redundant
900 // debug intrinsics.
901 for (auto *Pred : Preds)
902 if (!DTU->isBBPendingDeletion(Pred))
904
905 return Changed;
906}
907
908/// Find a destination block from BB if BB is mergeable empty block.
909BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) {
910 // If this block doesn't end with an uncond branch, ignore it.
911 UncondBrInst *BI = dyn_cast<UncondBrInst>(BB->getTerminator());
912 if (!BI)
913 return nullptr;
914
915 // If the instruction before the branch (skipping debug info) isn't a phi
916 // node, then other stuff is happening here.
918 if (BBI != BB->begin()) {
919 --BBI;
920 if (!isa<PHINode>(BBI))
921 return nullptr;
922 }
923
924 // Do not break infinite loops.
925 BasicBlock *DestBB = BI->getSuccessor();
926 if (DestBB == BB)
927 return nullptr;
928
929 if (!canMergeBlocks(BB, DestBB))
930 DestBB = nullptr;
931
932 return DestBB;
933}
934
935/// Eliminate blocks that contain only PHI nodes, debug info directives, and an
936/// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
937/// edges in ways that are non-optimal for isel. Start by eliminating these
938/// blocks so we can split them the way we want them.
939bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F, bool &ResetLI) {
940 SmallPtrSet<BasicBlock *, 16> Preheaders;
941 SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end());
942 while (!LoopList.empty()) {
943 Loop *L = LoopList.pop_back_val();
944 llvm::append_range(LoopList, *L);
945 if (BasicBlock *Preheader = L->getLoopPreheader())
946 Preheaders.insert(Preheader);
947 }
948
949 ResetLI = false;
950 bool MadeChange = false;
951 SmallPtrSet<PHINode *, 32> KnownNonDeadPHIs;
952 // Note that this intentionally skips the entry block.
953 for (auto &Block : llvm::drop_begin(F)) {
954 // Delete phi nodes that could block deleting other empty blocks.
956 MadeChange |= DeleteDeadPHIs(&Block, TLInfo, nullptr, &KnownNonDeadPHIs);
957 }
958
959 for (auto &Block : llvm::drop_begin(F)) {
960 auto *BB = &Block;
961 if (DTU->isBBPendingDeletion(BB))
962 continue;
963 BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB);
964 if (!DestBB ||
965 !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.count(BB)))
966 continue;
967
968 ResetLI |= eliminateMostlyEmptyBlock(BB);
969 MadeChange = true;
970 }
971 return MadeChange;
972}
973
974bool CodeGenPrepare::isMergingEmptyBlockProfitable(BasicBlock *BB,
975 BasicBlock *DestBB,
976 bool isPreheader) {
977 // Do not delete loop preheaders if doing so would create a critical edge.
978 // Loop preheaders can be good locations to spill registers. If the
979 // preheader is deleted and we create a critical edge, registers may be
980 // spilled in the loop body instead.
981 if (!DisablePreheaderProtect && isPreheader &&
982 !(BB->getSinglePredecessor() &&
984 return false;
985
986 // Skip merging if the block's successor is also a successor to any callbr
987 // that leads to this block.
988 // FIXME: Is this really needed? Is this a correctness issue?
989 for (BasicBlock *Pred : predecessors(BB)) {
990 if (isa<CallBrInst>(Pred->getTerminator()) &&
991 llvm::is_contained(successors(Pred), DestBB))
992 return false;
993 }
994
995 // Try to skip merging if the unique predecessor of BB is terminated by a
996 // switch or indirect branch instruction, and BB is used as an incoming block
997 // of PHIs in DestBB. In such case, merging BB and DestBB would cause ISel to
998 // add COPY instructions in the predecessor of BB instead of BB (if it is not
999 // merged). Note that the critical edge created by merging such blocks wont be
1000 // split in MachineSink because the jump table is not analyzable. By keeping
1001 // such empty block (BB), ISel will place COPY instructions in BB, not in the
1002 // predecessor of BB.
1003 BasicBlock *Pred = BB->getUniquePredecessor();
1004 if (!Pred || !(isa<SwitchInst>(Pred->getTerminator()) ||
1006 return true;
1007
1008 if (BB->getTerminator() != &*BB->getFirstNonPHIOrDbg())
1009 return true;
1010
1011 // We use a simple cost heuristic which determine skipping merging is
1012 // profitable if the cost of skipping merging is less than the cost of
1013 // merging : Cost(skipping merging) < Cost(merging BB), where the
1014 // Cost(skipping merging) is Freq(BB) * (Cost(Copy) + Cost(Branch)), and
1015 // the Cost(merging BB) is Freq(Pred) * Cost(Copy).
1016 // Assuming Cost(Copy) == Cost(Branch), we could simplify it to :
1017 // Freq(Pred) / Freq(BB) > 2.
1018 // Note that if there are multiple empty blocks sharing the same incoming
1019 // value for the PHIs in the DestBB, we consider them together. In such
1020 // case, Cost(merging BB) will be the sum of their frequencies.
1021
1022 if (!isa<PHINode>(DestBB->begin()))
1023 return true;
1024
1025 SmallPtrSet<BasicBlock *, 16> SameIncomingValueBBs;
1026
1027 // Find all other incoming blocks from which incoming values of all PHIs in
1028 // DestBB are the same as the ones from BB.
1029 for (BasicBlock *DestBBPred : predecessors(DestBB)) {
1030 if (DestBBPred == BB)
1031 continue;
1032
1033 if (llvm::all_of(DestBB->phis(), [&](const PHINode &DestPN) {
1034 return DestPN.getIncomingValueForBlock(BB) ==
1035 DestPN.getIncomingValueForBlock(DestBBPred);
1036 }))
1037 SameIncomingValueBBs.insert(DestBBPred);
1038 }
1039
1040 // See if all BB's incoming values are same as the value from Pred. In this
1041 // case, no reason to skip merging because COPYs are expected to be place in
1042 // Pred already.
1043 if (SameIncomingValueBBs.count(Pred))
1044 return true;
1045
1046 BlockFrequency PredFreq = BFI->getBlockFreq(Pred);
1047 BlockFrequency BBFreq = BFI->getBlockFreq(BB);
1048
1049 for (auto *SameValueBB : SameIncomingValueBBs)
1050 if (SameValueBB->getUniquePredecessor() == Pred &&
1051 DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB))
1052 BBFreq += BFI->getBlockFreq(SameValueBB);
1053
1054 std::optional<BlockFrequency> Limit = BBFreq.mul(FreqRatioToSkipMerge);
1055 return !Limit || PredFreq <= *Limit;
1056}
1057
1058/// Return true if we can merge BB into DestBB if there is a single
1059/// unconditional branch between them, and BB contains no other non-phi
1060/// instructions.
1061bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
1062 const BasicBlock *DestBB) const {
1063 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
1064 // the successor. If there are more complex condition (e.g. preheaders),
1065 // don't mess around with them.
1066 for (const PHINode &PN : BB->phis()) {
1067 for (const User *U : PN.users()) {
1068 const Instruction *UI = cast<Instruction>(U);
1069 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
1070 return false;
1071 // If User is inside DestBB block and it is a PHINode then check
1072 // incoming value. If incoming value is not from BB then this is
1073 // a complex condition (e.g. preheaders) we want to avoid here.
1074 if (UI->getParent() == DestBB) {
1075 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
1076 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
1077 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
1078 if (Insn && Insn->getParent() == BB &&
1079 Insn->getParent() != UPN->getIncomingBlock(I))
1080 return false;
1081 }
1082 }
1083 }
1084 }
1085
1086 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
1087 // and DestBB may have conflicting incoming values for the block. If so, we
1088 // can't merge the block.
1089 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
1090 if (!DestBBPN)
1091 return true; // no conflict.
1092
1093 // Collect the preds of BB.
1094 SmallPtrSet<const BasicBlock *, 16> BBPreds;
1095 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
1096 // It is faster to get preds from a PHI than with pred_iterator.
1097 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
1098 BBPreds.insert(BBPN->getIncomingBlock(i));
1099 } else {
1100 BBPreds.insert_range(predecessors(BB));
1101 }
1102
1103 // Walk the preds of DestBB.
1104 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
1105 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
1106 if (BBPreds.count(Pred)) { // Common predecessor?
1107 for (const PHINode &PN : DestBB->phis()) {
1108 const Value *V1 = PN.getIncomingValueForBlock(Pred);
1109 const Value *V2 = PN.getIncomingValueForBlock(BB);
1110
1111 // If V2 is a phi node in BB, look up what the mapped value will be.
1112 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
1113 if (V2PN->getParent() == BB)
1114 V2 = V2PN->getIncomingValueForBlock(Pred);
1115
1116 // If there is a conflict, bail out.
1117 if (V1 != V2)
1118 return false;
1119 }
1120 }
1121 }
1122
1123 return true;
1124}
1125
1126/// Replace all old uses with new ones, and push the updated BBs into FreshBBs.
1127static void replaceAllUsesWith(Value *Old, Value *New,
1129 bool IsHuge) {
1130 auto *OldI = dyn_cast<Instruction>(Old);
1131 if (OldI) {
1132 for (Value::user_iterator UI = OldI->user_begin(), E = OldI->user_end();
1133 UI != E; ++UI) {
1135 if (IsHuge)
1136 FreshBBs.insert(User->getParent());
1137 }
1138 }
1139 Old->replaceAllUsesWith(New);
1140}
1141
1142/// Eliminate a basic block that has only phi's and an unconditional branch in
1143/// it.
1144/// Indicate that the LoopInfo was modified only if it wasn't updated.
1145bool CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
1146 UncondBrInst *BI = cast<UncondBrInst>(BB->getTerminator());
1147 BasicBlock *DestBB = BI->getSuccessor();
1148
1149 LLVM_DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n"
1150 << *BB << *DestBB);
1151
1152 // If the destination block has a single pred, then this is a trivial edge,
1153 // just collapse it.
1154 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
1155 if (SinglePred != DestBB) {
1156 assert(SinglePred == BB &&
1157 "Single predecessor not the same as predecessor");
1158 // Merge DestBB into SinglePred/BB and delete it.
1159 MergeBlockIntoPredecessor(DestBB, DTU, LI);
1160 // Note: BB(=SinglePred) will not be deleted on this path.
1161 // DestBB(=its single successor) is the one that was deleted.
1162 LLVM_DEBUG(dbgs() << "AFTER:\n" << *SinglePred << "\n\n\n");
1163
1164 if (IsHugeFunc) {
1165 // Update FreshBBs to optimize the merged BB.
1166 FreshBBs.insert(SinglePred);
1167 FreshBBs.erase(DestBB);
1168 }
1169 return false;
1170 }
1171 }
1172
1173 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
1174 // to handle the new incoming edges it is about to have.
1175 for (PHINode &PN : DestBB->phis()) {
1176 // Remove the incoming value for BB, and remember it.
1177 Value *InVal = PN.removeIncomingValue(BB, false);
1178
1179 // Two options: either the InVal is a phi node defined in BB or it is some
1180 // value that dominates BB.
1181 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
1182 if (InValPhi && InValPhi->getParent() == BB) {
1183 // Add all of the input values of the input PHI as inputs of this phi.
1184 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
1185 PN.addIncoming(InValPhi->getIncomingValue(i),
1186 InValPhi->getIncomingBlock(i));
1187 } else {
1188 // Otherwise, add one instance of the dominating value for each edge that
1189 // we will be adding.
1190 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
1191 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
1192 PN.addIncoming(InVal, BBPN->getIncomingBlock(i));
1193 } else {
1194 for (BasicBlock *Pred : predecessors(BB))
1195 PN.addIncoming(InVal, Pred);
1196 }
1197 }
1198 }
1199
1200 // Preserve loop Metadata.
1201 if (BI->hasMetadata(LLVMContext::MD_loop)) {
1202 for (auto *Pred : predecessors(BB))
1203 Pred->getTerminator()->copyMetadata(*BI, LLVMContext::MD_loop);
1204 }
1205
1206 // The PHIs are now updated, change everything that refers to BB to use
1207 // DestBB and remove BB.
1209 SmallPtrSet<BasicBlock *, 8> SeenPreds;
1210 SmallPtrSet<BasicBlock *, 8> PredOfDestBB(llvm::from_range,
1211 predecessors(DestBB));
1212 for (auto *Pred : predecessors(BB)) {
1213 if (!PredOfDestBB.contains(Pred)) {
1214 if (SeenPreds.insert(Pred).second)
1215 DTUpdates.push_back({DominatorTree::Insert, Pred, DestBB});
1216 }
1217 }
1218 SeenPreds.clear();
1219 for (auto *Pred : predecessors(BB)) {
1220 if (SeenPreds.insert(Pred).second)
1221 DTUpdates.push_back({DominatorTree::Delete, Pred, BB});
1222 }
1223 DTUpdates.push_back({DominatorTree::Delete, BB, DestBB});
1224 BB->replaceAllUsesWith(DestBB);
1225 DTU->applyUpdates(DTUpdates);
1226 DTU->deleteBB(BB);
1227 ++NumBlocksElim;
1228
1229 LLVM_DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
1230 return true;
1231}
1232
1233// Computes a map of base pointer relocation instructions to corresponding
1234// derived pointer relocation instructions given a vector of all relocate calls
1236 const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
1238 &RelocateInstMap) {
1239 // Collect information in two maps: one primarily for locating the base object
1240 // while filling the second map; the second map is the final structure holding
1241 // a mapping between Base and corresponding Derived relocate calls
1243 for (auto *ThisRelocate : AllRelocateCalls) {
1244 auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
1245 ThisRelocate->getDerivedPtrIndex());
1246 RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
1247 }
1248 for (auto &Item : RelocateIdxMap) {
1249 std::pair<unsigned, unsigned> Key = Item.first;
1250 if (Key.first == Key.second)
1251 // Base relocation: nothing to insert
1252 continue;
1253
1254 GCRelocateInst *I = Item.second;
1255 auto BaseKey = std::make_pair(Key.first, Key.first);
1256
1257 // We're iterating over RelocateIdxMap so we cannot modify it.
1258 auto MaybeBase = RelocateIdxMap.find(BaseKey);
1259 if (MaybeBase == RelocateIdxMap.end())
1260 // TODO: We might want to insert a new base object relocate and gep off
1261 // that, if there are enough derived object relocates.
1262 continue;
1263
1264 RelocateInstMap[MaybeBase->second].push_back(I);
1265 }
1266}
1267
1268// Accepts a GEP and extracts the operands into a vector provided they're all
1269// small integer constants
1271 SmallVectorImpl<Value *> &OffsetV) {
1272 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
1273 // Only accept small constant integer operands
1274 auto *Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
1275 if (!Op || Op->getZExtValue() > 20)
1276 return false;
1277 }
1278
1279 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
1280 OffsetV.push_back(GEP->getOperand(i));
1281 return true;
1282}
1283
1284// Takes a RelocatedBase (base pointer relocation instruction) and Targets to
1285// replace, computes a replacement, and affects it.
1286static bool
1288 const SmallVectorImpl<GCRelocateInst *> &Targets) {
1289 bool MadeChange = false;
1290 // We must ensure the relocation of derived pointer is defined after
1291 // relocation of base pointer. If we find a relocation corresponding to base
1292 // defined earlier than relocation of base then we move relocation of base
1293 // right before found relocation. We consider only relocation in the same
1294 // basic block as relocation of base. Relocations from other basic block will
1295 // be skipped by optimization and we do not care about them.
1296 for (auto R = RelocatedBase->getParent()->getFirstInsertionPt();
1297 &*R != RelocatedBase; ++R)
1298 if (auto *RI = dyn_cast<GCRelocateInst>(R))
1299 if (RI->getStatepoint() == RelocatedBase->getStatepoint())
1300 if (RI->getBasePtrIndex() == RelocatedBase->getBasePtrIndex()) {
1301 RelocatedBase->moveBefore(RI->getIterator());
1302 MadeChange = true;
1303 break;
1304 }
1305
1306 for (GCRelocateInst *ToReplace : Targets) {
1307 assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&
1308 "Not relocating a derived object of the original base object");
1309 if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
1310 // A duplicate relocate call. TODO: coalesce duplicates.
1311 continue;
1312 }
1313
1314 if (RelocatedBase->getParent() != ToReplace->getParent()) {
1315 // Base and derived relocates are in different basic blocks.
1316 // In this case transform is only valid when base dominates derived
1317 // relocate. However it would be too expensive to check dominance
1318 // for each such relocate, so we skip the whole transformation.
1319 continue;
1320 }
1321
1322 Value *Base = ToReplace->getBasePtr();
1323 auto *Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
1324 if (!Derived || Derived->getPointerOperand() != Base)
1325 continue;
1326
1328 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
1329 continue;
1330
1331 // Create a Builder and replace the target callsite with a gep
1332 assert(RelocatedBase->getNextNode() &&
1333 "Should always have one since it's not a terminator");
1334
1335 // Insert after RelocatedBase
1336 IRBuilder<> Builder(RelocatedBase->getNextNode());
1337 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
1338
1339 // If gc_relocate does not match the actual type, cast it to the right type.
1340 // In theory, there must be a bitcast after gc_relocate if the type does not
1341 // match, and we should reuse it to get the derived pointer. But it could be
1342 // cases like this:
1343 // bb1:
1344 // ...
1345 // %g1 = call coldcc i8 addrspace(1)*
1346 // @llvm.experimental.gc.relocate.p1i8(...) br label %merge
1347 //
1348 // bb2:
1349 // ...
1350 // %g2 = call coldcc i8 addrspace(1)*
1351 // @llvm.experimental.gc.relocate.p1i8(...) br label %merge
1352 //
1353 // merge:
1354 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
1355 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
1356 //
1357 // In this case, we can not find the bitcast any more. So we insert a new
1358 // bitcast no matter there is already one or not. In this way, we can handle
1359 // all cases, and the extra bitcast should be optimized away in later
1360 // passes.
1361 Value *ActualRelocatedBase = RelocatedBase;
1362 if (RelocatedBase->getType() != Base->getType()) {
1363 ActualRelocatedBase =
1364 Builder.CreateBitCast(RelocatedBase, Base->getType());
1365 }
1366 Value *Replacement =
1367 Builder.CreateGEP(Derived->getSourceElementType(), ActualRelocatedBase,
1368 ArrayRef(OffsetV));
1369 Replacement->takeName(ToReplace);
1370 // If the newly generated derived pointer's type does not match the original
1371 // derived pointer's type, cast the new derived pointer to match it. Same
1372 // reasoning as above.
1373 Value *ActualReplacement = Replacement;
1374 if (Replacement->getType() != ToReplace->getType()) {
1375 ActualReplacement =
1376 Builder.CreateBitCast(Replacement, ToReplace->getType());
1377 }
1378 ToReplace->replaceAllUsesWith(ActualReplacement);
1379 ToReplace->eraseFromParent();
1380
1381 MadeChange = true;
1382 }
1383 return MadeChange;
1384}
1385
1386// Turns this:
1387//
1388// %base = ...
1389// %ptr = gep %base + 15
1390// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1391// %base' = relocate(%tok, i32 4, i32 4)
1392// %ptr' = relocate(%tok, i32 4, i32 5)
1393// %val = load %ptr'
1394//
1395// into this:
1396//
1397// %base = ...
1398// %ptr = gep %base + 15
1399// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1400// %base' = gc.relocate(%tok, i32 4, i32 4)
1401// %ptr' = gep %base' + 15
1402// %val = load %ptr'
1403bool CodeGenPrepare::simplifyOffsetableRelocate(GCStatepointInst &I) {
1404 bool MadeChange = false;
1405 SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
1406 for (auto *U : I.users())
1407 if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
1408 // Collect all the relocate calls associated with a statepoint
1409 AllRelocateCalls.push_back(Relocate);
1410
1411 // We need at least one base pointer relocation + one derived pointer
1412 // relocation to mangle
1413 if (AllRelocateCalls.size() < 2)
1414 return false;
1415
1416 // RelocateInstMap is a mapping from the base relocate instruction to the
1417 // corresponding derived relocate instructions
1418 MapVector<GCRelocateInst *, SmallVector<GCRelocateInst *, 0>> RelocateInstMap;
1419 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
1420 if (RelocateInstMap.empty())
1421 return false;
1422
1423 for (auto &Item : RelocateInstMap)
1424 // Item.first is the RelocatedBase to offset against
1425 // Item.second is the vector of Targets to replace
1426 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
1427 return MadeChange;
1428}
1429
1430/// Sink the specified cast instruction into its user blocks.
1431static bool SinkCast(CastInst *CI) {
1432 BasicBlock *DefBB = CI->getParent();
1433
1434 /// InsertedCasts - Only insert a cast in each block once.
1436
1437 bool MadeChange = false;
1438 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
1439 UI != E;) {
1440 Use &TheUse = UI.getUse();
1442
1443 // Figure out which BB this cast is used in. For PHI's this is the
1444 // appropriate predecessor block.
1445 BasicBlock *UserBB = User->getParent();
1446 if (PHINode *PN = dyn_cast<PHINode>(User)) {
1447 UserBB = PN->getIncomingBlock(TheUse);
1448 }
1449
1450 // Preincrement use iterator so we don't invalidate it.
1451 ++UI;
1452
1453 // The first insertion point of a block containing an EH pad is after the
1454 // pad. If the pad is the user, we cannot sink the cast past the pad.
1455 if (User->isEHPad())
1456 continue;
1457
1458 // If the block selected to receive the cast is an EH pad that does not
1459 // allow non-PHI instructions before the terminator, we can't sink the
1460 // cast.
1461 if (UserBB->getTerminator()->isEHPad())
1462 continue;
1463
1464 // If this user is in the same block as the cast, don't change the cast.
1465 if (UserBB == DefBB)
1466 continue;
1467
1468 // If we have already inserted a cast into this block, use it.
1469 CastInst *&InsertedCast = InsertedCasts[UserBB];
1470
1471 if (!InsertedCast) {
1472 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1473 assert(InsertPt != UserBB->end());
1474 InsertedCast = cast<CastInst>(CI->clone());
1475 InsertedCast->insertBefore(*UserBB, InsertPt);
1476 }
1477
1478 // Replace a use of the cast with a use of the new cast.
1479 TheUse = InsertedCast;
1480 MadeChange = true;
1481 ++NumCastUses;
1482 }
1483
1484 // If we removed all uses, nuke the cast.
1485 if (CI->use_empty()) {
1486 salvageDebugInfo(*CI);
1487 CI->eraseFromParent();
1488 MadeChange = true;
1489 }
1490
1491 return MadeChange;
1492}
1493
1494/// Hoists bitcasts to the source block to reduce register pressure
1495static bool optimizeBitCast(BitCastInst *BCI, const TargetLowering &TLI,
1496 const DataLayout &DL) {
1497 auto *SrcInst = dyn_cast<Instruction>(BCI->getOperand(0));
1498 if (!SrcInst || SrcInst->getParent() == BCI->getParent() ||
1499 SrcInst->isTerminator())
1500 return false;
1501
1502 Type *DestTy = BCI->getType();
1503 Type *SrcTy = SrcInst->getType();
1504 EVT SrcVT = TLI.getValueType(DL, SrcTy);
1505 EVT DestVT = TLI.getValueType(DL, DestTy);
1506
1507 // Bail out on scalable vectors and illegal destination types
1508 if (SrcVT.isScalableVector() || DestVT.isScalableVector())
1509 return false;
1510
1511 // Only hoist if it reduces physical register count
1512 if (TLI.getNumRegisters(BCI->getContext(), SrcVT) <=
1513 TLI.getNumRegisters(BCI->getContext(), DestVT))
1514 return false;
1515
1516 // Block large or cross-domain scalars to prevent spills and broken atomics.
1517 bool IsCrossDomain = DestTy->isFPOrFPVectorTy() != SrcTy->isFPOrFPVectorTy();
1518
1519 // A scalar is large if it requires more than one native register.
1520 unsigned NativeWidth = DL.getPointerSizeInBits();
1521 bool IsLargeScalar =
1522 !DestTy->isVectorTy() &&
1523 DL.getTypeSizeInBits(DestTy).getFixedValue() > NativeWidth;
1524
1525 if (IsCrossDomain || IsLargeScalar)
1526 return false;
1527
1528 // Hoist the bitcast
1529 BasicBlock *SrcBB = SrcInst->getParent();
1530 auto InsertPt = isa<PHINode>(SrcInst) ? SrcBB->getFirstInsertionPt()
1531 : std::next(SrcInst->getIterator());
1532 BCI->moveBefore(*SrcBB, InsertPt);
1533
1534 return true;
1535}
1536
1537/// If the specified cast instruction is a noop copy (e.g. it's casting from
1538/// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
1539/// reduce the number of virtual registers that must be created and coalesced.
1540///
1541/// Return true if any changes are made.
1543 const DataLayout &DL) {
1544 // Sink only "cheap" (or nop) address-space casts. This is a weaker condition
1545 // than sinking only nop casts, but is helpful on some platforms.
1546 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(CI)) {
1547 if (!TLI.isFreeAddrSpaceCast(ASC->getSrcAddressSpace(),
1548 ASC->getDestAddressSpace()))
1549 return false;
1550 }
1551
1552 // If this is a noop copy,
1553 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
1554 EVT DstVT = TLI.getValueType(DL, CI->getType());
1555
1556 // This is an fp<->int conversion?
1557 if (SrcVT.isInteger() != DstVT.isInteger())
1558 return false;
1559
1560 // If this is an extension, it will be a zero or sign extension, which
1561 // isn't a noop.
1562 if (SrcVT.bitsLT(DstVT))
1563 return false;
1564
1565 // If these values will be promoted, find out what they will be promoted
1566 // to. This helps us consider truncates on PPC as noop copies when they
1567 // are.
1568 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
1570 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
1571 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
1573 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
1574
1575 // If, after promotion, these are the same types, this is a noop copy.
1576 if (SrcVT != DstVT)
1577 return false;
1578
1579 return SinkCast(CI);
1580}
1581
1582// Match a simple increment by constant operation. Note that if a sub is
1583// matched, the step is negated (as if the step had been canonicalized to
1584// an add, even though we leave the instruction alone.)
1585static bool matchIncrement(const Instruction *IVInc, Instruction *&LHS,
1586 Constant *&Step) {
1587 if (match(IVInc, m_Add(m_Instruction(LHS), m_Constant(Step))) ||
1589 m_Instruction(LHS), m_Constant(Step)))))
1590 return true;
1591 if (match(IVInc, m_Sub(m_Instruction(LHS), m_Constant(Step))) ||
1593 m_Instruction(LHS), m_Constant(Step))))) {
1594 Step = ConstantExpr::getNeg(Step);
1595 return true;
1596 }
1597 return false;
1598}
1599
1600/// If given \p PN is an inductive variable with value IVInc coming from the
1601/// backedge, and on each iteration it gets increased by Step, return pair
1602/// <IVInc, Step>. Otherwise, return std::nullopt.
1603static std::optional<std::pair<Instruction *, Constant *>>
1604getIVIncrement(const PHINode *PN, const LoopInfo *LI) {
1605 const Loop *L = LI->getLoopFor(PN->getParent());
1606 if (!L || L->getHeader() != PN->getParent() || !L->getLoopLatch())
1607 return std::nullopt;
1608 auto *IVInc =
1609 dyn_cast<Instruction>(PN->getIncomingValueForBlock(L->getLoopLatch()));
1610 if (!IVInc || LI->getLoopFor(IVInc->getParent()) != L)
1611 return std::nullopt;
1612 Instruction *LHS = nullptr;
1613 Constant *Step = nullptr;
1614 if (matchIncrement(IVInc, LHS, Step) && LHS == PN)
1615 return std::make_pair(IVInc, Step);
1616 return std::nullopt;
1617}
1618
1619static bool isIVIncrement(const Value *V, const LoopInfo *LI) {
1620 auto *I = dyn_cast<Instruction>(V);
1621 if (!I)
1622 return false;
1623 Instruction *LHS = nullptr;
1624 Constant *Step = nullptr;
1625 if (!matchIncrement(I, LHS, Step))
1626 return false;
1627 if (auto *PN = dyn_cast<PHINode>(LHS))
1628 if (auto IVInc = getIVIncrement(PN, LI))
1629 return IVInc->first == I;
1630 return false;
1631}
1632
1633bool CodeGenPrepare::replaceMathCmpWithIntrinsic(BinaryOperator *BO,
1634 Value *Arg0, Value *Arg1,
1635 CmpInst *Cmp,
1636 Intrinsic::ID IID) {
1637 auto IsReplacableIVIncrement = [this, &Cmp](BinaryOperator *BO) {
1638 if (!isIVIncrement(BO, LI))
1639 return false;
1640 const Loop *L = LI->getLoopFor(BO->getParent());
1641 assert(L && "L should not be null after isIVIncrement()");
1642 // Do not risk on moving increment into a child loop.
1643 if (LI->getLoopFor(Cmp->getParent()) != L)
1644 return false;
1645
1646 // Finally, we need to ensure that the insert point will dominate all
1647 // existing uses of the increment.
1648
1649 auto &DT = getDT();
1650 if (DT.dominates(Cmp->getParent(), BO->getParent()))
1651 // If we're moving up the dom tree, all uses are trivially dominated.
1652 // (This is the common case for code produced by LSR.)
1653 return true;
1654
1655 // Otherwise, special case the single use in the phi recurrence.
1656 return BO->hasOneUse() && DT.dominates(Cmp->getParent(), L->getLoopLatch());
1657 };
1658 if (BO->getParent() != Cmp->getParent() && !IsReplacableIVIncrement(BO)) {
1659 // We used to use a dominator tree here to allow multi-block optimization.
1660 // But that was problematic because:
1661 // 1. It could cause a perf regression by hoisting the math op into the
1662 // critical path.
1663 // 2. It could cause a perf regression by creating a value that was live
1664 // across multiple blocks and increasing register pressure.
1665 // 3. Use of a dominator tree could cause large compile-time regression.
1666 // This is because we recompute the DT on every change in the main CGP
1667 // run-loop. The recomputing is probably unnecessary in many cases, so if
1668 // that was fixed, using a DT here would be ok.
1669 //
1670 // There is one important particular case we still want to handle: if BO is
1671 // the IV increment. Important properties that make it profitable:
1672 // - We can speculate IV increment anywhere in the loop (as long as the
1673 // indvar Phi is its only user);
1674 // - Upon computing Cmp, we effectively compute something equivalent to the
1675 // IV increment (despite it loops differently in the IR). So moving it up
1676 // to the cmp point does not really increase register pressure.
1677 return false;
1678 }
1679
1680 // We allow matching the canonical IR (add X, C) back to (usubo X, -C).
1681 if (BO->getOpcode() == Instruction::Add &&
1682 IID == Intrinsic::usub_with_overflow) {
1683 assert(isa<Constant>(Arg1) && "Unexpected input for usubo");
1685 }
1686
1687 // Insert at the first instruction of the pair.
1688 Instruction *InsertPt = nullptr;
1689 for (Instruction &Iter : *Cmp->getParent()) {
1690 // If BO is an XOR, it is not guaranteed that it comes after both inputs to
1691 // the overflow intrinsic are defined.
1692 if ((BO->getOpcode() != Instruction::Xor && &Iter == BO) || &Iter == Cmp) {
1693 InsertPt = &Iter;
1694 break;
1695 }
1696 }
1697 assert(InsertPt != nullptr && "Parent block did not contain cmp or binop");
1698
1699 IRBuilder<> Builder(InsertPt);
1700 Value *MathOV = Builder.CreateBinaryIntrinsic(IID, Arg0, Arg1);
1701 if (BO->getOpcode() != Instruction::Xor) {
1702 Value *Math = Builder.CreateExtractValue(MathOV, 0, "math");
1703 replaceAllUsesWith(BO, Math, FreshBBs, IsHugeFunc);
1704 } else
1705 assert(BO->hasOneUse() &&
1706 "Patterns with XOr should use the BO only in the compare");
1707 Value *OV = Builder.CreateExtractValue(MathOV, 1, "ov");
1708 replaceAllUsesWith(Cmp, OV, FreshBBs, IsHugeFunc);
1709 Cmp->eraseFromParent();
1710 BO->eraseFromParent();
1711 return true;
1712}
1713
1714/// Match special-case patterns that check for unsigned add overflow.
1716 BinaryOperator *&Add) {
1717 // Add = add A, 1; Cmp = icmp eq A,-1 (overflow if A is max val)
1718 // Add = add A,-1; Cmp = icmp ne A, 0 (overflow if A is non-zero)
1719 Value *A = Cmp->getOperand(0), *B = Cmp->getOperand(1);
1720
1721 // We are not expecting non-canonical/degenerate code. Just bail out.
1722 if (isa<Constant>(A))
1723 return false;
1724
1725 ICmpInst::Predicate Pred = Cmp->getPredicate();
1726 if (Pred == ICmpInst::ICMP_EQ && match(B, m_AllOnes()))
1727 B = ConstantInt::get(B->getType(), 1);
1728 else if (Pred == ICmpInst::ICMP_NE && match(B, m_ZeroInt()))
1729 B = Constant::getAllOnesValue(B->getType());
1730 else
1731 return false;
1732
1733 // Check the users of the variable operand of the compare looking for an add
1734 // with the adjusted constant.
1735 for (User *U : A->users()) {
1736 if (match(U, m_Add(m_Specific(A), m_Specific(B)))) {
1738 return true;
1739 }
1740 }
1741 return false;
1742}
1743
1744/// Try to combine the compare into a call to the llvm.uadd.with.overflow
1745/// intrinsic. Return true if any changes were made.
1746bool CodeGenPrepare::combineToUAddWithOverflow(CmpInst *Cmp,
1747 ModifyDT &ModifiedDT) {
1748 bool EdgeCase = false;
1749 Value *A, *B;
1750 BinaryOperator *Add;
1751 if (!match(Cmp, m_UAddWithOverflow(m_Value(A), m_Value(B), m_BinOp(Add)))) {
1753 return false;
1754 // Set A and B in case we match matchUAddWithOverflowConstantEdgeCases.
1755 A = Add->getOperand(0);
1756 B = Add->getOperand(1);
1757 EdgeCase = true;
1758 }
1759
1761 TLI->getValueType(*DL, Add->getType()),
1762 Add->hasNUsesOrMore(EdgeCase ? 1 : 2)))
1763 return false;
1764
1765 // We don't want to move around uses of condition values this late, so we
1766 // check if it is legal to create the call to the intrinsic in the basic
1767 // block containing the icmp.
1768 if (Add->getParent() != Cmp->getParent() && !Add->hasOneUse())
1769 return false;
1770
1771 if (!replaceMathCmpWithIntrinsic(Add, A, B, Cmp,
1772 Intrinsic::uadd_with_overflow))
1773 return false;
1774
1775 // Reset callers - do not crash by iterating over a dead instruction.
1776 ModifiedDT = ModifyDT::ModifyInstDT;
1777 return true;
1778}
1779
1780bool CodeGenPrepare::combineToUSubWithOverflow(CmpInst *Cmp,
1781 ModifyDT &ModifiedDT) {
1782 // We are not expecting non-canonical/degenerate code. Just bail out.
1783 Value *A = Cmp->getOperand(0), *B = Cmp->getOperand(1);
1784 if (isa<Constant>(A) && isa<Constant>(B))
1785 return false;
1786
1787 // Convert (A u> B) to (A u< B) to simplify pattern matching.
1788 ICmpInst::Predicate Pred = Cmp->getPredicate();
1789 if (Pred == ICmpInst::ICMP_UGT) {
1790 std::swap(A, B);
1791 Pred = ICmpInst::ICMP_ULT;
1792 }
1793 // Convert special-case: (A == 0) is the same as (A u< 1).
1794 if (Pred == ICmpInst::ICMP_EQ && match(B, m_ZeroInt())) {
1795 B = ConstantInt::get(B->getType(), 1);
1796 Pred = ICmpInst::ICMP_ULT;
1797 }
1798 // Convert special-case: (A != 0) is the same as (0 u< A).
1799 if (Pred == ICmpInst::ICMP_NE && match(B, m_ZeroInt())) {
1800 std::swap(A, B);
1801 Pred = ICmpInst::ICMP_ULT;
1802 }
1803 if (Pred != ICmpInst::ICMP_ULT)
1804 return false;
1805
1806 // Walk the users of a variable operand of a compare looking for a subtract or
1807 // add with that same operand. Also match the 2nd operand of the compare to
1808 // the add/sub, but that may be a negated constant operand of an add.
1809 Value *CmpVariableOperand = isa<Constant>(A) ? B : A;
1810 BinaryOperator *Sub = nullptr;
1811 for (User *U : CmpVariableOperand->users()) {
1812 // A - B, A u< B --> usubo(A, B)
1813 if (match(U, m_Sub(m_Specific(A), m_Specific(B)))) {
1815 break;
1816 }
1817
1818 // A + (-C), A u< C (canonicalized form of (sub A, C))
1819 const APInt *CmpC, *AddC;
1820 if (match(U, m_Add(m_Specific(A), m_APInt(AddC))) &&
1821 match(B, m_APInt(CmpC)) && *AddC == -(*CmpC)) {
1823 break;
1824 }
1825 }
1826 if (!Sub)
1827 return false;
1828
1830 TLI->getValueType(*DL, Sub->getType()),
1831 Sub->hasNUsesOrMore(1)))
1832 return false;
1833
1834 // We don't want to move around uses of condition values this late, so we
1835 // check if it is legal to create the call to the intrinsic in the basic
1836 // block containing the icmp.
1837 if (Sub->getParent() != Cmp->getParent() && !Sub->hasOneUse())
1838 return false;
1839
1840 if (!replaceMathCmpWithIntrinsic(Sub, Sub->getOperand(0), Sub->getOperand(1),
1841 Cmp, Intrinsic::usub_with_overflow))
1842 return false;
1843
1844 // Reset callers - do not crash by iterating over a dead instruction.
1845 ModifiedDT = ModifyDT::ModifyInstDT;
1846 return true;
1847}
1848
1849// Decanonicalizes icmp+ctpop power-of-two test if ctpop is slow.
1850// The same transformation exists in DAG combiner, but we repeat it here because
1851// DAG builder can break the pattern by moving icmp into a successor block.
1852bool CodeGenPrepare::unfoldPowerOf2Test(CmpInst *Cmp) {
1853 CmpPredicate Pred;
1854 Value *X;
1855 const APInt *C;
1856
1857 // (icmp (ctpop x), c)
1858 if (!match(Cmp, m_ICmp(Pred, m_Ctpop(m_Value(X)), m_APIntAllowPoison(C))))
1859 return false;
1860
1861 // We're only interested in "is power of 2 [or zero]" patterns.
1862 bool IsStrictlyPowerOf2Test = ICmpInst::isEquality(Pred) && *C == 1;
1863 bool IsPowerOf2OrZeroTest = (Pred == CmpInst::ICMP_ULT && *C == 2) ||
1864 (Pred == CmpInst::ICMP_UGT && *C == 1);
1865 if (!IsStrictlyPowerOf2Test && !IsPowerOf2OrZeroTest)
1866 return false;
1867
1868 // Some targets have better codegen for `ctpop(x) u</u>= 2/1`than for
1869 // `ctpop(x) ==/!= 1`. If ctpop is fast, only try changing the comparison,
1870 // and otherwise expand ctpop into a few simple instructions.
1871 Type *OpTy = X->getType();
1872 if (TLI->isCtpopFast(TLI->getValueType(*DL, OpTy))) {
1873 // Look for `ctpop(x) ==/!= 1`, where `ctpop(x)` is known to be non-zero.
1874 if (!IsStrictlyPowerOf2Test || !isKnownNonZero(Cmp->getOperand(0), *DL))
1875 return false;
1876
1877 // ctpop(x) == 1 -> ctpop(x) u< 2
1878 // ctpop(x) != 1 -> ctpop(x) u> 1
1879 if (Pred == ICmpInst::ICMP_EQ) {
1880 Cmp->setOperand(1, ConstantInt::get(OpTy, 2));
1881 Cmp->setPredicate(ICmpInst::ICMP_ULT);
1882 } else {
1883 Cmp->setPredicate(ICmpInst::ICMP_UGT);
1884 }
1885 return true;
1886 }
1887
1888 Value *NewCmp;
1889 if (IsPowerOf2OrZeroTest ||
1890 (IsStrictlyPowerOf2Test && isKnownNonZero(Cmp->getOperand(0), *DL))) {
1891 // ctpop(x) u< 2 -> (x & (x - 1)) == 0
1892 // ctpop(x) u> 1 -> (x & (x - 1)) != 0
1893 IRBuilder<> Builder(Cmp);
1894 Value *Sub = Builder.CreateAdd(X, Constant::getAllOnesValue(OpTy));
1895 Value *And = Builder.CreateAnd(X, Sub);
1896 CmpInst::Predicate NewPred =
1897 (Pred == CmpInst::ICMP_ULT || Pred == CmpInst::ICMP_EQ)
1899 : CmpInst::ICMP_NE;
1900 NewCmp = Builder.CreateICmp(NewPred, And, ConstantInt::getNullValue(OpTy));
1901 } else {
1902 // ctpop(x) == 1 -> (x ^ (x - 1)) u> (x - 1)
1903 // ctpop(x) != 1 -> (x ^ (x - 1)) u<= (x - 1)
1904 IRBuilder<> Builder(Cmp);
1905 Value *Sub = Builder.CreateAdd(X, Constant::getAllOnesValue(OpTy));
1906 Value *Xor = Builder.CreateXor(X, Sub);
1907 CmpInst::Predicate NewPred =
1909 NewCmp = Builder.CreateICmp(NewPred, Xor, Sub);
1910 }
1911
1912 Cmp->replaceAllUsesWith(NewCmp);
1914 return true;
1915}
1916
1917/// Sink the given CmpInst into user blocks to reduce the number of virtual
1918/// registers that must be created and coalesced. This is a clear win except on
1919/// targets with multiple condition code registers (PowerPC), where it might
1920/// lose; some adjustment may be wanted there.
1921///
1922/// Return true if any changes are made.
1923static bool sinkCmpExpression(CmpInst *Cmp, const TargetLowering &TLI,
1924 const DataLayout &DL) {
1925 if (TLI.hasMultipleConditionRegisters(EVT::getEVT(Cmp->getType())))
1926 return false;
1927
1928 // Avoid sinking soft-FP comparisons, since this can move them into a loop.
1929 if (TLI.useSoftFloat() && isa<FCmpInst>(Cmp))
1930 return false;
1931
1932 bool UsedInPhiOrCurrentBlock = any_of(Cmp->users(), [Cmp](User *U) {
1933 return isa<PHINode>(U) ||
1934 cast<Instruction>(U)->getParent() == Cmp->getParent();
1935 });
1936
1937 // Avoid sinking larger than legal integer comparisons unless its ONLY used in
1938 // another BB.
1939 if (UsedInPhiOrCurrentBlock && Cmp->getOperand(0)->getType()->isIntegerTy() &&
1940 Cmp->getOperand(0)->getType()->getScalarSizeInBits() >
1941 DL.getLargestLegalIntTypeSizeInBits())
1942 return false;
1943
1944 // Only insert a cmp in each block once.
1946
1947 bool MadeChange = false;
1948 for (Value::user_iterator UI = Cmp->user_begin(), E = Cmp->user_end();
1949 UI != E;) {
1950 Use &TheUse = UI.getUse();
1952
1953 // Preincrement use iterator so we don't invalidate it.
1954 ++UI;
1955
1956 // Don't bother for PHI nodes.
1957 if (isa<PHINode>(User))
1958 continue;
1959
1960 // Figure out which BB this cmp is used in.
1961 BasicBlock *UserBB = User->getParent();
1962 BasicBlock *DefBB = Cmp->getParent();
1963
1964 // If this user is in the same block as the cmp, don't change the cmp.
1965 if (UserBB == DefBB)
1966 continue;
1967
1968 // If we have already inserted a cmp into this block, use it.
1969 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
1970
1971 if (!InsertedCmp) {
1972 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1973 assert(InsertPt != UserBB->end());
1974 InsertedCmp = CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(),
1975 Cmp->getOperand(0), Cmp->getOperand(1), "");
1976 InsertedCmp->insertBefore(*UserBB, InsertPt);
1977 // Propagate the debug info.
1978 InsertedCmp->setDebugLoc(Cmp->getDebugLoc());
1979 }
1980
1981 // Replace a use of the cmp with a use of the new cmp.
1982 TheUse = InsertedCmp;
1983 MadeChange = true;
1984 ++NumCmpUses;
1985 }
1986
1987 // If we removed all uses, nuke the cmp.
1988 if (Cmp->use_empty()) {
1989 Cmp->eraseFromParent();
1990 MadeChange = true;
1991 }
1992
1993 return MadeChange;
1994}
1995
1996/// For pattern like:
1997///
1998/// DomCond = icmp sgt/slt CmpOp0, CmpOp1 (might not be in DomBB)
1999/// ...
2000/// DomBB:
2001/// ...
2002/// br DomCond, TrueBB, CmpBB
2003/// CmpBB: (with DomBB being the single predecessor)
2004/// ...
2005/// Cmp = icmp eq CmpOp0, CmpOp1
2006/// ...
2007///
2008/// It would use two comparison on targets that lowering of icmp sgt/slt is
2009/// different from lowering of icmp eq (PowerPC). This function try to convert
2010/// 'Cmp = icmp eq CmpOp0, CmpOp1' to ' Cmp = icmp slt/sgt CmpOp0, CmpOp1'.
2011/// After that, DomCond and Cmp can use the same comparison so reduce one
2012/// comparison.
2013///
2014/// Return true if any changes are made.
2016 const TargetLowering &TLI) {
2018 return false;
2019
2020 ICmpInst::Predicate Pred = Cmp->getPredicate();
2021 if (Pred != ICmpInst::ICMP_EQ)
2022 return false;
2023
2024 // If icmp eq has users other than CondBrInst and SelectInst, converting it to
2025 // icmp slt/sgt would introduce more redundant LLVM IR.
2026 for (User *U : Cmp->users()) {
2027 if (isa<CondBrInst>(U))
2028 continue;
2029 if (isa<SelectInst>(U) && cast<SelectInst>(U)->getCondition() == Cmp)
2030 continue;
2031 return false;
2032 }
2033
2034 // This is a cheap/incomplete check for dominance - just match a single
2035 // predecessor with a conditional branch.
2036 BasicBlock *CmpBB = Cmp->getParent();
2037 BasicBlock *DomBB = CmpBB->getSinglePredecessor();
2038 if (!DomBB)
2039 return false;
2040
2041 // We want to ensure that the only way control gets to the comparison of
2042 // interest is that a less/greater than comparison on the same operands is
2043 // false.
2044 Value *DomCond;
2045 BasicBlock *TrueBB, *FalseBB;
2046 if (!match(DomBB->getTerminator(), m_Br(m_Value(DomCond), TrueBB, FalseBB)))
2047 return false;
2048 if (CmpBB != FalseBB)
2049 return false;
2050
2051 Value *CmpOp0 = Cmp->getOperand(0), *CmpOp1 = Cmp->getOperand(1);
2052 CmpPredicate DomPred;
2053 if (!match(DomCond, m_ICmp(DomPred, m_Specific(CmpOp0), m_Specific(CmpOp1))))
2054 return false;
2055 if (DomPred != ICmpInst::ICMP_SGT && DomPred != ICmpInst::ICMP_SLT)
2056 return false;
2057
2058 // Convert the equality comparison to the opposite of the dominating
2059 // comparison and swap the direction for all branch/select users.
2060 // We have conceptually converted:
2061 // Res = (a < b) ? <LT_RES> : (a == b) ? <EQ_RES> : <GT_RES>;
2062 // to
2063 // Res = (a < b) ? <LT_RES> : (a > b) ? <GT_RES> : <EQ_RES>;
2064 // And similarly for branches.
2065 for (User *U : Cmp->users()) {
2066 if (auto *BI = dyn_cast<CondBrInst>(U)) {
2067 BI->swapSuccessors();
2068 continue;
2069 }
2070 if (auto *SI = dyn_cast<SelectInst>(U)) {
2071 // Swap operands
2072 SI->swapValues();
2073 SI->swapProfMetadata();
2074 continue;
2075 }
2076 llvm_unreachable("Must be a branch or a select");
2077 }
2078 Cmp->setPredicate(CmpInst::getSwappedPredicate(DomPred));
2079 return true;
2080}
2081
2082/// Many architectures use the same instruction for both subtract and cmp. Try
2083/// to swap cmp operands to match subtract operations to allow for CSE.
2085 Value *Op0 = Cmp->getOperand(0);
2086 Value *Op1 = Cmp->getOperand(1);
2087 if (!Op0->getType()->isIntegerTy() || isa<Constant>(Op0) ||
2088 isa<Constant>(Op1) || Op0 == Op1)
2089 return false;
2090
2091 // If a subtract already has the same operands as a compare, swapping would be
2092 // bad. If a subtract has the same operands as a compare but in reverse order,
2093 // then swapping is good.
2094 int GoodToSwap = 0;
2095 unsigned NumInspected = 0;
2096 for (const User *U : Op0->users()) {
2097 // Avoid walking many users.
2098 if (++NumInspected > 128)
2099 return false;
2100 if (match(U, m_Sub(m_Specific(Op1), m_Specific(Op0))))
2101 GoodToSwap++;
2102 else if (match(U, m_Sub(m_Specific(Op0), m_Specific(Op1))))
2103 GoodToSwap--;
2104 }
2105
2106 if (GoodToSwap > 0) {
2107 Cmp->swapOperands();
2108 return true;
2109 }
2110 return false;
2111}
2112
2113static bool foldFCmpToFPClassTest(CmpInst *Cmp, const TargetLowering &TLI,
2114 const DataLayout &DL) {
2115 FCmpInst *FCmp = dyn_cast<FCmpInst>(Cmp);
2116 if (!FCmp)
2117 return false;
2118
2119 // Don't fold if the target offers free fabs and the predicate is legal.
2120 EVT VT = TLI.getValueType(DL, Cmp->getOperand(0)->getType());
2121 if (TLI.isFAbsFree(VT) &&
2123 VT.getSimpleVT()))
2124 return false;
2125
2126 // Reverse the canonicalization if it is a FP class test
2127 auto ShouldReverseTransform = [](FPClassTest ClassTest) {
2128 return ClassTest == fcInf || ClassTest == (fcInf | fcNan);
2129 };
2130 auto [ClassVal, ClassTest] =
2131 fcmpToClassTest(FCmp->getPredicate(), *FCmp->getParent()->getParent(),
2132 FCmp->getOperand(0), FCmp->getOperand(1));
2133 if (!ClassVal)
2134 return false;
2135
2136 if (!ShouldReverseTransform(ClassTest) && !ShouldReverseTransform(~ClassTest))
2137 return false;
2138
2139 IRBuilder<> Builder(Cmp);
2140 Value *IsFPClass = Builder.createIsFPClass(ClassVal, ClassTest);
2141 Cmp->replaceAllUsesWith(IsFPClass);
2143 return true;
2144}
2145
2147 Instruction *Rem, const LoopInfo *LI, Value *&RemAmtOut, Value *&AddInstOut,
2148 Value *&AddOffsetOut, PHINode *&LoopIncrPNOut) {
2149 Value *Incr, *RemAmt;
2150 // NB: If RemAmt is a power of 2 it *should* have been transformed by now.
2151 if (!match(Rem, m_URem(m_Value(Incr), m_Value(RemAmt))))
2152 return false;
2153
2154 Value *AddInst, *AddOffset;
2155 // Find out loop increment PHI.
2156 PHINode *PN = dyn_cast<PHINode>(Incr);
2157 if (PN != nullptr) {
2158 AddInst = nullptr;
2159 AddOffset = nullptr;
2160 } else {
2161 // Search through a NUW add on top of the loop increment.
2162 if (!match(Incr, m_c_NUWAdd(m_Phi(PN), m_Value(AddOffset))))
2163 return false;
2164 AddInst = Incr;
2165 }
2166
2167 if (!PN)
2168 return false;
2169
2170 // This isn't strictly necessary, what we really need is one increment and any
2171 // amount of initial values all being the same.
2172 if (PN->getNumIncomingValues() != 2)
2173 return false;
2174
2175 // Only trivially analyzable loops.
2176 Loop *L = LI->getLoopFor(PN->getParent());
2177 if (!L || !L->getLoopPreheader() || !L->getLoopLatch())
2178 return false;
2179
2180 // Req that the remainder is in the loop
2181 if (!L->contains(Rem))
2182 return false;
2183
2184 // Only works if the remainder amount is a loop invaraint
2185 if (!L->isLoopInvariant(RemAmt))
2186 return false;
2187
2188 // Only works if the AddOffset is a loop invaraint
2189 if (AddOffset && !L->isLoopInvariant(AddOffset))
2190 return false;
2191
2192 // Is the PHI a loop increment?
2193 auto LoopIncrInfo = getIVIncrement(PN, LI);
2194 if (!LoopIncrInfo)
2195 return false;
2196
2197 // We need remainder_amount % increment_amount to be zero. Increment of one
2198 // satisfies that without any special logic and is overwhelmingly the common
2199 // case.
2200 if (!match(LoopIncrInfo->second, m_One()))
2201 return false;
2202
2203 // Need the increment to not overflow.
2204 if (!match(LoopIncrInfo->first, m_c_NUWAdd(m_Specific(PN), m_Value())))
2205 return false;
2206
2207 // Set output variables.
2208 RemAmtOut = RemAmt;
2209 LoopIncrPNOut = PN;
2210 AddInstOut = AddInst;
2211 AddOffsetOut = AddOffset;
2212
2213 return true;
2214}
2215
2216// Try to transform:
2217//
2218// for(i = Start; i < End; ++i)
2219// Rem = (i nuw+ IncrLoopInvariant) u% RemAmtLoopInvariant;
2220//
2221// ->
2222//
2223// Rem = (Start nuw+ IncrLoopInvariant) % RemAmtLoopInvariant;
2224// for(i = Start; i < End; ++i, ++rem)
2225// Rem = rem == RemAmtLoopInvariant ? 0 : Rem;
2227 const LoopInfo *LI,
2229 bool IsHuge) {
2230 Value *AddOffset, *RemAmt, *AddInst;
2231 PHINode *LoopIncrPN;
2232 if (!isRemOfLoopIncrementWithLoopInvariant(Rem, LI, RemAmt, AddInst,
2233 AddOffset, LoopIncrPN))
2234 return false;
2235
2236 // Only non-constant remainder as the extra IV is probably not profitable
2237 // in that case.
2238 //
2239 // Potential TODO(1): `urem` of a const ends up as `mul` + `shift` + `add`. If
2240 // we can rule out register pressure and ensure this `urem` is executed each
2241 // iteration, its probably profitable to handle the const case as well.
2242 //
2243 // Potential TODO(2): Should we have a check for how "nested" this remainder
2244 // operation is? The new code runs every iteration so if the remainder is
2245 // guarded behind unlikely conditions this might not be worth it.
2246 if (match(RemAmt, m_ImmConstant()))
2247 return false;
2248
2249 Loop *L = LI->getLoopFor(LoopIncrPN->getParent());
2250 Value *Start = LoopIncrPN->getIncomingValueForBlock(L->getLoopPreheader());
2251 // If we have add create initial value for remainder.
2252 // The logic here is:
2253 // (urem (add nuw Start, IncrLoopInvariant), RemAmtLoopInvariant
2254 //
2255 // Only proceed if the expression simplifies (otherwise we can't fully
2256 // optimize out the urem).
2257 if (AddInst) {
2258 assert(AddOffset && "We found an add but missing values");
2259 // Without dom-condition/assumption cache we aren't likely to get much out
2260 // of a context instruction.
2261 Start = simplifyAddInst(Start, AddOffset,
2262 match(AddInst, m_NSWAdd(m_Value(), m_Value())),
2263 /*IsNUW=*/true, *DL);
2264 if (!Start)
2265 return false;
2266 }
2267
2268 // If we can't fully optimize out the `rem`, skip this transform.
2269 Start = simplifyURemInst(Start, RemAmt, *DL);
2270 if (!Start)
2271 return false;
2272
2273 // Create new remainder with induction variable.
2274 Type *Ty = Rem->getType();
2275 IRBuilder<> Builder(Rem->getContext());
2276
2277 Builder.SetInsertPoint(LoopIncrPN);
2278 PHINode *NewRem = Builder.CreatePHI(Ty, 2);
2279
2280 Builder.SetInsertPoint(cast<Instruction>(
2281 LoopIncrPN->getIncomingValueForBlock(L->getLoopLatch())));
2282 // `(add (urem x, y), 1)` is always nuw.
2283 Value *RemAdd = Builder.CreateNUWAdd(NewRem, ConstantInt::get(Ty, 1));
2284 Value *RemCmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, RemAdd, RemAmt);
2285 Value *RemSel =
2286 Builder.CreateSelect(RemCmp, Constant::getNullValue(Ty), RemAdd);
2287
2288 NewRem->addIncoming(Start, L->getLoopPreheader());
2289 NewRem->addIncoming(RemSel, L->getLoopLatch());
2290
2291 // Insert all touched BBs.
2292 FreshBBs.insert(LoopIncrPN->getParent());
2293 FreshBBs.insert(L->getLoopLatch());
2294 FreshBBs.insert(Rem->getParent());
2295 if (AddInst)
2296 FreshBBs.insert(cast<Instruction>(AddInst)->getParent());
2297 replaceAllUsesWith(Rem, NewRem, FreshBBs, IsHuge);
2298 Rem->eraseFromParent();
2299 if (AddInst && AddInst->use_empty())
2300 cast<Instruction>(AddInst)->eraseFromParent();
2301 return true;
2302}
2303
2304bool CodeGenPrepare::optimizeURem(Instruction *Rem) {
2305 if (foldURemOfLoopIncrement(Rem, DL, LI, FreshBBs, IsHugeFunc))
2306 return true;
2307 return false;
2308}
2309
2310bool CodeGenPrepare::optimizeCmp(CmpInst *Cmp, ModifyDT &ModifiedDT) {
2311 if (sinkCmpExpression(Cmp, *TLI, *DL))
2312 return true;
2313
2314 if (combineToUAddWithOverflow(Cmp, ModifiedDT))
2315 return true;
2316
2317 if (combineToUSubWithOverflow(Cmp, ModifiedDT))
2318 return true;
2319
2320 if (unfoldPowerOf2Test(Cmp))
2321 return true;
2322
2323 if (foldICmpWithDominatingICmp(Cmp, *TLI))
2324 return true;
2325
2327 return true;
2328
2329 if (foldFCmpToFPClassTest(Cmp, *TLI, *DL))
2330 return true;
2331
2332 return false;
2333}
2334
2335/// Duplicate and sink the given 'and' instruction into user blocks where it is
2336/// used in a compare to allow isel to generate better code for targets where
2337/// this operation can be combined.
2338///
2339/// Return true if any changes are made.
2341 SetOfInstrs &InsertedInsts) {
2342 // Double-check that we're not trying to optimize an instruction that was
2343 // already optimized by some other part of this pass.
2344 assert(!InsertedInsts.count(AndI) &&
2345 "Attempting to optimize already optimized and instruction");
2346 (void)InsertedInsts;
2347
2348 // Nothing to do for single use in same basic block.
2349 if (AndI->hasOneUse() &&
2350 AndI->getParent() == cast<Instruction>(*AndI->user_begin())->getParent())
2351 return false;
2352
2353 // Try to avoid cases where sinking/duplicating is likely to increase register
2354 // pressure.
2355 if (!isa<ConstantInt>(AndI->getOperand(0)) &&
2356 !isa<ConstantInt>(AndI->getOperand(1)) &&
2357 AndI->getOperand(0)->hasOneUse() && AndI->getOperand(1)->hasOneUse())
2358 return false;
2359
2360 for (auto *U : AndI->users()) {
2362
2363 // Only sink 'and' feeding icmp with 0.
2364 if (!isa<ICmpInst>(User))
2365 return false;
2366
2367 auto *CmpC = dyn_cast<ConstantInt>(User->getOperand(1));
2368 if (!CmpC || !CmpC->isZero())
2369 return false;
2370 }
2371
2372 if (!TLI.isMaskAndCmp0FoldingBeneficial(*AndI))
2373 return false;
2374
2375 LLVM_DEBUG(dbgs() << "found 'and' feeding only icmp 0;\n");
2376 LLVM_DEBUG(AndI->getParent()->dump());
2377
2378 // Push the 'and' into the same block as the icmp 0. There should only be
2379 // one (icmp (and, 0)) in each block, since CSE/GVN should have removed any
2380 // others, so we don't need to keep track of which BBs we insert into.
2381 for (Value::user_iterator UI = AndI->user_begin(), E = AndI->user_end();
2382 UI != E;) {
2383 Use &TheUse = UI.getUse();
2385
2386 // Preincrement use iterator so we don't invalidate it.
2387 ++UI;
2388
2389 LLVM_DEBUG(dbgs() << "sinking 'and' use: " << *User << "\n");
2390
2391 // Keep the 'and' in the same place if the use is already in the same block.
2392 Instruction *InsertPt =
2393 User->getParent() == AndI->getParent() ? AndI : User;
2394 Instruction *InsertedAnd = BinaryOperator::Create(
2395 Instruction::And, AndI->getOperand(0), AndI->getOperand(1), "",
2396 InsertPt->getIterator());
2397 // Propagate the debug info.
2398 InsertedAnd->setDebugLoc(AndI->getDebugLoc());
2399
2400 // Replace a use of the 'and' with a use of the new 'and'.
2401 TheUse = InsertedAnd;
2402 ++NumAndUses;
2403 LLVM_DEBUG(User->getParent()->dump());
2404 }
2405
2406 // We removed all uses, nuke the and.
2407 AndI->eraseFromParent();
2408 return true;
2409}
2410
2411/// Check if the candidates could be combined with a shift instruction, which
2412/// includes:
2413/// 1. Truncate instruction
2414/// 2. And instruction and the imm is a mask of the low bits:
2415/// imm & (imm+1) == 0
2417 if (!isa<TruncInst>(User)) {
2418 if (User->getOpcode() != Instruction::And ||
2420 return false;
2421
2422 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
2423
2424 if ((Cimm & (Cimm + 1)).getBoolValue())
2425 return false;
2426 }
2427 return true;
2428}
2429
2430/// Sink both shift and truncate instruction to the use of truncate's BB.
2431static bool
2434 const TargetLowering &TLI, const DataLayout &DL) {
2435 BasicBlock *UserBB = User->getParent();
2437 auto *TruncI = cast<TruncInst>(User);
2438 bool MadeChange = false;
2439
2440 for (Value::user_iterator TruncUI = TruncI->user_begin(),
2441 TruncE = TruncI->user_end();
2442 TruncUI != TruncE;) {
2443
2444 Use &TruncTheUse = TruncUI.getUse();
2445 Instruction *TruncUser = cast<Instruction>(*TruncUI);
2446 // Preincrement use iterator so we don't invalidate it.
2447
2448 ++TruncUI;
2449
2450 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
2451 if (!ISDOpcode)
2452 continue;
2453
2454 // If the use is actually a legal node, there will not be an
2455 // implicit truncate.
2456 // FIXME: always querying the result type is just an
2457 // approximation; some nodes' legality is determined by the
2458 // operand or other means. There's no good way to find out though.
2460 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
2461 continue;
2462
2463 // Don't bother for PHI nodes.
2464 if (isa<PHINode>(TruncUser))
2465 continue;
2466
2467 BasicBlock *TruncUserBB = TruncUser->getParent();
2468
2469 if (UserBB == TruncUserBB)
2470 continue;
2471
2472 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
2473 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
2474
2475 if (!InsertedShift && !InsertedTrunc) {
2476 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
2477 assert(InsertPt != TruncUserBB->end());
2478 // Sink the shift
2479 if (ShiftI->getOpcode() == Instruction::AShr)
2480 InsertedShift =
2481 BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "");
2482 else
2483 InsertedShift =
2484 BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "");
2485 InsertedShift->setDebugLoc(ShiftI->getDebugLoc());
2486 InsertedShift->insertBefore(*TruncUserBB, InsertPt);
2487
2488 // Sink the trunc
2489 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
2490 TruncInsertPt++;
2491 // It will go ahead of any debug-info.
2492 TruncInsertPt.setHeadBit(true);
2493 assert(TruncInsertPt != TruncUserBB->end());
2494
2495 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
2496 TruncI->getType(), "");
2497 InsertedTrunc->insertBefore(*TruncUserBB, TruncInsertPt);
2498 InsertedTrunc->setDebugLoc(TruncI->getDebugLoc());
2499
2500 MadeChange = true;
2501
2502 TruncTheUse = InsertedTrunc;
2503 }
2504 }
2505 return MadeChange;
2506}
2507
2508/// Sink the shift *right* instruction into user blocks if the uses could
2509/// potentially be combined with this shift instruction and generate BitExtract
2510/// instruction. It will only be applied if the architecture supports BitExtract
2511/// instruction. Here is an example:
2512/// BB1:
2513/// %x.extract.shift = lshr i64 %arg1, 32
2514/// BB2:
2515/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
2516/// ==>
2517///
2518/// BB2:
2519/// %x.extract.shift.1 = lshr i64 %arg1, 32
2520/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
2521///
2522/// CodeGen will recognize the pattern in BB2 and generate BitExtract
2523/// instruction.
2524/// Return true if any changes are made.
2526 const TargetLowering &TLI,
2527 const DataLayout &DL) {
2528 BasicBlock *DefBB = ShiftI->getParent();
2529
2530 /// Only insert instructions in each block once.
2532
2533 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
2534
2535 bool MadeChange = false;
2536 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
2537 UI != E;) {
2538 Use &TheUse = UI.getUse();
2540 // Preincrement use iterator so we don't invalidate it.
2541 ++UI;
2542
2543 // Don't bother for PHI nodes.
2544 if (isa<PHINode>(User))
2545 continue;
2546
2548 continue;
2549
2550 BasicBlock *UserBB = User->getParent();
2551
2552 if (UserBB == DefBB) {
2553 // If the shift and truncate instruction are in the same BB. The use of
2554 // the truncate(TruncUse) may still introduce another truncate if not
2555 // legal. In this case, we would like to sink both shift and truncate
2556 // instruction to the BB of TruncUse.
2557 // for example:
2558 // BB1:
2559 // i64 shift.result = lshr i64 opnd, imm
2560 // trunc.result = trunc shift.result to i16
2561 //
2562 // BB2:
2563 // ----> We will have an implicit truncate here if the architecture does
2564 // not have i16 compare.
2565 // cmp i16 trunc.result, opnd2
2566 //
2567 if (isa<TruncInst>(User) &&
2568 shiftIsLegal
2569 // If the type of the truncate is legal, no truncate will be
2570 // introduced in other basic blocks.
2571 && (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
2572 MadeChange =
2573 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
2574
2575 continue;
2576 }
2577 // If we have already inserted a shift into this block, use it.
2578 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
2579
2580 if (!InsertedShift) {
2581 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
2582 assert(InsertPt != UserBB->end());
2583
2584 if (ShiftI->getOpcode() == Instruction::AShr)
2585 InsertedShift =
2586 BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "");
2587 else
2588 InsertedShift =
2589 BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "");
2590 InsertedShift->insertBefore(*UserBB, InsertPt);
2591 InsertedShift->setDebugLoc(ShiftI->getDebugLoc());
2592
2593 MadeChange = true;
2594 }
2595
2596 // Replace a use of the shift with a use of the new shift.
2597 TheUse = InsertedShift;
2598 }
2599
2600 // If we removed all uses, or there are none, nuke the shift.
2601 if (ShiftI->use_empty()) {
2602 salvageDebugInfo(*ShiftI);
2603 ShiftI->eraseFromParent();
2604 MadeChange = true;
2605 }
2606
2607 return MadeChange;
2608}
2609
2610/// If counting leading or trailing zeros is an expensive operation and a zero
2611/// input is defined, add a check for zero to avoid calling the intrinsic.
2612///
2613/// We want to transform:
2614/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
2615///
2616/// into:
2617/// entry:
2618/// %cmpz = icmp eq i64 %A, 0
2619/// br i1 %cmpz, label %cond.end, label %cond.false
2620/// cond.false:
2621/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
2622/// br label %cond.end
2623/// cond.end:
2624/// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
2625///
2626/// If the transform is performed, return true and set ModifiedDT to true.
2627static bool despeculateCountZeros(IntrinsicInst *CountZeros,
2628 DomTreeUpdater *DTU, LoopInfo *LI,
2629 const TargetLowering *TLI,
2630 const DataLayout *DL, ModifyDT &ModifiedDT,
2632 bool IsHugeFunc) {
2633 // If a zero input is undefined, it doesn't make sense to despeculate that.
2634 if (match(CountZeros->getOperand(1), m_One()))
2635 return false;
2636
2637 // If it's cheap to speculate, there's nothing to do.
2638 Type *Ty = CountZeros->getType();
2639 auto IntrinsicID = CountZeros->getIntrinsicID();
2640 if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz(Ty)) ||
2641 (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz(Ty)))
2642 return false;
2643
2644 // Only handle scalar cases. Anything else requires too much work.
2645 unsigned SizeInBits = Ty->getScalarSizeInBits();
2646 if (Ty->isVectorTy())
2647 return false;
2648
2649 // Bail if the value is never zero.
2650 Use &Op = CountZeros->getOperandUse(0);
2651 if (isKnownNonZero(Op, *DL))
2652 return false;
2653
2654 // The intrinsic will be sunk behind a compare against zero and branch.
2655 BasicBlock *StartBlock = CountZeros->getParent();
2656 BasicBlock *CallBlock = SplitBlock(StartBlock, CountZeros, DTU, LI,
2657 /* MSSAU */ nullptr, "cond.false");
2658 if (IsHugeFunc)
2659 FreshBBs.insert(CallBlock);
2660
2661 // Create another block after the count zero intrinsic. A PHI will be added
2662 // in this block to select the result of the intrinsic or the bit-width
2663 // constant if the input to the intrinsic is zero.
2664 BasicBlock::iterator SplitPt = std::next(BasicBlock::iterator(CountZeros));
2665 // Any debug-info after CountZeros should not be included.
2666 SplitPt.setHeadBit(true);
2667 BasicBlock *EndBlock = SplitBlock(CallBlock, &*SplitPt, DTU, LI,
2668 /* MSSAU */ nullptr, "cond.end");
2669 if (IsHugeFunc)
2670 FreshBBs.insert(EndBlock);
2671
2672 // Set up a builder to create a compare, conditional branch, and PHI.
2673 IRBuilder<> Builder(CountZeros->getContext());
2674 Builder.SetInsertPoint(StartBlock->getTerminator());
2675 Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
2676
2677 // Replace the unconditional branch that was created by the first split with
2678 // a compare against zero and a conditional branch.
2679 Value *Zero = Constant::getNullValue(Ty);
2680 // Avoid introducing branch on poison. This also replaces the ctz operand.
2682 Op = Builder.CreateFreeze(Op, Op->getName() + ".fr");
2683 Value *Cmp = Builder.CreateICmpEQ(Op, Zero, "cmpz");
2684 Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
2685 StartBlock->getTerminator()->eraseFromParent();
2686 DTU->applyUpdates({{DominatorTree::Insert, StartBlock, EndBlock}});
2687
2688 // Create a PHI in the end block to select either the output of the intrinsic
2689 // or the bit width of the operand.
2690 Builder.SetInsertPoint(EndBlock, EndBlock->begin());
2691 PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
2692 replaceAllUsesWith(CountZeros, PN, FreshBBs, IsHugeFunc);
2693 Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
2694 PN->addIncoming(BitWidth, StartBlock);
2695 PN->addIncoming(CountZeros, CallBlock);
2696
2697 // We are explicitly handling the zero case, so we can set the intrinsic's
2698 // undefined zero argument to 'true'. This will also prevent reprocessing the
2699 // intrinsic; we only despeculate when a zero input is defined.
2700 CountZeros->setArgOperand(1, Builder.getTrue());
2701 ModifiedDT = ModifyDT::ModifyBBDT;
2702 return true;
2703}
2704
2705bool CodeGenPrepare::optimizeCallInst(CallInst *CI, ModifyDT &ModifiedDT) {
2706 BasicBlock *BB = CI->getParent();
2707
2708 // Sink address computing for memory operands into the block.
2709 if (CI->isInlineAsm() && optimizeInlineAsmInst(CI))
2710 return true;
2711
2712 // Align the pointer arguments to this call if the target thinks it's a good
2713 // idea
2714 unsigned MinSize;
2715 Align PrefAlign;
2716 if (TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
2717 for (auto &Arg : CI->args()) {
2718 // We want to align both objects whose address is used directly and
2719 // objects whose address is used in casts and GEPs, though it only makes
2720 // sense for GEPs if the offset is a multiple of the desired alignment and
2721 // if size - offset meets the size threshold.
2722 if (!Arg->getType()->isPointerTy())
2723 continue;
2724 APInt Offset(DL->getIndexSizeInBits(
2725 cast<PointerType>(Arg->getType())->getAddressSpace()),
2726 0);
2727 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
2728 uint64_t Offset2 = Offset.getLimitedValue();
2729 if (!isAligned(PrefAlign, Offset2))
2730 continue;
2731 AllocaInst *AI;
2732 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlign() < PrefAlign) {
2733 std::optional<TypeSize> AllocaSize = AI->getAllocationSize(*DL);
2734 if (AllocaSize && AllocaSize->getKnownMinValue() >= MinSize + Offset2)
2735 AI->setAlignment(PrefAlign);
2736 }
2737 // Global variables can only be aligned if they are defined in this
2738 // object (i.e. they are uniquely initialized in this object), and
2739 // over-aligning global variables that have an explicit section is
2740 // forbidden.
2741 GlobalVariable *GV;
2742 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
2743 GV->getPointerAlignment(*DL) < PrefAlign &&
2744 GV->getGlobalSize(*DL) >= MinSize + Offset2)
2745 GV->setAlignment(PrefAlign);
2746 }
2747 }
2748 // If this is a memcpy (or similar) then we may be able to improve the
2749 // alignment.
2750 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
2751 Align DestAlign = getKnownAlignment(MI->getDest(), *DL);
2752 MaybeAlign MIDestAlign = MI->getDestAlign();
2753 if (!MIDestAlign || DestAlign > *MIDestAlign)
2754 MI->setDestAlignment(DestAlign);
2755 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
2756 MaybeAlign MTISrcAlign = MTI->getSourceAlign();
2757 Align SrcAlign = getKnownAlignment(MTI->getSource(), *DL);
2758 if (!MTISrcAlign || SrcAlign > *MTISrcAlign)
2759 MTI->setSourceAlignment(SrcAlign);
2760 }
2761 }
2762
2763 // If we have a cold call site, try to sink addressing computation into the
2764 // cold block. This interacts with our handling for loads and stores to
2765 // ensure that we can fold all uses of a potential addressing computation
2766 // into their uses. TODO: generalize this to work over profiling data
2767 if (CI->hasFnAttr(Attribute::Cold) &&
2768 !llvm::shouldOptimizeForSize(BB, PSI, BFI))
2769 for (auto &Arg : CI->args()) {
2770 if (!Arg->getType()->isPointerTy())
2771 continue;
2772 unsigned AS = Arg->getType()->getPointerAddressSpace();
2773 if (optimizeMemoryInst(CI, Arg, Arg->getType(), AS))
2774 return true;
2775 }
2776
2777 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
2778 if (II) {
2779 switch (II->getIntrinsicID()) {
2780 default:
2781 break;
2782 case Intrinsic::assume:
2783 llvm_unreachable("llvm.assume should have been removed already");
2784 case Intrinsic::allow_runtime_check:
2785 case Intrinsic::allow_ubsan_check:
2786 case Intrinsic::experimental_widenable_condition: {
2787 // Give up on future widening opportunities so that we can fold away dead
2788 // paths and merge blocks before going into block-local instruction
2789 // selection.
2790 if (II->use_empty()) {
2791 II->eraseFromParent();
2792 return true;
2793 }
2794 Constant *RetVal = ConstantInt::getTrue(II->getContext());
2795 resetIteratorIfInvalidatedWhileCalling(BB, [&]() {
2796 replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
2797 });
2798 return true;
2799 }
2800 case Intrinsic::objectsize:
2801 llvm_unreachable("llvm.objectsize.* should have been lowered already");
2802 case Intrinsic::is_constant:
2803 llvm_unreachable("llvm.is.constant.* should have been lowered already");
2804 case Intrinsic::aarch64_stlxr:
2805 case Intrinsic::aarch64_stxr: {
2806 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
2807 if (!ExtVal || !ExtVal->hasOneUse() ||
2808 ExtVal->getParent() == CI->getParent())
2809 return false;
2810 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
2811 ExtVal->moveBefore(CI->getIterator());
2812 // Mark this instruction as "inserted by CGP", so that other
2813 // optimizations don't touch it.
2814 InsertedInsts.insert(ExtVal);
2815 return true;
2816 }
2817
2818 case Intrinsic::launder_invariant_group:
2819 case Intrinsic::strip_invariant_group: {
2820 Value *ArgVal = II->getArgOperand(0);
2821 auto it = LargeOffsetGEPMap.find(II);
2822 if (it != LargeOffsetGEPMap.end()) {
2823 // Merge entries in LargeOffsetGEPMap to reflect the RAUW.
2824 // Make sure not to have to deal with iterator invalidation
2825 // after possibly adding ArgVal to LargeOffsetGEPMap.
2826 auto GEPs = std::move(it->second);
2827 LargeOffsetGEPMap[ArgVal].append(GEPs.begin(), GEPs.end());
2828 LargeOffsetGEPMap.erase(II);
2829 }
2830
2831 replaceAllUsesWith(II, ArgVal, FreshBBs, IsHugeFunc);
2832 II->eraseFromParent();
2833 return true;
2834 }
2835 case Intrinsic::cttz:
2836 case Intrinsic::ctlz:
2837 // If counting zeros is expensive, try to avoid it.
2838 return despeculateCountZeros(II, DTU, LI, TLI, DL, ModifiedDT, FreshBBs,
2839 IsHugeFunc);
2840 case Intrinsic::fshl:
2841 case Intrinsic::fshr:
2842 return optimizeFunnelShift(II);
2843 case Intrinsic::masked_gather:
2844 return optimizeGatherScatterInst(II, II->getArgOperand(0));
2845 case Intrinsic::masked_scatter:
2846 return optimizeGatherScatterInst(II, II->getArgOperand(1));
2847 case Intrinsic::masked_load:
2848 // Treat v1X masked load as load X type.
2849 if (auto *VT = dyn_cast<FixedVectorType>(II->getType())) {
2850 if (VT->getNumElements() == 1) {
2851 Value *PtrVal = II->getArgOperand(0);
2852 unsigned AS = PtrVal->getType()->getPointerAddressSpace();
2853 if (optimizeMemoryInst(II, PtrVal, VT->getElementType(), AS))
2854 return true;
2855 }
2856 }
2857 return false;
2858 case Intrinsic::masked_store:
2859 // Treat v1X masked store as store X type.
2860 if (auto *VT =
2861 dyn_cast<FixedVectorType>(II->getArgOperand(0)->getType())) {
2862 if (VT->getNumElements() == 1) {
2863 Value *PtrVal = II->getArgOperand(1);
2864 unsigned AS = PtrVal->getType()->getPointerAddressSpace();
2865 if (optimizeMemoryInst(II, PtrVal, VT->getElementType(), AS))
2866 return true;
2867 }
2868 }
2869 return false;
2870 case Intrinsic::umul_with_overflow:
2871 return optimizeMulWithOverflow(II, /*IsSigned=*/false, ModifiedDT);
2872 case Intrinsic::smul_with_overflow:
2873 return optimizeMulWithOverflow(II, /*IsSigned=*/true, ModifiedDT);
2874 }
2875
2876 SmallVector<Value *, 2> PtrOps;
2877 Type *AccessTy;
2878 if (TLI->getAddrModeArguments(II, PtrOps, AccessTy))
2879 while (!PtrOps.empty()) {
2880 Value *PtrVal = PtrOps.pop_back_val();
2881 unsigned AS = PtrVal->getType()->getPointerAddressSpace();
2882 if (optimizeMemoryInst(II, PtrVal, AccessTy, AS))
2883 return true;
2884 }
2885 }
2886
2887 // From here on out we're working with named functions.
2888 auto *Callee = CI->getCalledFunction();
2889 if (!Callee)
2890 return false;
2891
2892 // Lower all default uses of _chk calls. This is very similar
2893 // to what InstCombineCalls does, but here we are only lowering calls
2894 // to fortified library functions (e.g. __memcpy_chk) that have the default
2895 // "don't know" as the objectsize. Anything else should be left alone.
2896 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
2897 IRBuilder<> Builder(CI);
2898 if (Value *V = Simplifier.optimizeCall(CI, Builder)) {
2899 replaceAllUsesWith(CI, V, FreshBBs, IsHugeFunc);
2900 CI->eraseFromParent();
2901 return true;
2902 }
2903
2904 // SCCP may have propagated, among other things, C++ static variables across
2905 // calls. If this happens to be the case, we may want to undo it in order to
2906 // avoid redundant pointer computation of the constant, as the function method
2907 // returning the constant needs to be executed anyways.
2908 auto GetUniformReturnValue = [](const Function *F) -> GlobalVariable * {
2909 if (!F->getReturnType()->isPointerTy())
2910 return nullptr;
2911
2912 GlobalVariable *UniformValue = nullptr;
2913 for (auto &BB : *F) {
2914 if (auto *RI = dyn_cast<ReturnInst>(BB.getTerminator())) {
2915 if (auto *V = dyn_cast<GlobalVariable>(RI->getReturnValue())) {
2916 if (!UniformValue)
2917 UniformValue = V;
2918 else if (V != UniformValue)
2919 return nullptr;
2920 } else {
2921 return nullptr;
2922 }
2923 }
2924 }
2925
2926 return UniformValue;
2927 };
2928
2929 if (Callee->hasExactDefinition()) {
2930 if (GlobalVariable *RV = GetUniformReturnValue(Callee)) {
2931 bool MadeChange = false;
2932 for (Use &U : make_early_inc_range(RV->uses())) {
2933 auto *I = dyn_cast<Instruction>(U.getUser());
2934 if (!I || I->getParent() != CI->getParent()) {
2935 // Limit to the same basic block to avoid extending the call-site live
2936 // range, which otherwise could increase register pressure.
2937 continue;
2938 }
2939 if (CI->comesBefore(I)) {
2940 U.set(CI);
2941 MadeChange = true;
2942 }
2943 }
2944
2945 return MadeChange;
2946 }
2947 }
2948
2949 return false;
2950}
2951
2953 const CallInst *CI) {
2954 assert(CI && CI->use_empty());
2955
2956 if (const auto *II = dyn_cast<IntrinsicInst>(CI))
2957 switch (II->getIntrinsicID()) {
2958 case Intrinsic::memset:
2959 case Intrinsic::memcpy:
2960 case Intrinsic::memmove:
2961 return true;
2962 default:
2963 return false;
2964 }
2965
2966 Function *Callee = CI->getCalledFunction();
2967 if (Callee && TLInfo)
2968 switch (TLInfo->getLibFunc(*Callee)) {
2969 case LibFunc_strcpy:
2970 case LibFunc_strncpy:
2971 case LibFunc_strcat:
2972 case LibFunc_strncat:
2973 return true;
2974 default:
2975 return false;
2976 }
2977
2978 return false;
2979}
2980
2981/// Look for opportunities to duplicate return instructions to the predecessor
2982/// to enable tail call optimizations. The case it is currently looking for is
2983/// the following one. Known intrinsics or library function that may be tail
2984/// called are taken into account as well.
2985/// @code
2986/// bb0:
2987/// %tmp0 = tail call i32 @f0()
2988/// br label %return
2989/// bb1:
2990/// %tmp1 = tail call i32 @f1()
2991/// br label %return
2992/// bb2:
2993/// %tmp2 = tail call i32 @f2()
2994/// br label %return
2995/// return:
2996/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
2997/// ret i32 %retval
2998/// @endcode
2999///
3000/// =>
3001///
3002/// @code
3003/// bb0:
3004/// %tmp0 = tail call i32 @f0()
3005/// ret i32 %tmp0
3006/// bb1:
3007/// %tmp1 = tail call i32 @f1()
3008/// ret i32 %tmp1
3009/// bb2:
3010/// %tmp2 = tail call i32 @f2()
3011/// ret i32 %tmp2
3012/// @endcode
3013bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB,
3014 ModifyDT &ModifiedDT) {
3015 if (!BB->getTerminator())
3016 return false;
3017
3018 ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator());
3019 if (!RetI)
3020 return false;
3021
3022 assert(LI->getLoopFor(BB) == nullptr && "A return block cannot be in a loop");
3023
3024 PHINode *PN = nullptr;
3025 ExtractValueInst *EVI = nullptr;
3026 BitCastInst *BCI = nullptr;
3027 Value *V = RetI->getReturnValue();
3028 if (V) {
3029 BCI = dyn_cast<BitCastInst>(V);
3030 if (BCI)
3031 V = BCI->getOperand(0);
3032
3034 if (EVI) {
3035 V = EVI->getOperand(0);
3036 if (!llvm::all_of(EVI->indices(), equal_to(0)))
3037 return false;
3038 }
3039
3040 PN = dyn_cast<PHINode>(V);
3041 }
3042
3043 if (PN && PN->getParent() != BB)
3044 return false;
3045
3046 auto isLifetimeEndOrBitCastFor = [](const Instruction *Inst) {
3047 const BitCastInst *BC = dyn_cast<BitCastInst>(Inst);
3048 if (BC && BC->hasOneUse())
3049 Inst = BC->user_back();
3050
3051 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst))
3052 return II->getIntrinsicID() == Intrinsic::lifetime_end;
3053 return false;
3054 };
3055
3057
3058 auto isFakeUse = [&FakeUses](const Instruction *Inst) {
3059 if (auto *II = dyn_cast<IntrinsicInst>(Inst);
3060 II && II->getIntrinsicID() == Intrinsic::fake_use) {
3061 // Record the instruction so it can be preserved when the exit block is
3062 // removed. Do not preserve the fake use that uses the result of the
3063 // PHI instruction.
3064 // Do not copy fake uses that use the result of a PHI node.
3065 // FIXME: If we do want to copy the fake use into the return blocks, we
3066 // have to figure out which of the PHI node operands to use for each
3067 // copy.
3068 if (!isa<PHINode>(II->getOperand(0))) {
3069 FakeUses.push_back(II);
3070 }
3071 return true;
3072 }
3073
3074 return false;
3075 };
3076
3077 // Make sure there are no instructions between the first instruction
3078 // and return.
3080 // Skip over pseudo-probes and the bitcast.
3081 while (&*BI == BCI || &*BI == EVI || isa<PseudoProbeInst>(BI) ||
3082 isLifetimeEndOrBitCastFor(&*BI) || isFakeUse(&*BI))
3083 BI = std::next(BI);
3084 if (&*BI != RetI)
3085 return false;
3086
3087 // Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
3088 // call.
3089 auto MayBePermittedAsTailCall = [&](const auto *CI) {
3090 return TLI->mayBeEmittedAsTailCall(CI) &&
3091 attributesPermitTailCall(BB->getParent(), CI, RetI, *TLI);
3092 };
3093
3094 SmallVector<BasicBlock *, 4> TailCallBBs;
3095 // Record the call instructions so we can insert any fake uses
3096 // that need to be preserved before them.
3098 if (PN) {
3099 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
3100 // Look through bitcasts.
3101 Value *IncomingVal = PN->getIncomingValue(I)->stripPointerCasts();
3102 CallInst *CI = dyn_cast<CallInst>(IncomingVal);
3103 BasicBlock *PredBB = PN->getIncomingBlock(I);
3104 // Make sure the phi value is indeed produced by the tail call.
3105 if (CI && CI->hasOneUse() && CI->getParent() == PredBB &&
3106 MayBePermittedAsTailCall(CI)) {
3107 TailCallBBs.push_back(PredBB);
3108 CallInsts.push_back(CI);
3109 } else {
3110 // Consider the cases in which the phi value is indirectly produced by
3111 // the tail call, for example when encountering memset(), memmove(),
3112 // strcpy(), whose return value may have been optimized out. In such
3113 // cases, the value needs to be the first function argument.
3114 //
3115 // bb0:
3116 // tail call void @llvm.memset.p0.i64(ptr %0, i8 0, i64 %1)
3117 // br label %return
3118 // return:
3119 // %phi = phi ptr [ %0, %bb0 ], [ %2, %entry ]
3120 if (PredBB && PredBB->getSingleSuccessor() == BB)
3122 PredBB->getTerminator()->getPrevNode());
3123
3124 if (CI && CI->use_empty() &&
3125 isIntrinsicOrLFToBeTailCalled(TLInfo, CI) &&
3126 IncomingVal == CI->getArgOperand(0) &&
3127 MayBePermittedAsTailCall(CI)) {
3128 TailCallBBs.push_back(PredBB);
3129 CallInsts.push_back(CI);
3130 }
3131 }
3132 }
3133 } else {
3134 SmallPtrSet<BasicBlock *, 4> VisitedBBs;
3135 for (BasicBlock *Pred : predecessors(BB)) {
3136 if (!VisitedBBs.insert(Pred).second)
3137 continue;
3138 if (Instruction *I = Pred->rbegin()->getPrevNode()) {
3139 CallInst *CI = dyn_cast<CallInst>(I);
3140 if (CI && CI->use_empty() && MayBePermittedAsTailCall(CI)) {
3141 // Either we return void or the return value must be the first
3142 // argument of a known intrinsic or library function.
3143 if (!V || isa<UndefValue>(V) ||
3144 (isIntrinsicOrLFToBeTailCalled(TLInfo, CI) &&
3145 V == CI->getArgOperand(0))) {
3146 TailCallBBs.push_back(Pred);
3147 CallInsts.push_back(CI);
3148 }
3149 }
3150 }
3151 }
3152 }
3153
3154 bool Changed = false;
3155 for (auto const &TailCallBB : TailCallBBs) {
3156 // Make sure the call instruction is followed by an unconditional branch to
3157 // the return block.
3158 UncondBrInst *BI = dyn_cast<UncondBrInst>(TailCallBB->getTerminator());
3159 if (!BI || BI->getSuccessor() != BB)
3160 continue;
3161
3162 // Duplicate the return into TailCallBB.
3163 (void)FoldReturnIntoUncondBranch(RetI, BB, TailCallBB, DTU);
3165 BFI->getBlockFreq(BB) >= BFI->getBlockFreq(TailCallBB));
3166 BFI->setBlockFreq(BB,
3167 (BFI->getBlockFreq(BB) - BFI->getBlockFreq(TailCallBB)));
3168 ModifiedDT = ModifyDT::ModifyBBDT;
3169 Changed = true;
3170 ++NumRetsDup;
3171 }
3172
3173 // If we eliminated all predecessors of the block, delete the block now.
3174 if (Changed && !BB->hasAddressTaken() && pred_empty(BB)) {
3175 // Copy the fake uses found in the original return block to all blocks
3176 // that contain tail calls.
3177 for (auto *CI : CallInsts) {
3178 for (auto const *FakeUse : FakeUses) {
3179 auto *ClonedInst = FakeUse->clone();
3180 ClonedInst->insertBefore(CI->getIterator());
3181 }
3182 }
3183 DTU->deleteBB(BB);
3184 }
3185
3186 return Changed;
3187}
3188
3189//===----------------------------------------------------------------------===//
3190// Memory Optimization
3191//===----------------------------------------------------------------------===//
3192
3193namespace {
3194
3195/// This is an extended version of TargetLowering::AddrMode
3196/// which holds actual Value*'s for register values.
3197struct ExtAddrMode : public TargetLowering::AddrMode {
3198 Value *BaseReg = nullptr;
3199 Value *ScaledReg = nullptr;
3200 Value *OriginalValue = nullptr;
3201 bool InBounds = true;
3202
3203 enum FieldName {
3204 NoField = 0x00,
3205 BaseRegField = 0x01,
3206 BaseGVField = 0x02,
3207 BaseOffsField = 0x04,
3208 ScaledRegField = 0x08,
3209 ScaleField = 0x10,
3210 MultipleFields = 0xff
3211 };
3212
3213 ExtAddrMode() = default;
3214
3215 void print(raw_ostream &OS) const;
3216 void dump() const;
3217
3218 // Replace From in ExtAddrMode with To.
3219 // E.g., SExt insts may be promoted and deleted. We should replace them with
3220 // the promoted values.
3221 void replaceWith(Value *From, Value *To) {
3222 if (ScaledReg == From)
3223 ScaledReg = To;
3224 }
3225
3226 FieldName compare(const ExtAddrMode &other) {
3227 // First check that the types are the same on each field, as differing types
3228 // is something we can't cope with later on.
3229 if (BaseReg && other.BaseReg &&
3230 BaseReg->getType() != other.BaseReg->getType())
3231 return MultipleFields;
3232 if (BaseGV && other.BaseGV && BaseGV->getType() != other.BaseGV->getType())
3233 return MultipleFields;
3234 if (ScaledReg && other.ScaledReg &&
3235 ScaledReg->getType() != other.ScaledReg->getType())
3236 return MultipleFields;
3237
3238 // Conservatively reject 'inbounds' mismatches.
3239 if (InBounds != other.InBounds)
3240 return MultipleFields;
3241
3242 // Check each field to see if it differs.
3243 unsigned Result = NoField;
3244 if (BaseReg != other.BaseReg)
3245 Result |= BaseRegField;
3246 if (BaseGV != other.BaseGV)
3247 Result |= BaseGVField;
3248 if (BaseOffs != other.BaseOffs)
3249 Result |= BaseOffsField;
3250 if (ScaledReg != other.ScaledReg)
3251 Result |= ScaledRegField;
3252 // Don't count 0 as being a different scale, because that actually means
3253 // unscaled (which will already be counted by having no ScaledReg).
3254 if (Scale && other.Scale && Scale != other.Scale)
3255 Result |= ScaleField;
3256
3257 if (llvm::popcount(Result) > 1)
3258 return MultipleFields;
3259 else
3260 return static_cast<FieldName>(Result);
3261 }
3262
3263 // An AddrMode is trivial if it involves no calculation i.e. it is just a base
3264 // with no offset.
3265 bool isTrivial() {
3266 // An AddrMode is (BaseGV + BaseReg + BaseOffs + ScaleReg * Scale) so it is
3267 // trivial if at most one of these terms is nonzero, except that BaseGV and
3268 // BaseReg both being zero actually means a null pointer value, which we
3269 // consider to be 'non-zero' here.
3270 return !BaseOffs && !Scale && !(BaseGV && BaseReg);
3271 }
3272
3273 Value *GetFieldAsValue(FieldName Field, Type *IntPtrTy) {
3274 switch (Field) {
3275 default:
3276 return nullptr;
3277 case BaseRegField:
3278 return BaseReg;
3279 case BaseGVField:
3280 return BaseGV;
3281 case ScaledRegField:
3282 return ScaledReg;
3283 case BaseOffsField:
3284 return ConstantInt::getSigned(IntPtrTy, BaseOffs);
3285 }
3286 }
3287
3288 void SetCombinedField(FieldName Field, Value *V,
3289 const SmallVectorImpl<ExtAddrMode> &AddrModes) {
3290 switch (Field) {
3291 default:
3292 llvm_unreachable("Unhandled fields are expected to be rejected earlier");
3293 break;
3294 case ExtAddrMode::BaseRegField:
3295 BaseReg = V;
3296 break;
3297 case ExtAddrMode::BaseGVField:
3298 // A combined BaseGV is an Instruction, not a GlobalValue, so it goes
3299 // in the BaseReg field.
3300 assert(BaseReg == nullptr);
3301 BaseReg = V;
3302 BaseGV = nullptr;
3303 break;
3304 case ExtAddrMode::ScaledRegField:
3305 ScaledReg = V;
3306 // If we have a mix of scaled and unscaled addrmodes then we want scale
3307 // to be the scale and not zero.
3308 if (!Scale)
3309 for (const ExtAddrMode &AM : AddrModes)
3310 if (AM.Scale) {
3311 Scale = AM.Scale;
3312 break;
3313 }
3314 break;
3315 case ExtAddrMode::BaseOffsField:
3316 // The offset is no longer a constant, so it goes in ScaledReg with a
3317 // scale of 1.
3318 assert(ScaledReg == nullptr);
3319 ScaledReg = V;
3320 Scale = 1;
3321 BaseOffs = 0;
3322 break;
3323 }
3324 }
3325};
3326
3327#ifndef NDEBUG
3328static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
3329 AM.print(OS);
3330 return OS;
3331}
3332#endif
3333
3334#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3335void ExtAddrMode::print(raw_ostream &OS) const {
3336 bool NeedPlus = false;
3337 OS << "[";
3338 if (InBounds)
3339 OS << "inbounds ";
3340 if (BaseGV) {
3341 OS << "GV:";
3342 BaseGV->printAsOperand(OS, /*PrintType=*/false);
3343 NeedPlus = true;
3344 }
3345
3346 if (BaseOffs) {
3347 OS << (NeedPlus ? " + " : "") << BaseOffs;
3348 NeedPlus = true;
3349 }
3350
3351 if (BaseReg) {
3352 OS << (NeedPlus ? " + " : "") << "Base:";
3353 BaseReg->printAsOperand(OS, /*PrintType=*/false);
3354 NeedPlus = true;
3355 }
3356 if (Scale) {
3357 OS << (NeedPlus ? " + " : "") << Scale << "*";
3358 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
3359 }
3360
3361 OS << ']';
3362}
3363
3364LLVM_DUMP_METHOD void ExtAddrMode::dump() const {
3365 print(dbgs());
3366 dbgs() << '\n';
3367}
3368#endif
3369
3370} // end anonymous namespace
3371
3372namespace {
3373
3374/// This class provides transaction based operation on the IR.
3375/// Every change made through this class is recorded in the internal state and
3376/// can be undone (rollback) until commit is called.
3377/// CGP does not check if instructions could be speculatively executed when
3378/// moved. Preserving the original location would pessimize the debugging
3379/// experience, as well as negatively impact the quality of sample PGO.
3380class TypePromotionTransaction {
3381 /// This represents the common interface of the individual transaction.
3382 /// Each class implements the logic for doing one specific modification on
3383 /// the IR via the TypePromotionTransaction.
3384 class TypePromotionAction {
3385 protected:
3386 /// The Instruction modified.
3387 Instruction *Inst;
3388
3389 public:
3390 /// Constructor of the action.
3391 /// The constructor performs the related action on the IR.
3392 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
3393
3394 virtual ~TypePromotionAction() = default;
3395
3396 /// Undo the modification done by this action.
3397 /// When this method is called, the IR must be in the same state as it was
3398 /// before this action was applied.
3399 /// \pre Undoing the action works if and only if the IR is in the exact same
3400 /// state as it was directly after this action was applied.
3401 virtual void undo() = 0;
3402
3403 /// Advocate every change made by this action.
3404 /// When the results on the IR of the action are to be kept, it is important
3405 /// to call this function, otherwise hidden information may be kept forever.
3406 virtual void commit() {
3407 // Nothing to be done, this action is not doing anything.
3408 }
3409 };
3410
3411 /// Utility to remember the position of an instruction.
3412 class InsertionHandler {
3413 /// Position of an instruction.
3414 /// Either an instruction:
3415 /// - Is the first in a basic block: BB is used.
3416 /// - Has a previous instruction: PrevInst is used.
3417 struct {
3418 BasicBlock::iterator PrevInst;
3419 BasicBlock *BB;
3420 } Point;
3421 std::optional<DbgRecord::self_iterator> BeforeDbgRecord = std::nullopt;
3422
3423 /// Remember whether or not the instruction had a previous instruction.
3424 bool HasPrevInstruction;
3425
3426 public:
3427 /// Record the position of \p Inst.
3428 InsertionHandler(Instruction *Inst) {
3429 HasPrevInstruction = (Inst != &*(Inst->getParent()->begin()));
3430 BasicBlock *BB = Inst->getParent();
3431
3432 // Record where we would have to re-insert the instruction in the sequence
3433 // of DbgRecords, if we ended up reinserting.
3434 BeforeDbgRecord = Inst->getDbgReinsertionPosition();
3435
3436 if (HasPrevInstruction) {
3437 Point.PrevInst = std::prev(Inst->getIterator());
3438 } else {
3439 Point.BB = BB;
3440 }
3441 }
3442
3443 /// Insert \p Inst at the recorded position.
3444 void insert(Instruction *Inst) {
3445 if (HasPrevInstruction) {
3446 if (Inst->getParent())
3447 Inst->removeFromParent();
3448 Inst->insertAfter(Point.PrevInst);
3449 } else {
3450 BasicBlock::iterator Position = Point.BB->getFirstInsertionPt();
3451 if (Inst->getParent())
3452 Inst->moveBefore(*Point.BB, Position);
3453 else
3454 Inst->insertBefore(*Point.BB, Position);
3455 }
3456
3457 Inst->getParent()->reinsertInstInDbgRecords(Inst, BeforeDbgRecord);
3458 }
3459 };
3460
3461 /// Move an instruction before another.
3462 class InstructionMoveBefore : public TypePromotionAction {
3463 /// Original position of the instruction.
3464 InsertionHandler Position;
3465
3466 public:
3467 /// Move \p Inst before \p Before.
3468 InstructionMoveBefore(Instruction *Inst, BasicBlock::iterator Before)
3469 : TypePromotionAction(Inst), Position(Inst) {
3470 LLVM_DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before
3471 << "\n");
3472 Inst->moveBefore(Before);
3473 }
3474
3475 /// Move the instruction back to its original position.
3476 void undo() override {
3477 LLVM_DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
3478 Position.insert(Inst);
3479 }
3480 };
3481
3482 /// Set the operand of an instruction with a new value.
3483 class OperandSetter : public TypePromotionAction {
3484 /// Original operand of the instruction.
3485 Value *Origin;
3486
3487 /// Index of the modified instruction.
3488 unsigned Idx;
3489
3490 public:
3491 /// Set \p Idx operand of \p Inst with \p NewVal.
3492 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
3493 : TypePromotionAction(Inst), Idx(Idx) {
3494 LLVM_DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
3495 << "for:" << *Inst << "\n"
3496 << "with:" << *NewVal << "\n");
3497 Origin = Inst->getOperand(Idx);
3498 Inst->setOperand(Idx, NewVal);
3499 }
3500
3501 /// Restore the original value of the instruction.
3502 void undo() override {
3503 LLVM_DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
3504 << "for: " << *Inst << "\n"
3505 << "with: " << *Origin << "\n");
3506 Inst->setOperand(Idx, Origin);
3507 }
3508 };
3509
3510 /// Hide the operands of an instruction.
3511 /// Do as if this instruction was not using any of its operands.
3512 class OperandsHider : public TypePromotionAction {
3513 /// The list of original operands.
3514 SmallVector<Value *, 4> OriginalValues;
3515
3516 public:
3517 /// Remove \p Inst from the uses of the operands of \p Inst.
3518 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
3519 LLVM_DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
3520 unsigned NumOpnds = Inst->getNumOperands();
3521 OriginalValues.reserve(NumOpnds);
3522 for (unsigned It = 0; It < NumOpnds; ++It) {
3523 // Save the current operand.
3524 Value *Val = Inst->getOperand(It);
3525 OriginalValues.push_back(Val);
3526 // Set a dummy one.
3527 // We could use OperandSetter here, but that would imply an overhead
3528 // that we are not willing to pay.
3529 Inst->setOperand(It, PoisonValue::get(Val->getType()));
3530 }
3531 }
3532
3533 /// Restore the original list of uses.
3534 void undo() override {
3535 LLVM_DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
3536 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
3537 Inst->setOperand(It, OriginalValues[It]);
3538 }
3539 };
3540
3541 /// Build a truncate instruction.
3542 class TruncBuilder : public TypePromotionAction {
3543 Value *Val;
3544
3545 public:
3546 /// Build a truncate instruction of \p Opnd producing a \p Ty
3547 /// result.
3548 /// trunc Opnd to Ty.
3549 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
3550 IRBuilder<> Builder(Opnd);
3551 Builder.SetCurrentDebugLocation(DebugLoc());
3552 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
3553 LLVM_DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
3554 }
3555
3556 /// Get the built value.
3557 Value *getBuiltValue() { return Val; }
3558
3559 /// Remove the built instruction.
3560 void undo() override {
3561 LLVM_DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
3562 if (Instruction *IVal = dyn_cast<Instruction>(Val))
3563 IVal->eraseFromParent();
3564 }
3565 };
3566
3567 /// Build a sign extension instruction.
3568 class SExtBuilder : public TypePromotionAction {
3569 Value *Val;
3570
3571 public:
3572 /// Build a sign extension instruction of \p Opnd producing a \p Ty
3573 /// result.
3574 /// sext Opnd to Ty.
3575 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
3576 : TypePromotionAction(InsertPt) {
3577 IRBuilder<> Builder(InsertPt);
3578 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
3579 LLVM_DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
3580 }
3581
3582 /// Get the built value.
3583 Value *getBuiltValue() { return Val; }
3584
3585 /// Remove the built instruction.
3586 void undo() override {
3587 LLVM_DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
3588 if (Instruction *IVal = dyn_cast<Instruction>(Val))
3589 IVal->eraseFromParent();
3590 }
3591 };
3592
3593 /// Build a zero extension instruction.
3594 class ZExtBuilder : public TypePromotionAction {
3595 Value *Val;
3596
3597 public:
3598 /// Build a zero extension instruction of \p Opnd producing a \p Ty
3599 /// result.
3600 /// zext Opnd to Ty.
3601 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
3602 : TypePromotionAction(InsertPt) {
3603 IRBuilder<> Builder(InsertPt);
3604 Builder.SetCurrentDebugLocation(DebugLoc());
3605 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
3606 LLVM_DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
3607 }
3608
3609 /// Get the built value.
3610 Value *getBuiltValue() { return Val; }
3611
3612 /// Remove the built instruction.
3613 void undo() override {
3614 LLVM_DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
3615 if (Instruction *IVal = dyn_cast<Instruction>(Val))
3616 IVal->eraseFromParent();
3617 }
3618 };
3619
3620 /// Mutate an instruction to another type.
3621 class TypeMutator : public TypePromotionAction {
3622 /// Record the original type.
3623 Type *OrigTy;
3624
3625 public:
3626 /// Mutate the type of \p Inst into \p NewTy.
3627 TypeMutator(Instruction *Inst, Type *NewTy)
3628 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
3629 LLVM_DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
3630 << "\n");
3631 Inst->mutateType(NewTy);
3632 }
3633
3634 /// Mutate the instruction back to its original type.
3635 void undo() override {
3636 LLVM_DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
3637 << "\n");
3638 Inst->mutateType(OrigTy);
3639 }
3640 };
3641
3642 /// Replace the uses of an instruction by another instruction.
3643 class UsesReplacer : public TypePromotionAction {
3644 /// Helper structure to keep track of the replaced uses.
3645 struct InstructionAndIdx {
3646 /// The instruction using the instruction.
3647 Instruction *Inst;
3648
3649 /// The index where this instruction is used for Inst.
3650 unsigned Idx;
3651
3652 InstructionAndIdx(Instruction *Inst, unsigned Idx)
3653 : Inst(Inst), Idx(Idx) {}
3654 };
3655
3656 /// Keep track of the original uses (pair Instruction, Index).
3658 /// Keep track of the debug users.
3659 SmallVector<DbgVariableRecord *, 1> DbgVariableRecords;
3660
3661 /// Keep track of the new value so that we can undo it by replacing
3662 /// instances of the new value with the original value.
3663 Value *New;
3664
3666
3667 public:
3668 /// Replace all the use of \p Inst by \p New.
3669 UsesReplacer(Instruction *Inst, Value *New)
3670 : TypePromotionAction(Inst), New(New) {
3671 LLVM_DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
3672 << "\n");
3673 // Record the original uses.
3674 for (Use &U : Inst->uses()) {
3675 Instruction *UserI = cast<Instruction>(U.getUser());
3676 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
3677 }
3678 // Record the debug uses separately. They are not in the instruction's
3679 // use list, but they are replaced by RAUW.
3680 findDbgValues(Inst, DbgVariableRecords);
3681
3682 // Now, we can replace the uses.
3683 Inst->replaceAllUsesWith(New);
3684 }
3685
3686 /// Reassign the original uses of Inst to Inst.
3687 void undo() override {
3688 LLVM_DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
3689 for (InstructionAndIdx &Use : OriginalUses)
3690 Use.Inst->setOperand(Use.Idx, Inst);
3691 // RAUW has replaced all original uses with references to the new value,
3692 // including the debug uses. Since we are undoing the replacements,
3693 // the original debug uses must also be reinstated to maintain the
3694 // correctness and utility of debug value records.
3695 for (DbgVariableRecord *DVR : DbgVariableRecords)
3696 DVR->replaceVariableLocationOp(New, Inst);
3697 }
3698 };
3699
3700 /// Remove an instruction from the IR.
3701 class InstructionRemover : public TypePromotionAction {
3702 /// Original position of the instruction.
3703 InsertionHandler Inserter;
3704
3705 /// Helper structure to hide all the link to the instruction. In other
3706 /// words, this helps to do as if the instruction was removed.
3707 OperandsHider Hider;
3708
3709 /// Keep track of the uses replaced, if any.
3710 UsesReplacer *Replacer = nullptr;
3711
3712 /// Keep track of instructions removed.
3713 SetOfInstrs &RemovedInsts;
3714
3715 public:
3716 /// Remove all reference of \p Inst and optionally replace all its
3717 /// uses with New.
3718 /// \p RemovedInsts Keep track of the instructions removed by this Action.
3719 /// \pre If !Inst->use_empty(), then New != nullptr
3720 InstructionRemover(Instruction *Inst, SetOfInstrs &RemovedInsts,
3721 Value *New = nullptr)
3722 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
3723 RemovedInsts(RemovedInsts) {
3724 if (New)
3725 Replacer = new UsesReplacer(Inst, New);
3726 LLVM_DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
3727 RemovedInsts.insert(Inst);
3728 /// The instructions removed here will be freed after completing
3729 /// optimizeBlock() for all blocks as we need to keep track of the
3730 /// removed instructions during promotion.
3731 Inst->removeFromParent();
3732 }
3733
3734 ~InstructionRemover() override { delete Replacer; }
3735
3736 InstructionRemover &operator=(const InstructionRemover &other) = delete;
3737 InstructionRemover(const InstructionRemover &other) = delete;
3738
3739 /// Resurrect the instruction and reassign it to the proper uses if
3740 /// new value was provided when build this action.
3741 void undo() override {
3742 LLVM_DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
3743 Inserter.insert(Inst);
3744 if (Replacer)
3745 Replacer->undo();
3746 Hider.undo();
3747 RemovedInsts.erase(Inst);
3748 }
3749 };
3750
3751public:
3752 /// Restoration point.
3753 /// The restoration point is a pointer to an action instead of an iterator
3754 /// because the iterator may be invalidated but not the pointer.
3755 using ConstRestorationPt = const TypePromotionAction *;
3756
3757 TypePromotionTransaction(SetOfInstrs &RemovedInsts)
3758 : RemovedInsts(RemovedInsts) {}
3759
3760 /// Advocate every changes made in that transaction. Return true if any change
3761 /// happen.
3762 bool commit();
3763
3764 /// Undo all the changes made after the given point.
3765 void rollback(ConstRestorationPt Point);
3766
3767 /// Get the current restoration point.
3768 ConstRestorationPt getRestorationPoint() const;
3769
3770 /// \name API for IR modification with state keeping to support rollback.
3771 /// @{
3772 /// Same as Instruction::setOperand.
3773 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
3774
3775 /// Same as Instruction::eraseFromParent.
3776 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
3777
3778 /// Same as Value::replaceAllUsesWith.
3779 void replaceAllUsesWith(Instruction *Inst, Value *New);
3780
3781 /// Same as Value::mutateType.
3782 void mutateType(Instruction *Inst, Type *NewTy);
3783
3784 /// Same as IRBuilder::createTrunc.
3785 Value *createTrunc(Instruction *Opnd, Type *Ty);
3786
3787 /// Same as IRBuilder::createSExt.
3788 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
3789
3790 /// Same as IRBuilder::createZExt.
3791 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
3792
3793private:
3794 /// The ordered list of actions made so far.
3796
3797 using CommitPt =
3798 SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator;
3799
3800 SetOfInstrs &RemovedInsts;
3801};
3802
3803} // end anonymous namespace
3804
3805void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
3806 Value *NewVal) {
3807 Actions.push_back(std::make_unique<TypePromotionTransaction::OperandSetter>(
3808 Inst, Idx, NewVal));
3809}
3810
3811void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
3812 Value *NewVal) {
3813 Actions.push_back(
3814 std::make_unique<TypePromotionTransaction::InstructionRemover>(
3815 Inst, RemovedInsts, NewVal));
3816}
3817
3818void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
3819 Value *New) {
3820 Actions.push_back(
3821 std::make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
3822}
3823
3824void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
3825 Actions.push_back(
3826 std::make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
3827}
3828
3829Value *TypePromotionTransaction::createTrunc(Instruction *Opnd, Type *Ty) {
3830 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
3831 Value *Val = Ptr->getBuiltValue();
3832 Actions.push_back(std::move(Ptr));
3833 return Val;
3834}
3835
3836Value *TypePromotionTransaction::createSExt(Instruction *Inst, Value *Opnd,
3837 Type *Ty) {
3838 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
3839 Value *Val = Ptr->getBuiltValue();
3840 Actions.push_back(std::move(Ptr));
3841 return Val;
3842}
3843
3844Value *TypePromotionTransaction::createZExt(Instruction *Inst, Value *Opnd,
3845 Type *Ty) {
3846 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
3847 Value *Val = Ptr->getBuiltValue();
3848 Actions.push_back(std::move(Ptr));
3849 return Val;
3850}
3851
3852TypePromotionTransaction::ConstRestorationPt
3853TypePromotionTransaction::getRestorationPoint() const {
3854 return !Actions.empty() ? Actions.back().get() : nullptr;
3855}
3856
3857bool TypePromotionTransaction::commit() {
3858 for (std::unique_ptr<TypePromotionAction> &Action : Actions)
3859 Action->commit();
3860 bool Modified = !Actions.empty();
3861 Actions.clear();
3862 return Modified;
3863}
3864
3865void TypePromotionTransaction::rollback(
3866 TypePromotionTransaction::ConstRestorationPt Point) {
3867 while (!Actions.empty() && Point != Actions.back().get()) {
3868 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
3869 Curr->undo();
3870 }
3871}
3872
3873namespace {
3874
3875/// A helper class for matching addressing modes.
3876///
3877/// This encapsulates the logic for matching the target-legal addressing modes.
3878class AddressingModeMatcher {
3879 SmallVectorImpl<Instruction *> &AddrModeInsts;
3880 const TargetLowering &TLI;
3881 const TargetRegisterInfo &TRI;
3882 const DataLayout &DL;
3883 const LoopInfo &LI;
3884 const std::function<const DominatorTree &()> getDTFn;
3885
3886 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
3887 /// the memory instruction that we're computing this address for.
3888 Type *AccessTy;
3889 unsigned AddrSpace;
3890 Instruction *MemoryInst;
3891
3892 /// This is the addressing mode that we're building up. This is
3893 /// part of the return value of this addressing mode matching stuff.
3894 ExtAddrMode &AddrMode;
3895
3896 /// The instructions inserted by other CodeGenPrepare optimizations.
3897 const SetOfInstrs &InsertedInsts;
3898
3899 /// A map from the instructions to their type before promotion.
3900 InstrToOrigTy &PromotedInsts;
3901
3902 /// The ongoing transaction where every action should be registered.
3903 TypePromotionTransaction &TPT;
3904
3905 // A GEP which has too large offset to be folded into the addressing mode.
3906 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP;
3907
3908 /// This is set to true when we should not do profitability checks.
3909 /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
3910 bool IgnoreProfitability;
3911
3912 /// True if we are optimizing for size.
3913 bool OptSize = false;
3914
3915 ProfileSummaryInfo *PSI;
3916 BlockFrequencyInfo *BFI;
3917
3918 AddressingModeMatcher(
3919 SmallVectorImpl<Instruction *> &AMI, const TargetLowering &TLI,
3920 const TargetRegisterInfo &TRI, const LoopInfo &LI,
3921 const std::function<const DominatorTree &()> getDTFn, Type *AT,
3922 unsigned AS, Instruction *MI, ExtAddrMode &AM,
3923 const SetOfInstrs &InsertedInsts, InstrToOrigTy &PromotedInsts,
3924 TypePromotionTransaction &TPT,
3925 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP,
3926 bool OptSize, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI)
3927 : AddrModeInsts(AMI), TLI(TLI), TRI(TRI),
3928 DL(MI->getDataLayout()), LI(LI), getDTFn(getDTFn),
3929 AccessTy(AT), AddrSpace(AS), MemoryInst(MI), AddrMode(AM),
3930 InsertedInsts(InsertedInsts), PromotedInsts(PromotedInsts), TPT(TPT),
3931 LargeOffsetGEP(LargeOffsetGEP), OptSize(OptSize), PSI(PSI), BFI(BFI) {
3932 IgnoreProfitability = false;
3933 }
3934
3935public:
3936 /// Find the maximal addressing mode that a load/store of V can fold,
3937 /// give an access type of AccessTy. This returns a list of involved
3938 /// instructions in AddrModeInsts.
3939 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
3940 /// optimizations.
3941 /// \p PromotedInsts maps the instructions to their type before promotion.
3942 /// \p The ongoing transaction where every action should be registered.
3943 static ExtAddrMode
3944 Match(Value *V, Type *AccessTy, unsigned AS, Instruction *MemoryInst,
3945 SmallVectorImpl<Instruction *> &AddrModeInsts,
3946 const TargetLowering &TLI, const LoopInfo &LI,
3947 const std::function<const DominatorTree &()> getDTFn,
3948 const TargetRegisterInfo &TRI, const SetOfInstrs &InsertedInsts,
3949 InstrToOrigTy &PromotedInsts, TypePromotionTransaction &TPT,
3950 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP,
3951 bool OptSize, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI) {
3952 ExtAddrMode Result;
3953
3954 bool Success = AddressingModeMatcher(AddrModeInsts, TLI, TRI, LI, getDTFn,
3955 AccessTy, AS, MemoryInst, Result,
3956 InsertedInsts, PromotedInsts, TPT,
3957 LargeOffsetGEP, OptSize, PSI, BFI)
3958 .matchAddr(V, 0);
3959 (void)Success;
3960 assert(Success && "Couldn't select *anything*?");
3961 return Result;
3962 }
3963
3964private:
3965 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
3966 bool matchAddr(Value *Addr, unsigned Depth);
3967 bool matchOperationAddr(User *AddrInst, unsigned Opcode, unsigned Depth,
3968 bool *MovedAway = nullptr);
3969 bool isProfitableToFoldIntoAddressingMode(Instruction *I,
3970 ExtAddrMode &AMBefore,
3971 ExtAddrMode &AMAfter);
3972 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
3973 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
3974 Value *PromotedOperand) const;
3975};
3976
3977class PhiNodeSet;
3978
3979/// An iterator for PhiNodeSet.
3980class PhiNodeSetIterator {
3981 PhiNodeSet *const Set;
3982 size_t CurrentIndex = 0;
3983
3984public:
3985 /// The constructor. Start should point to either a valid element, or be equal
3986 /// to the size of the underlying SmallVector of the PhiNodeSet.
3987 PhiNodeSetIterator(PhiNodeSet *const Set, size_t Start);
3988 PHINode *operator*() const;
3989 PhiNodeSetIterator &operator++();
3990 bool operator==(const PhiNodeSetIterator &RHS) const;
3991 bool operator!=(const PhiNodeSetIterator &RHS) const;
3992};
3993
3994/// Keeps a set of PHINodes.
3995///
3996/// This is a minimal set implementation for a specific use case:
3997/// It is very fast when there are very few elements, but also provides good
3998/// performance when there are many. It is similar to SmallPtrSet, but also
3999/// provides iteration by insertion order, which is deterministic and stable
4000/// across runs. It is also similar to SmallSetVector, but provides removing
4001/// elements in O(1) time. This is achieved by not actually removing the element
4002/// from the underlying vector, so comes at the cost of using more memory, but
4003/// that is fine, since PhiNodeSets are used as short lived objects.
4004class PhiNodeSet {
4005 friend class PhiNodeSetIterator;
4006
4007 using MapType = SmallDenseMap<PHINode *, size_t, 32>;
4008 using iterator = PhiNodeSetIterator;
4009
4010 /// Keeps the elements in the order of their insertion in the underlying
4011 /// vector. To achieve constant time removal, it never deletes any element.
4013
4014 /// Keeps the elements in the underlying set implementation. This (and not the
4015 /// NodeList defined above) is the source of truth on whether an element
4016 /// is actually in the collection.
4017 MapType NodeMap;
4018
4019 /// Points to the first valid (not deleted) element when the set is not empty
4020 /// and the value is not zero. Equals to the size of the underlying vector
4021 /// when the set is empty. When the value is 0, as in the beginning, the
4022 /// first element may or may not be valid.
4023 size_t FirstValidElement = 0;
4024
4025public:
4026 /// Inserts a new element to the collection.
4027 /// \returns true if the element is actually added, i.e. was not in the
4028 /// collection before the operation.
4029 bool insert(PHINode *Ptr) {
4030 if (NodeMap.insert(std::make_pair(Ptr, NodeList.size())).second) {
4031 NodeList.push_back(Ptr);
4032 return true;
4033 }
4034 return false;
4035 }
4036
4037 /// Removes the element from the collection.
4038 /// \returns whether the element is actually removed, i.e. was in the
4039 /// collection before the operation.
4040 bool erase(PHINode *Ptr) {
4041 if (NodeMap.erase(Ptr)) {
4042 SkipRemovedElements(FirstValidElement);
4043 return true;
4044 }
4045 return false;
4046 }
4047
4048 /// Removes all elements and clears the collection.
4049 void clear() {
4050 NodeMap.clear();
4051 NodeList.clear();
4052 FirstValidElement = 0;
4053 }
4054
4055 /// \returns an iterator that will iterate the elements in the order of
4056 /// insertion.
4057 iterator begin() {
4058 if (FirstValidElement == 0)
4059 SkipRemovedElements(FirstValidElement);
4060 return PhiNodeSetIterator(this, FirstValidElement);
4061 }
4062
4063 /// \returns an iterator that points to the end of the collection.
4064 iterator end() { return PhiNodeSetIterator(this, NodeList.size()); }
4065
4066 /// Returns the number of elements in the collection.
4067 size_t size() const { return NodeMap.size(); }
4068
4069 /// \returns 1 if the given element is in the collection, and 0 if otherwise.
4070 size_t count(PHINode *Ptr) const { return NodeMap.count(Ptr); }
4071
4072private:
4073 /// Updates the CurrentIndex so that it will point to a valid element.
4074 ///
4075 /// If the element of NodeList at CurrentIndex is valid, it does not
4076 /// change it. If there are no more valid elements, it updates CurrentIndex
4077 /// to point to the end of the NodeList.
4078 void SkipRemovedElements(size_t &CurrentIndex) {
4079 while (CurrentIndex < NodeList.size()) {
4080 auto it = NodeMap.find(NodeList[CurrentIndex]);
4081 // If the element has been deleted and added again later, NodeMap will
4082 // point to a different index, so CurrentIndex will still be invalid.
4083 if (it != NodeMap.end() && it->second == CurrentIndex)
4084 break;
4085 ++CurrentIndex;
4086 }
4087 }
4088};
4089
4090PhiNodeSetIterator::PhiNodeSetIterator(PhiNodeSet *const Set, size_t Start)
4091 : Set(Set), CurrentIndex(Start) {}
4092
4093PHINode *PhiNodeSetIterator::operator*() const {
4094 assert(CurrentIndex < Set->NodeList.size() &&
4095 "PhiNodeSet access out of range");
4096 return Set->NodeList[CurrentIndex];
4097}
4098
4099PhiNodeSetIterator &PhiNodeSetIterator::operator++() {
4100 assert(CurrentIndex < Set->NodeList.size() &&
4101 "PhiNodeSet access out of range");
4102 ++CurrentIndex;
4103 Set->SkipRemovedElements(CurrentIndex);
4104 return *this;
4105}
4106
4107bool PhiNodeSetIterator::operator==(const PhiNodeSetIterator &RHS) const {
4108 return CurrentIndex == RHS.CurrentIndex;
4109}
4110
4111bool PhiNodeSetIterator::operator!=(const PhiNodeSetIterator &RHS) const {
4112 return !((*this) == RHS);
4113}
4114
4115/// Keep track of simplification of Phi nodes.
4116/// Accept the set of all phi nodes and erase phi node from this set
4117/// if it is simplified.
4118class SimplificationTracker {
4119 DenseMap<Value *, Value *> Storage;
4120 // Tracks newly created Phi nodes. The elements are iterated by insertion
4121 // order.
4122 PhiNodeSet AllPhiNodes;
4123 // Tracks newly created Select nodes.
4124 SmallPtrSet<SelectInst *, 32> AllSelectNodes;
4125
4126public:
4127 Value *Get(Value *V) {
4128 do {
4129 auto SV = Storage.find(V);
4130 if (SV == Storage.end())
4131 return V;
4132 V = SV->second;
4133 } while (true);
4134 }
4135
4136 void Put(Value *From, Value *To) { Storage.insert({From, To}); }
4137
4138 void ReplacePhi(PHINode *From, PHINode *To) {
4139 Value *OldReplacement = Get(From);
4140 while (OldReplacement != From) {
4141 From = To;
4142 To = dyn_cast<PHINode>(OldReplacement);
4143 OldReplacement = Get(From);
4144 }
4145 assert(To && Get(To) == To && "Replacement PHI node is already replaced.");
4146 Put(From, To);
4147 From->replaceAllUsesWith(To);
4148 AllPhiNodes.erase(From);
4149 From->eraseFromParent();
4150 }
4151
4152 PhiNodeSet &newPhiNodes() { return AllPhiNodes; }
4153
4154 void insertNewPhi(PHINode *PN) { AllPhiNodes.insert(PN); }
4155
4156 void insertNewSelect(SelectInst *SI) { AllSelectNodes.insert(SI); }
4157
4158 unsigned countNewPhiNodes() const { return AllPhiNodes.size(); }
4159
4160 unsigned countNewSelectNodes() const { return AllSelectNodes.size(); }
4161
4162 void destroyNewNodes(Type *CommonType) {
4163 // For safe erasing, replace the uses with dummy value first.
4164 auto *Dummy = PoisonValue::get(CommonType);
4165 for (auto *I : AllPhiNodes) {
4166 I->replaceAllUsesWith(Dummy);
4167 I->eraseFromParent();
4168 }
4169 AllPhiNodes.clear();
4170 for (auto *I : AllSelectNodes) {
4171 I->replaceAllUsesWith(Dummy);
4172 I->eraseFromParent();
4173 }
4174 AllSelectNodes.clear();
4175 }
4176};
4177
4178/// A helper class for combining addressing modes.
4179class AddressingModeCombiner {
4180 typedef DenseMap<Value *, Value *> FoldAddrToValueMapping;
4181 typedef std::pair<PHINode *, PHINode *> PHIPair;
4182
4183private:
4184 /// The addressing modes we've collected.
4186
4187 /// The field in which the AddrModes differ, when we have more than one.
4188 ExtAddrMode::FieldName DifferentField = ExtAddrMode::NoField;
4189
4190 /// Are the AddrModes that we have all just equal to their original values?
4191 bool AllAddrModesTrivial = true;
4192
4193 /// Common Type for all different fields in addressing modes.
4194 Type *CommonType = nullptr;
4195
4196 const DataLayout &DL;
4197
4198 /// Original Address.
4199 Value *Original;
4200
4201 /// Common value among addresses
4202 Value *CommonValue = nullptr;
4203
4204public:
4205 AddressingModeCombiner(const DataLayout &DL, Value *OriginalValue)
4206 : DL(DL), Original(OriginalValue) {}
4207
4208 ~AddressingModeCombiner() { eraseCommonValueIfDead(); }
4209
4210 /// Get the combined AddrMode
4211 const ExtAddrMode &getAddrMode() const { return AddrModes[0]; }
4212
4213 /// Add a new AddrMode if it's compatible with the AddrModes we already
4214 /// have.
4215 /// \return True iff we succeeded in doing so.
4216 bool addNewAddrMode(ExtAddrMode &NewAddrMode) {
4217 // Take note of if we have any non-trivial AddrModes, as we need to detect
4218 // when all AddrModes are trivial as then we would introduce a phi or select
4219 // which just duplicates what's already there.
4220 AllAddrModesTrivial = AllAddrModesTrivial && NewAddrMode.isTrivial();
4221
4222 // If this is the first addrmode then everything is fine.
4223 if (AddrModes.empty()) {
4224 AddrModes.emplace_back(NewAddrMode);
4225 return true;
4226 }
4227
4228 // Figure out how different this is from the other address modes, which we
4229 // can do just by comparing against the first one given that we only care
4230 // about the cumulative difference.
4231 ExtAddrMode::FieldName ThisDifferentField =
4232 AddrModes[0].compare(NewAddrMode);
4233 if (DifferentField == ExtAddrMode::NoField)
4234 DifferentField = ThisDifferentField;
4235 else if (DifferentField != ThisDifferentField)
4236 DifferentField = ExtAddrMode::MultipleFields;
4237
4238 // If NewAddrMode differs in more than one dimension we cannot handle it.
4239 bool CanHandle = DifferentField != ExtAddrMode::MultipleFields;
4240
4241 // If Scale Field is different then we reject.
4242 CanHandle = CanHandle && DifferentField != ExtAddrMode::ScaleField;
4243
4244 // We also must reject the case when base offset is different and
4245 // scale reg is not null, we cannot handle this case due to merge of
4246 // different offsets will be used as ScaleReg.
4247 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseOffsField ||
4248 !NewAddrMode.ScaledReg);
4249
4250 // We also must reject the case when GV is different and BaseReg installed
4251 // due to we want to use base reg as a merge of GV values.
4252 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseGVField ||
4253 !NewAddrMode.HasBaseReg);
4254
4255 // Even if NewAddMode is the same we still need to collect it due to
4256 // original value is different. And later we will need all original values
4257 // as anchors during finding the common Phi node.
4258 if (CanHandle)
4259 AddrModes.emplace_back(NewAddrMode);
4260 else
4261 AddrModes.clear();
4262
4263 return CanHandle;
4264 }
4265
4266 /// Combine the addressing modes we've collected into a single
4267 /// addressing mode.
4268 /// \return True iff we successfully combined them or we only had one so
4269 /// didn't need to combine them anyway.
4270 bool combineAddrModes() {
4271 // If we have no AddrModes then they can't be combined.
4272 if (AddrModes.size() == 0)
4273 return false;
4274
4275 // A single AddrMode can trivially be combined.
4276 if (AddrModes.size() == 1 || DifferentField == ExtAddrMode::NoField)
4277 return true;
4278
4279 // If the AddrModes we collected are all just equal to the value they are
4280 // derived from then combining them wouldn't do anything useful.
4281 if (AllAddrModesTrivial)
4282 return false;
4283
4284 if (!addrModeCombiningAllowed())
4285 return false;
4286
4287 // Build a map between <original value, basic block where we saw it> to
4288 // value of base register.
4289 // Bail out if there is no common type.
4290 FoldAddrToValueMapping Map;
4291 if (!initializeMap(Map))
4292 return false;
4293
4294 CommonValue = findCommon(Map);
4295 if (CommonValue)
4296 AddrModes[0].SetCombinedField(DifferentField, CommonValue, AddrModes);
4297 return CommonValue != nullptr;
4298 }
4299
4300private:
4301 /// `CommonValue` may be a placeholder inserted by us.
4302 /// If the placeholder is not used, we should remove this dead instruction.
4303 void eraseCommonValueIfDead() {
4304 if (CommonValue && CommonValue->use_empty())
4305 if (Instruction *CommonInst = dyn_cast<Instruction>(CommonValue))
4306 CommonInst->eraseFromParent();
4307 }
4308
4309 /// Initialize Map with anchor values. For address seen
4310 /// we set the value of different field saw in this address.
4311 /// At the same time we find a common type for different field we will
4312 /// use to create new Phi/Select nodes. Keep it in CommonType field.
4313 /// Return false if there is no common type found.
4314 bool initializeMap(FoldAddrToValueMapping &Map) {
4315 // Keep track of keys where the value is null. We will need to replace it
4316 // with constant null when we know the common type.
4317 SmallVector<Value *, 2> NullValue;
4318 Type *IntPtrTy = DL.getIntPtrType(AddrModes[0].OriginalValue->getType());
4319 for (auto &AM : AddrModes) {
4320 Value *DV = AM.GetFieldAsValue(DifferentField, IntPtrTy);
4321 if (DV) {
4322 auto *Type = DV->getType();
4323 if (CommonType && CommonType != Type)
4324 return false;
4325 CommonType = Type;
4326 Map[AM.OriginalValue] = DV;
4327 } else {
4328 NullValue.push_back(AM.OriginalValue);
4329 }
4330 }
4331 assert(CommonType && "At least one non-null value must be!");
4332 for (auto *V : NullValue)
4333 Map[V] = Constant::getNullValue(CommonType);
4334 return true;
4335 }
4336
4337 /// We have mapping between value A and other value B where B was a field in
4338 /// addressing mode represented by A. Also we have an original value C
4339 /// representing an address we start with. Traversing from C through phi and
4340 /// selects we ended up with A's in a map. This utility function tries to find
4341 /// a value V which is a field in addressing mode C and traversing through phi
4342 /// nodes and selects we will end up in corresponded values B in a map.
4343 /// The utility will create a new Phi/Selects if needed.
4344 // The simple example looks as follows:
4345 // BB1:
4346 // p1 = b1 + 40
4347 // br cond BB2, BB3
4348 // BB2:
4349 // p2 = b2 + 40
4350 // br BB3
4351 // BB3:
4352 // p = phi [p1, BB1], [p2, BB2]
4353 // v = load p
4354 // Map is
4355 // p1 -> b1
4356 // p2 -> b2
4357 // Request is
4358 // p -> ?
4359 // The function tries to find or build phi [b1, BB1], [b2, BB2] in BB3.
4360 Value *findCommon(FoldAddrToValueMapping &Map) {
4361 // Tracks the simplification of newly created phi nodes. The reason we use
4362 // this mapping is because we will add new created Phi nodes in AddrToBase.
4363 // Simplification of Phi nodes is recursive, so some Phi node may
4364 // be simplified after we added it to AddrToBase. In reality this
4365 // simplification is possible only if original phi/selects were not
4366 // simplified yet.
4367 // Using this mapping we can find the current value in AddrToBase.
4368 SimplificationTracker ST;
4369
4370 // First step, DFS to create PHI nodes for all intermediate blocks.
4371 // Also fill traverse order for the second step.
4372 SmallVector<Value *, 32> TraverseOrder;
4373 InsertPlaceholders(Map, TraverseOrder, ST);
4374
4375 // Second Step, fill new nodes by merged values and simplify if possible.
4376 FillPlaceholders(Map, TraverseOrder, ST);
4377
4378 if (!AddrSinkNewSelects && ST.countNewSelectNodes() > 0) {
4379 ST.destroyNewNodes(CommonType);
4380 return nullptr;
4381 }
4382
4383 // Now we'd like to match New Phi nodes to existed ones.
4384 unsigned PhiNotMatchedCount = 0;
4385 if (!MatchPhiSet(ST, AddrSinkNewPhis, PhiNotMatchedCount)) {
4386 ST.destroyNewNodes(CommonType);
4387 return nullptr;
4388 }
4389
4390 auto *Result = ST.Get(Map.find(Original)->second);
4391 if (Result) {
4392 NumMemoryInstsPhiCreated += ST.countNewPhiNodes() + PhiNotMatchedCount;
4393 NumMemoryInstsSelectCreated += ST.countNewSelectNodes();
4394 }
4395 return Result;
4396 }
4397
4398 /// Try to match PHI node to Candidate.
4399 /// Matcher tracks the matched Phi nodes.
4400 bool MatchPhiNode(PHINode *PHI, PHINode *Candidate,
4401 SmallSetVector<PHIPair, 8> &Matcher,
4402 PhiNodeSet &PhiNodesToMatch) {
4403 SmallVector<PHIPair, 8> WorkList;
4404 Matcher.insert({PHI, Candidate});
4405 SmallPtrSet<PHINode *, 8> MatchedPHIs;
4406 MatchedPHIs.insert(PHI);
4407 WorkList.push_back({PHI, Candidate});
4408 SmallSet<PHIPair, 8> Visited;
4409 while (!WorkList.empty()) {
4410 auto Item = WorkList.pop_back_val();
4411 if (!Visited.insert(Item).second)
4412 continue;
4413 // We iterate over all incoming values to Phi to compare them.
4414 // If values are different and both of them Phi and the first one is a
4415 // Phi we added (subject to match) and both of them is in the same basic
4416 // block then we can match our pair if values match. So we state that
4417 // these values match and add it to work list to verify that.
4418 for (auto *B : Item.first->blocks()) {
4419 Value *FirstValue = Item.first->getIncomingValueForBlock(B);
4420 Value *SecondValue = Item.second->getIncomingValueForBlock(B);
4421 if (FirstValue == SecondValue)
4422 continue;
4423
4424 PHINode *FirstPhi = dyn_cast<PHINode>(FirstValue);
4425 PHINode *SecondPhi = dyn_cast<PHINode>(SecondValue);
4426
4427 // One of them is not Phi or
4428 // The first one is not Phi node from the set we'd like to match or
4429 // Phi nodes from different basic blocks then
4430 // we will not be able to match.
4431 if (!FirstPhi || !SecondPhi || !PhiNodesToMatch.count(FirstPhi) ||
4432 FirstPhi->getParent() != SecondPhi->getParent())
4433 return false;
4434
4435 // If we already matched them then continue.
4436 if (Matcher.count({FirstPhi, SecondPhi}))
4437 continue;
4438 // So the values are different and does not match. So we need them to
4439 // match. (But we register no more than one match per PHI node, so that
4440 // we won't later try to replace them twice.)
4441 if (MatchedPHIs.insert(FirstPhi).second)
4442 Matcher.insert({FirstPhi, SecondPhi});
4443 // But me must check it.
4444 WorkList.push_back({FirstPhi, SecondPhi});
4445 }
4446 }
4447 return true;
4448 }
4449
4450 /// For the given set of PHI nodes (in the SimplificationTracker) try
4451 /// to find their equivalents.
4452 /// Returns false if this matching fails and creation of new Phi is disabled.
4453 bool MatchPhiSet(SimplificationTracker &ST, bool AllowNewPhiNodes,
4454 unsigned &PhiNotMatchedCount) {
4455 // Matched and PhiNodesToMatch iterate their elements in a deterministic
4456 // order, so the replacements (ReplacePhi) are also done in a deterministic
4457 // order.
4458 SmallSetVector<PHIPair, 8> Matched;
4459 SmallPtrSet<PHINode *, 8> WillNotMatch;
4460 PhiNodeSet &PhiNodesToMatch = ST.newPhiNodes();
4461 while (PhiNodesToMatch.size()) {
4462 PHINode *PHI = *PhiNodesToMatch.begin();
4463
4464 // Add us, if no Phi nodes in the basic block we do not match.
4465 WillNotMatch.clear();
4466 WillNotMatch.insert(PHI);
4467
4468 // Traverse all Phis until we found equivalent or fail to do that.
4469 bool IsMatched = false;
4470 for (auto &P : PHI->getParent()->phis()) {
4471 // Skip new Phi nodes.
4472 if (PhiNodesToMatch.count(&P))
4473 continue;
4474 if ((IsMatched = MatchPhiNode(PHI, &P, Matched, PhiNodesToMatch)))
4475 break;
4476 // If it does not match, collect all Phi nodes from matcher.
4477 // if we end up with no match, them all these Phi nodes will not match
4478 // later.
4479 WillNotMatch.insert_range(llvm::make_first_range(Matched));
4480 Matched.clear();
4481 }
4482 if (IsMatched) {
4483 // Replace all matched values and erase them.
4484 for (auto MV : Matched)
4485 ST.ReplacePhi(MV.first, MV.second);
4486 Matched.clear();
4487 continue;
4488 }
4489 // If we are not allowed to create new nodes then bail out.
4490 if (!AllowNewPhiNodes)
4491 return false;
4492 // Just remove all seen values in matcher. They will not match anything.
4493 PhiNotMatchedCount += WillNotMatch.size();
4494 for (auto *P : WillNotMatch)
4495 PhiNodesToMatch.erase(P);
4496 }
4497 return true;
4498 }
4499 /// Fill the placeholders with values from predecessors and simplify them.
4500 void FillPlaceholders(FoldAddrToValueMapping &Map,
4501 SmallVectorImpl<Value *> &TraverseOrder,
4502 SimplificationTracker &ST) {
4503 while (!TraverseOrder.empty()) {
4504 Value *Current = TraverseOrder.pop_back_val();
4505 assert(Map.contains(Current) && "No node to fill!!!");
4506 Value *V = Map[Current];
4507
4508 if (SelectInst *Select = dyn_cast<SelectInst>(V)) {
4509 // CurrentValue also must be Select.
4510 auto *CurrentSelect = cast<SelectInst>(Current);
4511 auto *TrueValue = CurrentSelect->getTrueValue();
4512 assert(Map.contains(TrueValue) && "No True Value!");
4513 Select->setTrueValue(ST.Get(Map[TrueValue]));
4514 auto *FalseValue = CurrentSelect->getFalseValue();
4515 assert(Map.contains(FalseValue) && "No False Value!");
4516 Select->setFalseValue(ST.Get(Map[FalseValue]));
4517 } else {
4518 // Must be a Phi node then.
4519 auto *PHI = cast<PHINode>(V);
4520 // Fill the Phi node with values from predecessors.
4521 for (auto *B : predecessors(PHI->getParent())) {
4522 Value *PV = cast<PHINode>(Current)->getIncomingValueForBlock(B);
4523 assert(Map.contains(PV) && "No predecessor Value!");
4524 PHI->addIncoming(ST.Get(Map[PV]), B);
4525 }
4526 }
4527 }
4528 }
4529
4530 /// Starting from original value recursively iterates over def-use chain up to
4531 /// known ending values represented in a map. For each traversed phi/select
4532 /// inserts a placeholder Phi or Select.
4533 /// Reports all new created Phi/Select nodes by adding them to set.
4534 /// Also reports and order in what values have been traversed.
4535 void InsertPlaceholders(FoldAddrToValueMapping &Map,
4536 SmallVectorImpl<Value *> &TraverseOrder,
4537 SimplificationTracker &ST) {
4538 SmallVector<Value *, 32> Worklist;
4539 assert((isa<PHINode>(Original) || isa<SelectInst>(Original)) &&
4540 "Address must be a Phi or Select node");
4541 auto *Dummy = PoisonValue::get(CommonType);
4542 Worklist.push_back(Original);
4543 while (!Worklist.empty()) {
4544 Value *Current = Worklist.pop_back_val();
4545 // if it is already visited or it is an ending value then skip it.
4546 if (Map.contains(Current))
4547 continue;
4548 TraverseOrder.push_back(Current);
4549
4550 // CurrentValue must be a Phi node or select. All others must be covered
4551 // by anchors.
4552 if (SelectInst *CurrentSelect = dyn_cast<SelectInst>(Current)) {
4553 // Is it OK to get metadata from OrigSelect?!
4554 // Create a Select placeholder with dummy value.
4555 SelectInst *Select =
4556 SelectInst::Create(CurrentSelect->getCondition(), Dummy, Dummy,
4557 CurrentSelect->getName(),
4558 CurrentSelect->getIterator(), CurrentSelect);
4559 Map[Current] = Select;
4560 ST.insertNewSelect(Select);
4561 // We are interested in True and False values.
4562 Worklist.push_back(CurrentSelect->getTrueValue());
4563 Worklist.push_back(CurrentSelect->getFalseValue());
4564 } else {
4565 // It must be a Phi node then.
4566 PHINode *CurrentPhi = cast<PHINode>(Current);
4567 unsigned PredCount = CurrentPhi->getNumIncomingValues();
4568 PHINode *PHI =
4569 PHINode::Create(CommonType, PredCount, "sunk_phi", CurrentPhi->getIterator());
4570 Map[Current] = PHI;
4571 ST.insertNewPhi(PHI);
4572 append_range(Worklist, CurrentPhi->incoming_values());
4573 }
4574 }
4575 }
4576
4577 bool addrModeCombiningAllowed() {
4579 return false;
4580 switch (DifferentField) {
4581 default:
4582 return false;
4583 case ExtAddrMode::BaseRegField:
4585 case ExtAddrMode::BaseGVField:
4586 return AddrSinkCombineBaseGV;
4587 case ExtAddrMode::BaseOffsField:
4589 case ExtAddrMode::ScaledRegField:
4591 }
4592 }
4593};
4594} // end anonymous namespace
4595
4596/// Try adding ScaleReg*Scale to the current addressing mode.
4597/// Return true and update AddrMode if this addr mode is legal for the target,
4598/// false if not.
4599bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
4600 unsigned Depth) {
4601 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
4602 // mode. Just process that directly.
4603 if (Scale == 1)
4604 return matchAddr(ScaleReg, Depth);
4605
4606 // If the scale is 0, it takes nothing to add this.
4607 if (Scale == 0)
4608 return true;
4609
4610 // If we already have a scale of this value, we can add to it, otherwise, we
4611 // need an available scale field.
4612 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
4613 return false;
4614
4615 ExtAddrMode TestAddrMode = AddrMode;
4616
4617 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
4618 // [A+B + A*7] -> [B+A*8].
4619 TestAddrMode.Scale += Scale;
4620 TestAddrMode.ScaledReg = ScaleReg;
4621
4622 // If the new address isn't legal, bail out.
4623 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
4624 return false;
4625
4626 // It was legal, so commit it.
4627 AddrMode = TestAddrMode;
4628
4629 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
4630 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
4631 // X*Scale + C*Scale to addr mode. If we found available IV increment, do not
4632 // go any further: we can reuse it and cannot eliminate it.
4633 ConstantInt *CI = nullptr;
4634 Value *AddLHS = nullptr;
4635 if (isa<Instruction>(ScaleReg) && // not a constant expr.
4636 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI))) &&
4637 !isIVIncrement(ScaleReg, &LI) && CI->getValue().isSignedIntN(64)) {
4638 TestAddrMode.InBounds = false;
4639 TestAddrMode.ScaledReg = AddLHS;
4640 TestAddrMode.BaseOffs += CI->getSExtValue() * TestAddrMode.Scale;
4641
4642 // If this addressing mode is legal, commit it and remember that we folded
4643 // this instruction.
4644 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
4645 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
4646 AddrMode = TestAddrMode;
4647 return true;
4648 }
4649 // Restore status quo.
4650 TestAddrMode = AddrMode;
4651 }
4652
4653 // If this is an add recurrence with a constant step, return the increment
4654 // instruction and the canonicalized step.
4655 auto GetConstantStep =
4656 [this](const Value *V) -> std::optional<std::pair<Instruction *, APInt>> {
4657 auto *PN = dyn_cast<PHINode>(V);
4658 if (!PN)
4659 return std::nullopt;
4660 auto IVInc = getIVIncrement(PN, &LI);
4661 if (!IVInc)
4662 return std::nullopt;
4663 // TODO: The result of the intrinsics above is two-complement. However when
4664 // IV inc is expressed as add or sub, iv.next is potentially a poison value.
4665 // If it has nuw or nsw flags, we need to make sure that these flags are
4666 // inferrable at the point of memory instruction. Otherwise we are replacing
4667 // well-defined two-complement computation with poison. Currently, to avoid
4668 // potentially complex analysis needed to prove this, we reject such cases.
4669 if (auto *OIVInc = dyn_cast<OverflowingBinaryOperator>(IVInc->first))
4670 if (OIVInc->hasNoSignedWrap() || OIVInc->hasNoUnsignedWrap())
4671 return std::nullopt;
4672 if (auto *ConstantStep = dyn_cast<ConstantInt>(IVInc->second))
4673 return std::make_pair(IVInc->first, ConstantStep->getValue());
4674 return std::nullopt;
4675 };
4676
4677 // Try to account for the following special case:
4678 // 1. ScaleReg is an inductive variable;
4679 // 2. We use it with non-zero offset;
4680 // 3. IV's increment is available at the point of memory instruction.
4681 //
4682 // In this case, we may reuse the IV increment instead of the IV Phi to
4683 // achieve the following advantages:
4684 // 1. If IV step matches the offset, we will have no need in the offset;
4685 // 2. Even if they don't match, we will reduce the overlap of living IV
4686 // and IV increment, that will potentially lead to better register
4687 // assignment.
4688 if (AddrMode.BaseOffs) {
4689 if (auto IVStep = GetConstantStep(ScaleReg)) {
4690 Instruction *IVInc = IVStep->first;
4691 // The following assert is important to ensure a lack of infinite loops.
4692 // This transforms is (intentionally) the inverse of the one just above.
4693 // If they don't agree on the definition of an increment, we'd alternate
4694 // back and forth indefinitely.
4695 assert(isIVIncrement(IVInc, &LI) && "implied by GetConstantStep");
4696 APInt Step = IVStep->second;
4697 APInt Offset = Step * AddrMode.Scale;
4698 if (Offset.isSignedIntN(64)) {
4699 TestAddrMode.InBounds = false;
4700 TestAddrMode.ScaledReg = IVInc;
4701 TestAddrMode.BaseOffs -= Offset.getLimitedValue();
4702 // If this addressing mode is legal, commit it..
4703 // (Note that we defer the (expensive) domtree base legality check
4704 // to the very last possible point.)
4705 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace) &&
4706 getDTFn().dominates(IVInc, MemoryInst)) {
4707 AddrModeInsts.push_back(cast<Instruction>(IVInc));
4708 AddrMode = TestAddrMode;
4709 return true;
4710 }
4711 // Restore status quo.
4712 TestAddrMode = AddrMode;
4713 }
4714 }
4715 }
4716
4717 // Otherwise, just return what we have.
4718 return true;
4719}
4720
4721/// This is a little filter, which returns true if an addressing computation
4722/// involving I might be folded into a load/store accessing it.
4723/// This doesn't need to be perfect, but needs to accept at least
4724/// the set of instructions that MatchOperationAddr can.
4726 switch (I->getOpcode()) {
4727 case Instruction::BitCast:
4728 case Instruction::AddrSpaceCast:
4729 // Don't touch identity bitcasts.
4730 if (I->getType() == I->getOperand(0)->getType())
4731 return false;
4732 return I->getType()->isIntOrPtrTy();
4733 case Instruction::PtrToInt:
4734 // PtrToInt is always a noop, as we know that the int type is pointer sized.
4735 return true;
4736 case Instruction::IntToPtr:
4737 // We know the input is intptr_t, so this is foldable.
4738 return true;
4739 case Instruction::Add:
4740 return true;
4741 case Instruction::Mul:
4742 case Instruction::Shl:
4743 // Can only handle X*C and X << C.
4744 return isa<ConstantInt>(I->getOperand(1));
4745 case Instruction::GetElementPtr:
4746 return true;
4747 default:
4748 return false;
4749 }
4750}
4751
4752/// Check whether or not \p Val is a legal instruction for \p TLI.
4753/// \note \p Val is assumed to be the product of some type promotion.
4754/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
4755/// to be legal, as the non-promoted value would have had the same state.
4757 const DataLayout &DL, Value *Val) {
4758 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
4759 if (!PromotedInst)
4760 return false;
4761 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
4762 // If the ISDOpcode is undefined, it was undefined before the promotion.
4763 if (!ISDOpcode)
4764 return true;
4765 // Otherwise, check if the promoted instruction is legal or not.
4766 return TLI.isOperationLegalOrCustom(
4767 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
4768}
4769
4770namespace {
4771
4772/// Hepler class to perform type promotion.
4773class TypePromotionHelper {
4774 /// Utility function to add a promoted instruction \p ExtOpnd to
4775 /// \p PromotedInsts and record the type of extension we have seen.
4776 static void addPromotedInst(InstrToOrigTy &PromotedInsts,
4777 Instruction *ExtOpnd, bool IsSExt) {
4778 ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension;
4779 auto [It, Inserted] = PromotedInsts.try_emplace(ExtOpnd);
4780 if (!Inserted) {
4781 // If the new extension is same as original, the information in
4782 // PromotedInsts[ExtOpnd] is still correct.
4783 if (It->second.getInt() == ExtTy)
4784 return;
4785
4786 // Now the new extension is different from old extension, we make
4787 // the type information invalid by setting extension type to
4788 // BothExtension.
4789 ExtTy = BothExtension;
4790 }
4791 It->second = TypeIsSExt(ExtOpnd->getType(), ExtTy);
4792 }
4793
4794 /// Utility function to query the original type of instruction \p Opnd
4795 /// with a matched extension type. If the extension doesn't match, we
4796 /// cannot use the information we had on the original type.
4797 /// BothExtension doesn't match any extension type.
4798 static const Type *getOrigType(const InstrToOrigTy &PromotedInsts,
4799 Instruction *Opnd, bool IsSExt) {
4800 ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension;
4801 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
4802 if (It != PromotedInsts.end() && It->second.getInt() == ExtTy)
4803 return It->second.getPointer();
4804 return nullptr;
4805 }
4806
4807 /// Utility function to check whether or not a sign or zero extension
4808 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
4809 /// either using the operands of \p Inst or promoting \p Inst.
4810 /// The type of the extension is defined by \p IsSExt.
4811 /// In other words, check if:
4812 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
4813 /// #1 Promotion applies:
4814 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
4815 /// #2 Operand reuses:
4816 /// ext opnd1 to ConsideredExtType.
4817 /// \p PromotedInsts maps the instructions to their type before promotion.
4818 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
4819 const InstrToOrigTy &PromotedInsts, bool IsSExt);
4820
4821 /// Utility function to determine if \p OpIdx should be promoted when
4822 /// promoting \p Inst.
4823 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
4824 return !(isa<SelectInst>(Inst) && OpIdx == 0);
4825 }
4826
4827 /// Utility function to promote the operand of \p Ext when this
4828 /// operand is a promotable trunc or sext or zext.
4829 /// \p PromotedInsts maps the instructions to their type before promotion.
4830 /// \p CreatedInstsCost[out] contains the cost of all instructions
4831 /// created to promote the operand of Ext.
4832 /// Newly added extensions are inserted in \p Exts.
4833 /// Newly added truncates are inserted in \p Truncs.
4834 /// Should never be called directly.
4835 /// \return The promoted value which is used instead of Ext.
4836 static Value *promoteOperandForTruncAndAnyExt(
4837 Instruction *Ext, TypePromotionTransaction &TPT,
4838 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4839 SmallVectorImpl<Instruction *> *Exts,
4840 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
4841
4842 /// Utility function to promote the operand of \p Ext when this
4843 /// operand is promotable and is not a supported trunc or sext.
4844 /// \p PromotedInsts maps the instructions to their type before promotion.
4845 /// \p CreatedInstsCost[out] contains the cost of all the instructions
4846 /// created to promote the operand of Ext.
4847 /// Newly added extensions are inserted in \p Exts.
4848 /// Newly added truncates are inserted in \p Truncs.
4849 /// Should never be called directly.
4850 /// \return The promoted value which is used instead of Ext.
4851 static Value *promoteOperandForOther(Instruction *Ext,
4852 TypePromotionTransaction &TPT,
4853 InstrToOrigTy &PromotedInsts,
4854 unsigned &CreatedInstsCost,
4855 SmallVectorImpl<Instruction *> *Exts,
4856 SmallVectorImpl<Instruction *> *Truncs,
4857 const TargetLowering &TLI, bool IsSExt);
4858
4859 /// \see promoteOperandForOther.
4860 static Value *signExtendOperandForOther(
4861 Instruction *Ext, TypePromotionTransaction &TPT,
4862 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4863 SmallVectorImpl<Instruction *> *Exts,
4864 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
4865 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
4866 Exts, Truncs, TLI, true);
4867 }
4868
4869 /// \see promoteOperandForOther.
4870 static Value *zeroExtendOperandForOther(
4871 Instruction *Ext, TypePromotionTransaction &TPT,
4872 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4873 SmallVectorImpl<Instruction *> *Exts,
4874 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
4875 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
4876 Exts, Truncs, TLI, false);
4877 }
4878
4879public:
4880 /// Type for the utility function that promotes the operand of Ext.
4881 using Action = Value *(*)(Instruction *Ext, TypePromotionTransaction &TPT,
4882 InstrToOrigTy &PromotedInsts,
4883 unsigned &CreatedInstsCost,
4884 SmallVectorImpl<Instruction *> *Exts,
4885 SmallVectorImpl<Instruction *> *Truncs,
4886 const TargetLowering &TLI);
4887
4888 /// Given a sign/zero extend instruction \p Ext, return the appropriate
4889 /// action to promote the operand of \p Ext instead of using Ext.
4890 /// \return NULL if no promotable action is possible with the current
4891 /// sign extension.
4892 /// \p InsertedInsts keeps track of all the instructions inserted by the
4893 /// other CodeGenPrepare optimizations. This information is important
4894 /// because we do not want to promote these instructions as CodeGenPrepare
4895 /// will reinsert them later. Thus creating an infinite loop: create/remove.
4896 /// \p PromotedInsts maps the instructions to their type before promotion.
4897 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
4898 const TargetLowering &TLI,
4899 const InstrToOrigTy &PromotedInsts);
4900};
4901
4902} // end anonymous namespace
4903
4904bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
4905 Type *ConsideredExtType,
4906 const InstrToOrigTy &PromotedInsts,
4907 bool IsSExt) {
4908 // The promotion helper does not know how to deal with vector types yet.
4909 // To be able to fix that, we would need to fix the places where we
4910 // statically extend, e.g., constants and such.
4911 if (Inst->getType()->isVectorTy())
4912 return false;
4913
4914 // We can always get through zext.
4915 if (isa<ZExtInst>(Inst))
4916 return true;
4917
4918 // sext(sext) is ok too.
4919 if (IsSExt && isa<SExtInst>(Inst))
4920 return true;
4921
4922 // We can get through binary operator, if it is legal. In other words, the
4923 // binary operator must have a nuw or nsw flag.
4924 if (const auto *BinOp = dyn_cast<BinaryOperator>(Inst))
4925 if (isa<OverflowingBinaryOperator>(BinOp) &&
4926 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
4927 (IsSExt && BinOp->hasNoSignedWrap())))
4928 return true;
4929
4930 // ext(and(opnd, cst)) --> and(ext(opnd), ext(cst))
4931 if ((Inst->getOpcode() == Instruction::And ||
4932 Inst->getOpcode() == Instruction::Or))
4933 return true;
4934
4935 // ext(xor(opnd, cst)) --> xor(ext(opnd), ext(cst))
4936 if (Inst->getOpcode() == Instruction::Xor) {
4937 // Make sure it is not a NOT.
4938 if (const auto *Cst = dyn_cast<ConstantInt>(Inst->getOperand(1)))
4939 if (!Cst->getValue().isAllOnes())
4940 return true;
4941 }
4942
4943 // zext(shrl(opnd, cst)) --> shrl(zext(opnd), zext(cst))
4944 // It may change a poisoned value into a regular value, like
4945 // zext i32 (shrl i8 %val, 12) --> shrl i32 (zext i8 %val), 12
4946 // poisoned value regular value
4947 // It should be OK since undef covers valid value.
4948 if (Inst->getOpcode() == Instruction::LShr && !IsSExt)
4949 return true;
4950
4951 // and(ext(shl(opnd, cst)), cst) --> and(shl(ext(opnd), ext(cst)), cst)
4952 // It may change a poisoned value into a regular value, like
4953 // zext i32 (shl i8 %val, 12) --> shl i32 (zext i8 %val), 12
4954 // poisoned value regular value
4955 // It should be OK since undef covers valid value.
4956 if (Inst->getOpcode() == Instruction::Shl && Inst->hasOneUse()) {
4957 const auto *ExtInst = cast<const Instruction>(*Inst->user_begin());
4958 if (ExtInst->hasOneUse()) {
4959 const auto *AndInst = dyn_cast<const Instruction>(*ExtInst->user_begin());
4960 if (AndInst && AndInst->getOpcode() == Instruction::And) {
4961 const auto *Cst = dyn_cast<ConstantInt>(AndInst->getOperand(1));
4962 if (Cst &&
4963 Cst->getValue().isIntN(Inst->getType()->getIntegerBitWidth()))
4964 return true;
4965 }
4966 }
4967 }
4968
4969 // Check if we can do the following simplification.
4970 // ext(trunc(opnd)) --> ext(opnd)
4971 if (!isa<TruncInst>(Inst))
4972 return false;
4973
4974 Value *OpndVal = Inst->getOperand(0);
4975 // Check if we can use this operand in the extension.
4976 // If the type is larger than the result type of the extension, we cannot.
4977 if (!OpndVal->getType()->isIntegerTy() ||
4978 OpndVal->getType()->getIntegerBitWidth() >
4979 ConsideredExtType->getIntegerBitWidth())
4980 return false;
4981
4982 // If the operand of the truncate is not an instruction, we will not have
4983 // any information on the dropped bits.
4984 // (Actually we could for constant but it is not worth the extra logic).
4985 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
4986 if (!Opnd)
4987 return false;
4988
4989 // Check if the source of the type is narrow enough.
4990 // I.e., check that trunc just drops extended bits of the same kind of
4991 // the extension.
4992 // #1 get the type of the operand and check the kind of the extended bits.
4993 const Type *OpndType = getOrigType(PromotedInsts, Opnd, IsSExt);
4994 if (OpndType)
4995 ;
4996 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
4997 OpndType = Opnd->getOperand(0)->getType();
4998 else
4999 return false;
5000
5001 // #2 check that the truncate just drops extended bits.
5002 return Inst->getType()->getIntegerBitWidth() >=
5003 OpndType->getIntegerBitWidth();
5004}
5005
5006TypePromotionHelper::Action TypePromotionHelper::getAction(
5007 Instruction *Ext, const SetOfInstrs &InsertedInsts,
5008 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
5009 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5010 "Unexpected instruction type");
5011 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
5012 Type *ExtTy = Ext->getType();
5013 bool IsSExt = isa<SExtInst>(Ext);
5014 // If the operand of the extension is not an instruction, we cannot
5015 // get through.
5016 // If it, check we can get through.
5017 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
5018 return nullptr;
5019
5020 // Do not promote if the operand has been added by codegenprepare.
5021 // Otherwise, it means we are undoing an optimization that is likely to be
5022 // redone, thus causing potential infinite loop.
5023 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
5024 return nullptr;
5025
5026 // SExt or Trunc instructions.
5027 // Return the related handler.
5028 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
5029 isa<ZExtInst>(ExtOpnd))
5030 return promoteOperandForTruncAndAnyExt;
5031
5032 // Regular instruction.
5033 // Abort early if we will have to insert non-free instructions.
5034 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
5035 return nullptr;
5036 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
5037}
5038
5039Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
5040 Instruction *SExt, TypePromotionTransaction &TPT,
5041 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
5042 SmallVectorImpl<Instruction *> *Exts,
5043 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
5044 // By construction, the operand of SExt is an instruction. Otherwise we cannot
5045 // get through it and this method should not be called.
5046 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
5047 Value *ExtVal = SExt;
5048 bool HasMergedNonFreeExt = false;
5049 if (isa<ZExtInst>(SExtOpnd)) {
5050 // Replace s|zext(zext(opnd))
5051 // => zext(opnd).
5052 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
5053 Value *ZExt =
5054 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
5055 TPT.replaceAllUsesWith(SExt, ZExt);
5056 TPT.eraseInstruction(SExt);
5057 ExtVal = ZExt;
5058 } else {
5059 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
5060 // => z|sext(opnd).
5061 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
5062 }
5063 CreatedInstsCost = 0;
5064
5065 // Remove dead code.
5066 if (SExtOpnd->use_empty())
5067 TPT.eraseInstruction(SExtOpnd);
5068
5069 // Check if the extension is still needed.
5070 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
5071 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
5072 if (ExtInst) {
5073 if (Exts)
5074 Exts->push_back(ExtInst);
5075 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
5076 }
5077 return ExtVal;
5078 }
5079
5080 // At this point we have: ext ty opnd to ty.
5081 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
5082 Value *NextVal = ExtInst->getOperand(0);
5083 TPT.eraseInstruction(ExtInst, NextVal);
5084 return NextVal;
5085}
5086
5087Value *TypePromotionHelper::promoteOperandForOther(
5088 Instruction *Ext, TypePromotionTransaction &TPT,
5089 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
5090 SmallVectorImpl<Instruction *> *Exts,
5091 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
5092 bool IsSExt) {
5093 // By construction, the operand of Ext is an instruction. Otherwise we cannot
5094 // get through it and this method should not be called.
5095 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
5096 CreatedInstsCost = 0;
5097 if (!ExtOpnd->hasOneUse()) {
5098 // ExtOpnd will be promoted.
5099 // All its uses, but Ext, will need to use a truncated value of the
5100 // promoted version.
5101 // Create the truncate now.
5102 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
5103 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
5104 // Insert it just after the definition.
5105 ITrunc->moveAfter(ExtOpnd);
5106 if (Truncs)
5107 Truncs->push_back(ITrunc);
5108 }
5109
5110 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
5111 // Restore the operand of Ext (which has been replaced by the previous call
5112 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
5113 TPT.setOperand(Ext, 0, ExtOpnd);
5114 }
5115
5116 // Get through the Instruction:
5117 // 1. Update its type.
5118 // 2. Replace the uses of Ext by Inst.
5119 // 3. Extend each operand that needs to be extended.
5120
5121 // Remember the original type of the instruction before promotion.
5122 // This is useful to know that the high bits are sign extended bits.
5123 addPromotedInst(PromotedInsts, ExtOpnd, IsSExt);
5124 // Step #1.
5125 TPT.mutateType(ExtOpnd, Ext->getType());
5126 // Step #2.
5127 TPT.replaceAllUsesWith(Ext, ExtOpnd);
5128 // Step #3.
5129 LLVM_DEBUG(dbgs() << "Propagate Ext to operands\n");
5130 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
5131 ++OpIdx) {
5132 LLVM_DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
5133 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
5134 !shouldExtOperand(ExtOpnd, OpIdx)) {
5135 LLVM_DEBUG(dbgs() << "No need to propagate\n");
5136 continue;
5137 }
5138 // Check if we can statically extend the operand.
5139 Value *Opnd = ExtOpnd->getOperand(OpIdx);
5140 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
5141 LLVM_DEBUG(dbgs() << "Statically extend\n");
5142 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
5143 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
5144 : Cst->getValue().zext(BitWidth);
5145 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
5146 continue;
5147 }
5148 // UndefValue are typed, so we have to statically sign extend them.
5149 if (isa<UndefValue>(Opnd)) {
5150 LLVM_DEBUG(dbgs() << "Statically extend\n");
5151 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
5152 continue;
5153 }
5154
5155 // Otherwise we have to explicitly sign extend the operand.
5156 Value *ValForExtOpnd = IsSExt
5157 ? TPT.createSExt(ExtOpnd, Opnd, Ext->getType())
5158 : TPT.createZExt(ExtOpnd, Opnd, Ext->getType());
5159 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
5160 Instruction *InstForExtOpnd = dyn_cast<Instruction>(ValForExtOpnd);
5161 if (!InstForExtOpnd)
5162 continue;
5163
5164 if (Exts)
5165 Exts->push_back(InstForExtOpnd);
5166
5167 CreatedInstsCost += !TLI.isExtFree(InstForExtOpnd);
5168 }
5169 LLVM_DEBUG(dbgs() << "Extension is useless now\n");
5170 TPT.eraseInstruction(Ext);
5171 return ExtOpnd;
5172}
5173
5174/// Check whether or not promoting an instruction to a wider type is profitable.
5175/// \p NewCost gives the cost of extension instructions created by the
5176/// promotion.
5177/// \p OldCost gives the cost of extension instructions before the promotion
5178/// plus the number of instructions that have been
5179/// matched in the addressing mode the promotion.
5180/// \p PromotedOperand is the value that has been promoted.
5181/// \return True if the promotion is profitable, false otherwise.
5182bool AddressingModeMatcher::isPromotionProfitable(
5183 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
5184 LLVM_DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost
5185 << '\n');
5186 // The cost of the new extensions is greater than the cost of the
5187 // old extension plus what we folded.
5188 // This is not profitable.
5189 if (NewCost > OldCost)
5190 return false;
5191 if (NewCost < OldCost)
5192 return true;
5193 // The promotion is neutral but it may help folding the sign extension in
5194 // loads for instance.
5195 // Check that we did not create an illegal instruction.
5196 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
5197}
5198
5199/// Given an instruction or constant expr, see if we can fold the operation
5200/// into the addressing mode. If so, update the addressing mode and return
5201/// true, otherwise return false without modifying AddrMode.
5202/// If \p MovedAway is not NULL, it contains the information of whether or
5203/// not AddrInst has to be folded into the addressing mode on success.
5204/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
5205/// because it has been moved away.
5206/// Thus AddrInst must not be added in the matched instructions.
5207/// This state can happen when AddrInst is a sext, since it may be moved away.
5208/// Therefore, AddrInst may not be valid when MovedAway is true and it must
5209/// not be referenced anymore.
5210bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
5211 unsigned Depth,
5212 bool *MovedAway) {
5213 // Avoid exponential behavior on extremely deep expression trees.
5214 if (Depth >= 5)
5215 return false;
5216
5217 // By default, all matched instructions stay in place.
5218 if (MovedAway)
5219 *MovedAway = false;
5220
5221 switch (Opcode) {
5222 case Instruction::PtrToInt:
5223 // PtrToInt is always a noop, as we know that the int type is pointer sized.
5224 return matchAddr(AddrInst->getOperand(0), Depth);
5225 case Instruction::IntToPtr: {
5226 auto AS = AddrInst->getType()->getPointerAddressSpace();
5227 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
5228 // This inttoptr is a no-op if the integer type is pointer sized.
5229 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
5230 return matchAddr(AddrInst->getOperand(0), Depth);
5231 return false;
5232 }
5233 case Instruction::BitCast:
5234 // BitCast is always a noop, and we can handle it as long as it is
5235 // int->int or pointer->pointer (we don't want int<->fp or something).
5236 if (AddrInst->getOperand(0)->getType()->isIntOrPtrTy() &&
5237 // Don't touch identity bitcasts. These were probably put here by LSR,
5238 // and we don't want to mess around with them. Assume it knows what it
5239 // is doing.
5240 AddrInst->getOperand(0)->getType() != AddrInst->getType())
5241 return matchAddr(AddrInst->getOperand(0), Depth);
5242 return false;
5243 case Instruction::AddrSpaceCast: {
5244 unsigned SrcAS =
5245 AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
5246 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
5247 if (TLI.getTargetMachine().isNoopAddrSpaceCast(SrcAS, DestAS))
5248 return matchAddr(AddrInst->getOperand(0), Depth);
5249 return false;
5250 }
5251 case Instruction::Add: {
5252 // Check to see if we can merge in one operand, then the other. If so, we
5253 // win.
5254 ExtAddrMode BackupAddrMode = AddrMode;
5255 unsigned OldSize = AddrModeInsts.size();
5256 // Start a transaction at this point.
5257 // The LHS may match but not the RHS.
5258 // Therefore, we need a higher level restoration point to undo partially
5259 // matched operation.
5260 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5261 TPT.getRestorationPoint();
5262
5263 // Try to match an integer constant second to increase its chance of ending
5264 // up in `BaseOffs`, resp. decrease its chance of ending up in `BaseReg`.
5265 int First = 0, Second = 1;
5266 if (isa<ConstantInt>(AddrInst->getOperand(First))
5267 && !isa<ConstantInt>(AddrInst->getOperand(Second)))
5268 std::swap(First, Second);
5269 AddrMode.InBounds = false;
5270 if (matchAddr(AddrInst->getOperand(First), Depth + 1) &&
5271 matchAddr(AddrInst->getOperand(Second), Depth + 1))
5272 return true;
5273
5274 // Restore the old addr mode info.
5275 AddrMode = BackupAddrMode;
5276 AddrModeInsts.resize(OldSize);
5277 TPT.rollback(LastKnownGood);
5278
5279 // Otherwise this was over-aggressive. Try merging operands in the opposite
5280 // order.
5281 if (matchAddr(AddrInst->getOperand(Second), Depth + 1) &&
5282 matchAddr(AddrInst->getOperand(First), Depth + 1))
5283 return true;
5284
5285 // Otherwise we definitely can't merge the ADD in.
5286 AddrMode = BackupAddrMode;
5287 AddrModeInsts.resize(OldSize);
5288 TPT.rollback(LastKnownGood);
5289 break;
5290 }
5291 // case Instruction::Or:
5292 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
5293 // break;
5294 case Instruction::Mul:
5295 case Instruction::Shl: {
5296 // Can only handle X*C and X << C.
5297 AddrMode.InBounds = false;
5298 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
5299 if (!RHS || RHS->getBitWidth() > 64)
5300 return false;
5301 int64_t Scale = Opcode == Instruction::Shl
5302 ? 1LL << RHS->getLimitedValue(RHS->getBitWidth() - 1)
5303 : RHS->getSExtValue();
5304
5305 return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
5306 }
5307 case Instruction::GetElementPtr: {
5308 // Scan the GEP. We check it if it contains constant offsets and at most
5309 // one variable offset.
5310 int VariableOperand = -1;
5311 unsigned VariableScale = 0;
5312
5313 int64_t ConstantOffset = 0;
5314 gep_type_iterator GTI = gep_type_begin(AddrInst);
5315 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
5316 if (StructType *STy = GTI.getStructTypeOrNull()) {
5317 const StructLayout *SL = DL.getStructLayout(STy);
5318 unsigned Idx =
5319 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
5320 ConstantOffset += SL->getElementOffset(Idx);
5321 } else {
5322 TypeSize TS = GTI.getSequentialElementStride(DL);
5323 if (TS.isNonZero()) {
5324 // The optimisations below currently only work for fixed offsets.
5325 if (TS.isScalable())
5326 return false;
5327 int64_t TypeSize = TS.getFixedValue();
5328 if (ConstantInt *CI =
5329 dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
5330 const APInt &CVal = CI->getValue();
5331 if (CVal.getSignificantBits() <= 64) {
5332 ConstantOffset += CVal.getSExtValue() * TypeSize;
5333 continue;
5334 }
5335 }
5336 // We only allow one variable index at the moment.
5337 if (VariableOperand != -1)
5338 return false;
5339
5340 // Remember the variable index.
5341 VariableOperand = i;
5342 VariableScale = TypeSize;
5343 }
5344 }
5345 }
5346
5347 // A common case is for the GEP to only do a constant offset. In this case,
5348 // just add it to the disp field and check validity.
5349 if (VariableOperand == -1) {
5350 AddrMode.BaseOffs += ConstantOffset;
5351 if (matchAddr(AddrInst->getOperand(0), Depth + 1)) {
5352 if (!cast<GEPOperator>(AddrInst)->isInBounds())
5353 AddrMode.InBounds = false;
5354 return true;
5355 }
5356 AddrMode.BaseOffs -= ConstantOffset;
5357
5359 TLI.shouldConsiderGEPOffsetSplit() && Depth == 0 &&
5360 ConstantOffset > 0) {
5361 // Record GEPs with non-zero offsets as candidates for splitting in
5362 // the event that the offset cannot fit into the r+i addressing mode.
5363 // Simple and common case that only one GEP is used in calculating the
5364 // address for the memory access.
5365 Value *Base = AddrInst->getOperand(0);
5366 auto *BaseI = dyn_cast<Instruction>(Base);
5367 auto *GEP = cast<GetElementPtrInst>(AddrInst);
5369 (BaseI && !isa<CastInst>(BaseI) &&
5370 !isa<GetElementPtrInst>(BaseI))) {
5371 // Make sure the parent block allows inserting non-PHI instructions
5372 // before the terminator.
5373 BasicBlock *Parent = BaseI ? BaseI->getParent()
5374 : &GEP->getFunction()->getEntryBlock();
5375 if (!Parent->getTerminator()->isEHPad())
5376 LargeOffsetGEP = std::make_pair(GEP, ConstantOffset);
5377 }
5378 }
5379
5380 return false;
5381 }
5382
5383 // Save the valid addressing mode in case we can't match.
5384 ExtAddrMode BackupAddrMode = AddrMode;
5385 unsigned OldSize = AddrModeInsts.size();
5386
5387 // See if the scale and offset amount is valid for this target.
5388 AddrMode.BaseOffs += ConstantOffset;
5389 if (!cast<GEPOperator>(AddrInst)->isInBounds())
5390 AddrMode.InBounds = false;
5391
5392 // Match the base operand of the GEP.
5393 if (!matchAddr(AddrInst->getOperand(0), Depth + 1)) {
5394 // If it couldn't be matched, just stuff the value in a register.
5395 if (AddrMode.HasBaseReg) {
5396 AddrMode = BackupAddrMode;
5397 AddrModeInsts.resize(OldSize);
5398 return false;
5399 }
5400 AddrMode.HasBaseReg = true;
5401 AddrMode.BaseReg = AddrInst->getOperand(0);
5402 }
5403
5404 // Match the remaining variable portion of the GEP.
5405 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
5406 Depth)) {
5407 // If it couldn't be matched, try stuffing the base into a register
5408 // instead of matching it, and retrying the match of the scale.
5409 AddrMode = BackupAddrMode;
5410 AddrModeInsts.resize(OldSize);
5411 if (AddrMode.HasBaseReg)
5412 return false;
5413 AddrMode.HasBaseReg = true;
5414 AddrMode.BaseReg = AddrInst->getOperand(0);
5415 AddrMode.BaseOffs += ConstantOffset;
5416 if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
5417 VariableScale, Depth)) {
5418 // If even that didn't work, bail.
5419 AddrMode = BackupAddrMode;
5420 AddrModeInsts.resize(OldSize);
5421 return false;
5422 }
5423 }
5424
5425 return true;
5426 }
5427 case Instruction::SExt:
5428 case Instruction::ZExt: {
5429 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
5430 if (!Ext)
5431 return false;
5432
5433 // Try to move this ext out of the way of the addressing mode.
5434 // Ask for a method for doing so.
5435 TypePromotionHelper::Action TPH =
5436 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
5437 if (!TPH)
5438 return false;
5439
5440 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5441 TPT.getRestorationPoint();
5442 unsigned CreatedInstsCost = 0;
5443 unsigned ExtCost = !TLI.isExtFree(Ext);
5444 Value *PromotedOperand =
5445 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
5446 // SExt has been moved away.
5447 // Thus either it will be rematched later in the recursive calls or it is
5448 // gone. Anyway, we must not fold it into the addressing mode at this point.
5449 // E.g.,
5450 // op = add opnd, 1
5451 // idx = ext op
5452 // addr = gep base, idx
5453 // is now:
5454 // promotedOpnd = ext opnd <- no match here
5455 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
5456 // addr = gep base, op <- match
5457 if (MovedAway)
5458 *MovedAway = true;
5459
5460 assert(PromotedOperand &&
5461 "TypePromotionHelper should have filtered out those cases");
5462
5463 ExtAddrMode BackupAddrMode = AddrMode;
5464 unsigned OldSize = AddrModeInsts.size();
5465
5466 if (!matchAddr(PromotedOperand, Depth) ||
5467 // The total of the new cost is equal to the cost of the created
5468 // instructions.
5469 // The total of the old cost is equal to the cost of the extension plus
5470 // what we have saved in the addressing mode.
5471 !isPromotionProfitable(CreatedInstsCost,
5472 ExtCost + (AddrModeInsts.size() - OldSize),
5473 PromotedOperand)) {
5474 AddrMode = BackupAddrMode;
5475 AddrModeInsts.resize(OldSize);
5476 LLVM_DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
5477 TPT.rollback(LastKnownGood);
5478 return false;
5479 }
5480
5481 // SExt has been deleted. Make sure it is not referenced by the AddrMode.
5482 AddrMode.replaceWith(Ext, PromotedOperand);
5483 return true;
5484 }
5485 case Instruction::Call:
5486 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(AddrInst)) {
5487 if (II->getIntrinsicID() == Intrinsic::threadlocal_address) {
5488 GlobalValue &GV = cast<GlobalValue>(*II->getArgOperand(0));
5489 if (TLI.addressingModeSupportsTLS(GV))
5490 return matchAddr(AddrInst->getOperand(0), Depth);
5491 }
5492 }
5493 break;
5494 }
5495 return false;
5496}
5497
5498/// If we can, try to add the value of 'Addr' into the current addressing mode.
5499/// If Addr can't be added to AddrMode this returns false and leaves AddrMode
5500/// unmodified. This assumes that Addr is either a pointer type or intptr_t
5501/// for the target.
5502///
5503bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
5504 // Start a transaction at this point that we will rollback if the matching
5505 // fails.
5506 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5507 TPT.getRestorationPoint();
5508 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
5509 if (CI->getValue().isSignedIntN(64)) {
5510 // Check if the addition would result in a signed overflow.
5511 int64_t Result;
5512 bool Overflow =
5513 AddOverflow(AddrMode.BaseOffs, CI->getSExtValue(), Result);
5514 if (!Overflow) {
5515 // Fold in immediates if legal for the target.
5516 AddrMode.BaseOffs = Result;
5517 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
5518 return true;
5519 AddrMode.BaseOffs -= CI->getSExtValue();
5520 }
5521 }
5522 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
5523 // If this is a global variable, try to fold it into the addressing mode.
5524 if (!AddrMode.BaseGV) {
5525 AddrMode.BaseGV = GV;
5526 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
5527 return true;
5528 AddrMode.BaseGV = nullptr;
5529 }
5530 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
5531 ExtAddrMode BackupAddrMode = AddrMode;
5532 unsigned OldSize = AddrModeInsts.size();
5533
5534 // Check to see if it is possible to fold this operation.
5535 bool MovedAway = false;
5536 if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
5537 // This instruction may have been moved away. If so, there is nothing
5538 // to check here.
5539 if (MovedAway)
5540 return true;
5541 // Okay, it's possible to fold this. Check to see if it is actually
5542 // *profitable* to do so. We use a simple cost model to avoid increasing
5543 // register pressure too much.
5544 if (I->hasOneUse() ||
5545 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
5546 AddrModeInsts.push_back(I);
5547 return true;
5548 }
5549
5550 // It isn't profitable to do this, roll back.
5551 AddrMode = BackupAddrMode;
5552 AddrModeInsts.resize(OldSize);
5553 TPT.rollback(LastKnownGood);
5554 }
5555 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
5556 if (matchOperationAddr(CE, CE->getOpcode(), Depth))
5557 return true;
5558 TPT.rollback(LastKnownGood);
5559 } else if (isa<ConstantPointerNull>(Addr)) {
5560 // Null pointer gets folded without affecting the addressing mode.
5561 return true;
5562 }
5563
5564 // Worse case, the target should support [reg] addressing modes. :)
5565 if (!AddrMode.HasBaseReg) {
5566 AddrMode.HasBaseReg = true;
5567 AddrMode.BaseReg = Addr;
5568 // Still check for legality in case the target supports [imm] but not [i+r].
5569 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
5570 return true;
5571 AddrMode.HasBaseReg = false;
5572 AddrMode.BaseReg = nullptr;
5573 }
5574
5575 // If the base register is already taken, see if we can do [r+r].
5576 if (AddrMode.Scale == 0) {
5577 AddrMode.Scale = 1;
5578 AddrMode.ScaledReg = Addr;
5579 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
5580 return true;
5581 AddrMode.Scale = 0;
5582 AddrMode.ScaledReg = nullptr;
5583 }
5584 // Couldn't match.
5585 TPT.rollback(LastKnownGood);
5586 return false;
5587}
5588
5589/// Check to see if all uses of OpVal by the specified inline asm call are due
5590/// to memory operands. If so, return true, otherwise return false.
5592 const TargetLowering &TLI,
5593 const TargetRegisterInfo &TRI) {
5594 const Function *F = CI->getFunction();
5595 TargetLowering::AsmOperandInfoVector TargetConstraints =
5596 TLI.ParseConstraints(F->getDataLayout(), &TRI, *CI);
5597
5598 for (TargetLowering::AsmOperandInfo &OpInfo : TargetConstraints) {
5599 // Compute the constraint code and ConstraintType to use.
5600 TLI.ComputeConstraintToUse(OpInfo, SDValue());
5601
5602 // If this asm operand is our Value*, and if it isn't an indirect memory
5603 // operand, we can't fold it! TODO: Also handle C_Address?
5604 if (OpInfo.CallOperandVal == OpVal &&
5605 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
5606 !OpInfo.isIndirect))
5607 return false;
5608 }
5609
5610 return true;
5611}
5612
5613/// Recursively walk all the uses of I until we find a memory use.
5614/// If we find an obviously non-foldable instruction, return true.
5615/// Add accessed addresses and types to MemoryUses.
5617 Instruction *I, SmallVectorImpl<std::pair<Use *, Type *>> &MemoryUses,
5618 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetLowering &TLI,
5619 const TargetRegisterInfo &TRI, bool OptSize, ProfileSummaryInfo *PSI,
5620 BlockFrequencyInfo *BFI, unsigned &SeenInsts) {
5621 // If we already considered this instruction, we're done.
5622 if (!ConsideredInsts.insert(I).second)
5623 return false;
5624
5625 // If this is an obviously unfoldable instruction, bail out.
5626 if (!MightBeFoldableInst(I))
5627 return true;
5628
5629 // Loop over all the uses, recursively processing them.
5630 for (Use &U : I->uses()) {
5631 // Conservatively return true if we're seeing a large number or a deep chain
5632 // of users. This avoids excessive compilation times in pathological cases.
5633 if (SeenInsts++ >= MaxAddressUsersToScan)
5634 return true;
5635
5636 Instruction *UserI = cast<Instruction>(U.getUser());
5637 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
5638 MemoryUses.push_back({&U, LI->getType()});
5639 continue;
5640 }
5641
5642 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
5643 if (U.getOperandNo() != StoreInst::getPointerOperandIndex())
5644 return true; // Storing addr, not into addr.
5645 MemoryUses.push_back({&U, SI->getValueOperand()->getType()});
5646 continue;
5647 }
5648
5649 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UserI)) {
5650 if (U.getOperandNo() != AtomicRMWInst::getPointerOperandIndex())
5651 return true; // Storing addr, not into addr.
5652 MemoryUses.push_back({&U, RMW->getValOperand()->getType()});
5653 continue;
5654 }
5655
5657 if (U.getOperandNo() != AtomicCmpXchgInst::getPointerOperandIndex())
5658 return true; // Storing addr, not into addr.
5659 MemoryUses.push_back({&U, CmpX->getCompareOperand()->getType()});
5660 continue;
5661 }
5662
5665 Type *AccessTy;
5666 if (!TLI.getAddrModeArguments(II, PtrOps, AccessTy))
5667 return true;
5668
5669 if (!find(PtrOps, U.get()))
5670 return true;
5671
5672 MemoryUses.push_back({&U, AccessTy});
5673 continue;
5674 }
5675
5676 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
5677 if (CI->hasFnAttr(Attribute::Cold)) {
5678 // If this is a cold call, we can sink the addressing calculation into
5679 // the cold path. See optimizeCallInst
5680 if (!llvm::shouldOptimizeForSize(CI->getParent(), PSI, BFI))
5681 continue;
5682 }
5683
5684 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledOperand());
5685 if (!IA)
5686 return true;
5687
5688 // If this is a memory operand, we're cool, otherwise bail out.
5689 if (!IsOperandAMemoryOperand(CI, IA, I, TLI, TRI))
5690 return true;
5691 continue;
5692 }
5693
5694 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI, TRI, OptSize,
5695 PSI, BFI, SeenInsts))
5696 return true;
5697 }
5698
5699 return false;
5700}
5701
5703 Instruction *I, SmallVectorImpl<std::pair<Use *, Type *>> &MemoryUses,
5704 const TargetLowering &TLI, const TargetRegisterInfo &TRI, bool OptSize,
5706 unsigned SeenInsts = 0;
5707 SmallPtrSet<Instruction *, 16> ConsideredInsts;
5708 return FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI, TRI, OptSize,
5709 PSI, BFI, SeenInsts);
5710}
5711
5712
5713/// Return true if Val is already known to be live at the use site that we're
5714/// folding it into. If so, there is no cost to include it in the addressing
5715/// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
5716/// instruction already.
5717bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,
5718 Value *KnownLive1,
5719 Value *KnownLive2) {
5720 // If Val is either of the known-live values, we know it is live!
5721 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
5722 return true;
5723
5724 // All values other than instructions and arguments (e.g. constants) are live.
5725 if (!isa<Instruction>(Val) && !isa<Argument>(Val))
5726 return true;
5727
5728 // If Val is a constant sized alloca in the entry block, it is live, this is
5729 // true because it is just a reference to the stack/frame pointer, which is
5730 // live for the whole function.
5731 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
5732 if (AI->isStaticAlloca())
5733 return true;
5734
5735 // Check to see if this value is already used in the memory instruction's
5736 // block. If so, it's already live into the block at the very least, so we
5737 // can reasonably fold it.
5738 return Val->isUsedInBasicBlock(MemoryInst->getParent());
5739}
5740
5741/// It is possible for the addressing mode of the machine to fold the specified
5742/// instruction into a load or store that ultimately uses it.
5743/// However, the specified instruction has multiple uses.
5744/// Given this, it may actually increase register pressure to fold it
5745/// into the load. For example, consider this code:
5746///
5747/// X = ...
5748/// Y = X+1
5749/// use(Y) -> nonload/store
5750/// Z = Y+1
5751/// load Z
5752///
5753/// In this case, Y has multiple uses, and can be folded into the load of Z
5754/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
5755/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
5756/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
5757/// number of computations either.
5758///
5759/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
5760/// X was live across 'load Z' for other reasons, we actually *would* want to
5761/// fold the addressing mode in the Z case. This would make Y die earlier.
5762bool AddressingModeMatcher::isProfitableToFoldIntoAddressingMode(
5763 Instruction *I, ExtAddrMode &AMBefore, ExtAddrMode &AMAfter) {
5764 if (IgnoreProfitability)
5765 return true;
5766
5767 // AMBefore is the addressing mode before this instruction was folded into it,
5768 // and AMAfter is the addressing mode after the instruction was folded. Get
5769 // the set of registers referenced by AMAfter and subtract out those
5770 // referenced by AMBefore: this is the set of values which folding in this
5771 // address extends the lifetime of.
5772 //
5773 // Note that there are only two potential values being referenced here,
5774 // BaseReg and ScaleReg (global addresses are always available, as are any
5775 // folded immediates).
5776 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
5777
5778 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
5779 // lifetime wasn't extended by adding this instruction.
5780 if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
5781 BaseReg = nullptr;
5782 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
5783 ScaledReg = nullptr;
5784
5785 // If folding this instruction (and it's subexprs) didn't extend any live
5786 // ranges, we're ok with it.
5787 if (!BaseReg && !ScaledReg)
5788 return true;
5789
5790 // If all uses of this instruction can have the address mode sunk into them,
5791 // we can remove the addressing mode and effectively trade one live register
5792 // for another (at worst.) In this context, folding an addressing mode into
5793 // the use is just a particularly nice way of sinking it.
5795 if (FindAllMemoryUses(I, MemoryUses, TLI, TRI, OptSize, PSI, BFI))
5796 return false; // Has a non-memory, non-foldable use!
5797
5798 // Now that we know that all uses of this instruction are part of a chain of
5799 // computation involving only operations that could theoretically be folded
5800 // into a memory use, loop over each of these memory operation uses and see
5801 // if they could *actually* fold the instruction. The assumption is that
5802 // addressing modes are cheap and that duplicating the computation involved
5803 // many times is worthwhile, even on a fastpath. For sinking candidates
5804 // (i.e. cold call sites), this serves as a way to prevent excessive code
5805 // growth since most architectures have some reasonable small and fast way to
5806 // compute an effective address. (i.e LEA on x86)
5807 SmallVector<Instruction *, 32> MatchedAddrModeInsts;
5808 for (const std::pair<Use *, Type *> &Pair : MemoryUses) {
5809 Value *Address = Pair.first->get();
5810 Instruction *UserI = cast<Instruction>(Pair.first->getUser());
5811 Type *AddressAccessTy = Pair.second;
5812 unsigned AS = Address->getType()->getPointerAddressSpace();
5813
5814 // Do a match against the root of this address, ignoring profitability. This
5815 // will tell us if the addressing mode for the memory operation will
5816 // *actually* cover the shared instruction.
5817 ExtAddrMode Result;
5818 std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr,
5819 0);
5820 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5821 TPT.getRestorationPoint();
5822 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, TRI, LI, getDTFn,
5823 AddressAccessTy, AS, UserI, Result,
5824 InsertedInsts, PromotedInsts, TPT,
5825 LargeOffsetGEP, OptSize, PSI, BFI);
5826 Matcher.IgnoreProfitability = true;
5827 bool Success = Matcher.matchAddr(Address, 0);
5828 (void)Success;
5829 assert(Success && "Couldn't select *anything*?");
5830
5831 // The match was to check the profitability, the changes made are not
5832 // part of the original matcher. Therefore, they should be dropped
5833 // otherwise the original matcher will not present the right state.
5834 TPT.rollback(LastKnownGood);
5835
5836 // If the match didn't cover I, then it won't be shared by it.
5837 if (!is_contained(MatchedAddrModeInsts, I))
5838 return false;
5839
5840 MatchedAddrModeInsts.clear();
5841 }
5842
5843 return true;
5844}
5845
5846/// Return true if the specified values are defined in a
5847/// different basic block than BB.
5848static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
5850 return I->getParent() != BB;
5851 return false;
5852}
5853
5854// Find an insert position of Addr for MemoryInst. We can't guarantee MemoryInst
5855// is the first instruction that will use Addr. So we need to find the first
5856// user of Addr in current BB.
5858 Value *SunkAddr) {
5859 if (Addr->hasOneUse())
5860 return MemoryInst->getIterator();
5861
5862 // We already have a SunkAddr in current BB, but we may need to insert cast
5863 // instruction after it.
5864 if (SunkAddr) {
5865 if (Instruction *AddrInst = dyn_cast<Instruction>(SunkAddr))
5866 return std::next(AddrInst->getIterator());
5867 }
5868
5869 // Find the first user of Addr in current BB.
5870 Instruction *Earliest = MemoryInst;
5871 for (User *U : Addr->users()) {
5872 Instruction *UserInst = dyn_cast<Instruction>(U);
5873 if (UserInst && UserInst->getParent() == MemoryInst->getParent()) {
5874 if (isa<PHINode>(UserInst) || UserInst->isDebugOrPseudoInst())
5875 continue;
5876 if (UserInst->comesBefore(Earliest))
5877 Earliest = UserInst;
5878 }
5879 }
5880 return Earliest->getIterator();
5881}
5882
5883/// Sink addressing mode computation immediate before MemoryInst if doing so
5884/// can be done without increasing register pressure. The need for the
5885/// register pressure constraint means this can end up being an all or nothing
5886/// decision for all uses of the same addressing computation.
5887///
5888/// Load and Store Instructions often have addressing modes that can do
5889/// significant amounts of computation. As such, instruction selection will try
5890/// to get the load or store to do as much computation as possible for the
5891/// program. The problem is that isel can only see within a single block. As
5892/// such, we sink as much legal addressing mode work into the block as possible.
5893///
5894/// This method is used to optimize both load/store and inline asms with memory
5895/// operands. It's also used to sink addressing computations feeding into cold
5896/// call sites into their (cold) basic block.
5897///
5898/// The motivation for handling sinking into cold blocks is that doing so can
5899/// both enable other address mode sinking (by satisfying the register pressure
5900/// constraint above), and reduce register pressure globally (by removing the
5901/// addressing mode computation from the fast path entirely.).
5902bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
5903 Type *AccessTy, unsigned AddrSpace) {
5904 Value *Repl = Addr;
5905
5906 // Try to collapse single-value PHI nodes. This is necessary to undo
5907 // unprofitable PRE transformations.
5908 SmallVector<Value *, 8> worklist;
5909 SmallPtrSet<Value *, 16> Visited;
5910 worklist.push_back(Addr);
5911
5912 // Use a worklist to iteratively look through PHI and select nodes, and
5913 // ensure that the addressing mode obtained from the non-PHI/select roots of
5914 // the graph are compatible.
5915 bool PhiOrSelectSeen = false;
5916 SmallVector<Instruction *, 16> AddrModeInsts;
5917 AddressingModeCombiner AddrModes(*DL, Addr);
5918 TypePromotionTransaction TPT(RemovedInsts);
5919 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5920 TPT.getRestorationPoint();
5921 while (!worklist.empty()) {
5922 Value *V = worklist.pop_back_val();
5923
5924 // We allow traversing cyclic Phi nodes.
5925 // In case of success after this loop we ensure that traversing through
5926 // Phi nodes ends up with all cases to compute address of the form
5927 // BaseGV + Base + Scale * Index + Offset
5928 // where Scale and Offset are constans and BaseGV, Base and Index
5929 // are exactly the same Values in all cases.
5930 // It means that BaseGV, Scale and Offset dominate our memory instruction
5931 // and have the same value as they had in address computation represented
5932 // as Phi. So we can safely sink address computation to memory instruction.
5933 if (!Visited.insert(V).second)
5934 continue;
5935
5936 // For a PHI node, push all of its incoming values.
5937 if (PHINode *P = dyn_cast<PHINode>(V)) {
5938 append_range(worklist, P->incoming_values());
5939 PhiOrSelectSeen = true;
5940 continue;
5941 }
5942 // Similar for select.
5943 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
5944 worklist.push_back(SI->getFalseValue());
5945 worklist.push_back(SI->getTrueValue());
5946 PhiOrSelectSeen = true;
5947 continue;
5948 }
5949
5950 // For non-PHIs, determine the addressing mode being computed. Note that
5951 // the result may differ depending on what other uses our candidate
5952 // addressing instructions might have.
5953 AddrModeInsts.clear();
5954 std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr,
5955 0);
5956 // Defer the query (and possible computation of) the dom tree to point of
5957 // actual use. It's expected that most address matches don't actually need
5958 // the domtree.
5959 auto getDTFn = [this]() -> const DominatorTree & { return getDT(); };
5960 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
5961 V, AccessTy, AddrSpace, MemoryInst, AddrModeInsts, *TLI, *LI, getDTFn,
5962 *TRI, InsertedInsts, PromotedInsts, TPT, LargeOffsetGEP, OptSize, PSI,
5963 BFI);
5964
5965 GetElementPtrInst *GEP = LargeOffsetGEP.first;
5966 if (GEP && !NewGEPBases.count(GEP)) {
5967 // If splitting the underlying data structure can reduce the offset of a
5968 // GEP, collect the GEP. Skip the GEPs that are the new bases of
5969 // previously split data structures.
5970 LargeOffsetGEPMap[GEP->getPointerOperand()].push_back(LargeOffsetGEP);
5971 LargeOffsetGEPID.insert(std::make_pair(GEP, LargeOffsetGEPID.size()));
5972 }
5973
5974 NewAddrMode.OriginalValue = V;
5975 if (!AddrModes.addNewAddrMode(NewAddrMode))
5976 break;
5977 }
5978
5979 // Try to combine the AddrModes we've collected. If we couldn't collect any,
5980 // or we have multiple but either couldn't combine them or combining them
5981 // wouldn't do anything useful, bail out now.
5982 if (!AddrModes.combineAddrModes()) {
5983 TPT.rollback(LastKnownGood);
5984 return false;
5985 }
5986 bool Modified = TPT.commit();
5987
5988 // Get the combined AddrMode (or the only AddrMode, if we only had one).
5989 ExtAddrMode AddrMode = AddrModes.getAddrMode();
5990
5991 // If all the instructions matched are already in this BB, don't do anything.
5992 // If we saw a Phi node then it is not local definitely, and if we saw a
5993 // select then we want to push the address calculation past it even if it's
5994 // already in this BB.
5995 if (!PhiOrSelectSeen && none_of(AddrModeInsts, [&](Value *V) {
5996 return IsNonLocalValue(V, MemoryInst->getParent());
5997 })) {
5998 LLVM_DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode
5999 << "\n");
6000 return Modified;
6001 }
6002
6003 // Now that we determined the addressing expression we want to use and know
6004 // that we have to sink it into this block. Check to see if we have already
6005 // done this for some other load/store instr in this block. If so, reuse
6006 // the computation. Before attempting reuse, check if the address is valid
6007 // as it may have been erased.
6008
6009 WeakTrackingVH SunkAddrVH = SunkAddrs[Addr];
6010
6011 Value *SunkAddr = SunkAddrVH.pointsToAliveValue() ? SunkAddrVH : nullptr;
6012 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
6013
6014 // The current BB may be optimized multiple times, we can't guarantee the
6015 // reuse of Addr happens later, call findInsertPos to find an appropriate
6016 // insert position.
6017 auto InsertPos = findInsertPos(Addr, MemoryInst, SunkAddr);
6018
6019 // TODO: Adjust insert point considering (Base|Scaled)Reg if possible.
6020 if (!SunkAddr) {
6021 auto &DT = getDT();
6022 if ((AddrMode.BaseReg && !DT.dominates(AddrMode.BaseReg, &*InsertPos)) ||
6023 (AddrMode.ScaledReg && !DT.dominates(AddrMode.ScaledReg, &*InsertPos)))
6024 return Modified;
6025 }
6026
6027 IRBuilder<> Builder(MemoryInst->getParent(), InsertPos);
6028
6029 if (SunkAddr) {
6030 LLVM_DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode
6031 << " for " << *MemoryInst << "\n");
6032 if (SunkAddr->getType() != Addr->getType()) {
6033 if (SunkAddr->getType()->getPointerAddressSpace() !=
6034 Addr->getType()->getPointerAddressSpace() &&
6035 !DL->isNonIntegralPointerType(Addr->getType())) {
6036 // There are two reasons the address spaces might not match: a no-op
6037 // addrspacecast, or a ptrtoint/inttoptr pair. Either way, we emit a
6038 // ptrtoint/inttoptr pair to ensure we match the original semantics.
6039 // TODO: allow bitcast between different address space pointers with the
6040 // same size.
6041 SunkAddr = Builder.CreatePtrToInt(SunkAddr, IntPtrTy, "sunkaddr");
6042 SunkAddr =
6043 Builder.CreateIntToPtr(SunkAddr, Addr->getType(), "sunkaddr");
6044 } else
6045 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
6046 }
6048 SubtargetInfo->addrSinkUsingGEPs())) {
6049 // By default, we use the GEP-based method when AA is used later. This
6050 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
6051 LLVM_DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode
6052 << " for " << *MemoryInst << "\n");
6053 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
6054
6055 // First, find the pointer.
6056 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
6057 ResultPtr = AddrMode.BaseReg;
6058 AddrMode.BaseReg = nullptr;
6059 }
6060
6061 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
6062 // We can't add more than one pointer together, nor can we scale a
6063 // pointer (both of which seem meaningless).
6064 if (ResultPtr || AddrMode.Scale != 1)
6065 return Modified;
6066
6067 ResultPtr = AddrMode.ScaledReg;
6068 AddrMode.Scale = 0;
6069 }
6070
6071 // It is only safe to sign extend the BaseReg if we know that the math
6072 // required to create it did not overflow before we extend it. Since
6073 // the original IR value was tossed in favor of a constant back when
6074 // the AddrMode was created we need to bail out gracefully if widths
6075 // do not match instead of extending it.
6076 //
6077 // (See below for code to add the scale.)
6078 if (AddrMode.Scale) {
6079 Type *ScaledRegTy = AddrMode.ScaledReg->getType();
6081 cast<IntegerType>(ScaledRegTy)->getBitWidth())
6082 return Modified;
6083 }
6084
6085 GlobalValue *BaseGV = AddrMode.BaseGV;
6086 if (BaseGV != nullptr) {
6087 if (ResultPtr)
6088 return Modified;
6089
6090 if (BaseGV->isThreadLocal()) {
6091 ResultPtr = Builder.CreateThreadLocalAddress(BaseGV);
6092 } else {
6093 ResultPtr = BaseGV;
6094 }
6095 }
6096
6097 // If the real base value actually came from an inttoptr, then the matcher
6098 // will look through it and provide only the integer value. In that case,
6099 // use it here.
6100 if (!DL->isNonIntegralPointerType(Addr->getType())) {
6101 if (!ResultPtr && AddrMode.BaseReg) {
6102 ResultPtr = Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(),
6103 "sunkaddr");
6104 AddrMode.BaseReg = nullptr;
6105 } else if (!ResultPtr && AddrMode.Scale == 1) {
6106 ResultPtr = Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(),
6107 "sunkaddr");
6108 AddrMode.Scale = 0;
6109 }
6110 }
6111
6112 if (!ResultPtr && !AddrMode.BaseReg && !AddrMode.Scale &&
6113 !AddrMode.BaseOffs) {
6114 SunkAddr = Constant::getNullValue(Addr->getType());
6115 } else if (!ResultPtr) {
6116 return Modified;
6117 } else {
6118 Type *I8PtrTy =
6119 Builder.getPtrTy(Addr->getType()->getPointerAddressSpace());
6120
6121 // Start with the base register. Do this first so that subsequent address
6122 // matching finds it last, which will prevent it from trying to match it
6123 // as the scaled value in case it happens to be a mul. That would be
6124 // problematic if we've sunk a different mul for the scale, because then
6125 // we'd end up sinking both muls.
6126 if (AddrMode.BaseReg) {
6127 Value *V = AddrMode.BaseReg;
6128 if (V->getType() != IntPtrTy)
6129 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
6130
6131 ResultIndex = V;
6132 }
6133
6134 // Add the scale value.
6135 if (AddrMode.Scale) {
6136 Value *V = AddrMode.ScaledReg;
6137 if (V->getType() == IntPtrTy) {
6138 // done.
6139 } else {
6141 cast<IntegerType>(V->getType())->getBitWidth() &&
6142 "We can't transform if ScaledReg is too narrow");
6143 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
6144 }
6145
6146 if (AddrMode.Scale != 1)
6147 V = Builder.CreateMul(
6148 V, ConstantInt::getSigned(IntPtrTy, AddrMode.Scale), "sunkaddr");
6149 if (ResultIndex)
6150 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
6151 else
6152 ResultIndex = V;
6153 }
6154
6155 // Add in the Base Offset if present.
6156 if (AddrMode.BaseOffs) {
6158 if (ResultIndex) {
6159 // We need to add this separately from the scale above to help with
6160 // SDAG consecutive load/store merging.
6161 if (ResultPtr->getType() != I8PtrTy)
6162 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
6163 ResultPtr = Builder.CreatePtrAdd(ResultPtr, ResultIndex, "sunkaddr",
6164 AddrMode.InBounds);
6165 }
6166
6167 ResultIndex = V;
6168 }
6169
6170 if (!ResultIndex) {
6171 auto PtrInst = dyn_cast<Instruction>(ResultPtr);
6172 // We know that we have a pointer without any offsets. If this pointer
6173 // originates from a different basic block than the current one, we
6174 // must be able to recreate it in the current basic block.
6175 // We do not support the recreation of any instructions yet.
6176 if (PtrInst && PtrInst->getParent() != MemoryInst->getParent())
6177 return Modified;
6178 SunkAddr = ResultPtr;
6179 } else {
6180 if (ResultPtr->getType() != I8PtrTy)
6181 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
6182 SunkAddr = Builder.CreatePtrAdd(ResultPtr, ResultIndex, "sunkaddr",
6183 AddrMode.InBounds);
6184 }
6185
6186 if (SunkAddr->getType() != Addr->getType()) {
6187 if (SunkAddr->getType()->getPointerAddressSpace() !=
6188 Addr->getType()->getPointerAddressSpace() &&
6189 !DL->isNonIntegralPointerType(Addr->getType())) {
6190 // There are two reasons the address spaces might not match: a no-op
6191 // addrspacecast, or a ptrtoint/inttoptr pair. Either way, we emit a
6192 // ptrtoint/inttoptr pair to ensure we match the original semantics.
6193 // TODO: allow bitcast between different address space pointers with
6194 // the same size.
6195 SunkAddr = Builder.CreatePtrToInt(SunkAddr, IntPtrTy, "sunkaddr");
6196 SunkAddr =
6197 Builder.CreateIntToPtr(SunkAddr, Addr->getType(), "sunkaddr");
6198 } else
6199 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
6200 }
6201 }
6202 } else {
6203 // We'd require a ptrtoint/inttoptr down the line, which we can't do for
6204 // non-integral pointers, so in that case bail out now.
6205 Type *BaseTy = AddrMode.BaseReg ? AddrMode.BaseReg->getType() : nullptr;
6206 Type *ScaleTy = AddrMode.Scale ? AddrMode.ScaledReg->getType() : nullptr;
6207 PointerType *BasePtrTy = dyn_cast_or_null<PointerType>(BaseTy);
6208 PointerType *ScalePtrTy = dyn_cast_or_null<PointerType>(ScaleTy);
6209 if (DL->isNonIntegralPointerType(Addr->getType()) ||
6210 (BasePtrTy && DL->isNonIntegralPointerType(BasePtrTy)) ||
6211 (ScalePtrTy && DL->isNonIntegralPointerType(ScalePtrTy)) ||
6212 (AddrMode.BaseGV &&
6213 DL->isNonIntegralPointerType(AddrMode.BaseGV->getType())))
6214 return Modified;
6215
6216 LLVM_DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode
6217 << " for " << *MemoryInst << "\n");
6218 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
6219 Value *Result = nullptr;
6220
6221 // Start with the base register. Do this first so that subsequent address
6222 // matching finds it last, which will prevent it from trying to match it
6223 // as the scaled value in case it happens to be a mul. That would be
6224 // problematic if we've sunk a different mul for the scale, because then
6225 // we'd end up sinking both muls.
6226 if (AddrMode.BaseReg) {
6227 Value *V = AddrMode.BaseReg;
6228 if (V->getType()->isPointerTy())
6229 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
6230 if (V->getType() != IntPtrTy)
6231 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
6232 Result = V;
6233 }
6234
6235 // Add the scale value.
6236 if (AddrMode.Scale) {
6237 Value *V = AddrMode.ScaledReg;
6238 if (V->getType() == IntPtrTy) {
6239 // done.
6240 } else if (V->getType()->isPointerTy()) {
6241 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
6242 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
6243 cast<IntegerType>(V->getType())->getBitWidth()) {
6244 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
6245 } else {
6246 // It is only safe to sign extend the BaseReg if we know that the math
6247 // required to create it did not overflow before we extend it. Since
6248 // the original IR value was tossed in favor of a constant back when
6249 // the AddrMode was created we need to bail out gracefully if widths
6250 // do not match instead of extending it.
6252 if (I && (Result != AddrMode.BaseReg))
6253 I->eraseFromParent();
6254 return Modified;
6255 }
6256 if (AddrMode.Scale != 1)
6257 V = Builder.CreateMul(
6258 V, ConstantInt::getSigned(IntPtrTy, AddrMode.Scale), "sunkaddr");
6259 if (Result)
6260 Result = Builder.CreateAdd(Result, V, "sunkaddr");
6261 else
6262 Result = V;
6263 }
6264
6265 // Add in the BaseGV if present.
6266 GlobalValue *BaseGV = AddrMode.BaseGV;
6267 if (BaseGV != nullptr) {
6268 Value *BaseGVPtr;
6269 if (BaseGV->isThreadLocal()) {
6270 BaseGVPtr = Builder.CreateThreadLocalAddress(BaseGV);
6271 } else {
6272 BaseGVPtr = BaseGV;
6273 }
6274 Value *V = Builder.CreatePtrToInt(BaseGVPtr, IntPtrTy, "sunkaddr");
6275 if (Result)
6276 Result = Builder.CreateAdd(Result, V, "sunkaddr");
6277 else
6278 Result = V;
6279 }
6280
6281 // Add in the Base Offset if present.
6282 if (AddrMode.BaseOffs) {
6284 if (Result)
6285 Result = Builder.CreateAdd(Result, V, "sunkaddr");
6286 else
6287 Result = V;
6288 }
6289
6290 if (!Result)
6291 SunkAddr = Constant::getNullValue(Addr->getType());
6292 else
6293 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
6294 }
6295
6296 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
6297 // Store the newly computed address into the cache. In the case we reused a
6298 // value, this should be idempotent.
6299 SunkAddrs[Addr] = WeakTrackingVH(SunkAddr);
6300
6301 // If we have no uses, recursively delete the value and all dead instructions
6302 // using it.
6303 if (Repl->use_empty()) {
6304 resetIteratorIfInvalidatedWhileCalling(CurInstIterator->getParent(), [&]() {
6305 RecursivelyDeleteTriviallyDeadInstructions(
6306 Repl, TLInfo, nullptr,
6307 [&](Value *V) { removeAllAssertingVHReferences(V); });
6308 });
6309 }
6310 ++NumMemoryInsts;
6311 return true;
6312}
6313
6314/// Rewrite GEP input to gather/scatter to enable SelectionDAGBuilder to find
6315/// a uniform base to use for ISD::MGATHER/MSCATTER. SelectionDAGBuilder can
6316/// only handle a 2 operand GEP in the same basic block or a splat constant
6317/// vector. The 2 operands to the GEP must have a scalar pointer and a vector
6318/// index.
6319///
6320/// If the existing GEP has a vector base pointer that is splat, we can look
6321/// through the splat to find the scalar pointer. If we can't find a scalar
6322/// pointer there's nothing we can do.
6323///
6324/// If we have a GEP with more than 2 indices where the middle indices are all
6325/// zeroes, we can replace it with 2 GEPs where the second has 2 operands.
6326///
6327/// If the final index isn't a vector or is a splat, we can emit a scalar GEP
6328/// followed by a GEP with an all zeroes vector index. This will enable
6329/// SelectionDAGBuilder to use the scalar GEP as the uniform base and have a
6330/// zero index.
6331bool CodeGenPrepare::optimizeGatherScatterInst(Instruction *MemoryInst,
6332 Value *Ptr) {
6333 Value *NewAddr;
6334
6335 if (const auto *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
6336 // Don't optimize GEPs that don't have indices.
6337 if (!GEP->hasIndices())
6338 return false;
6339
6340 // If the GEP and the gather/scatter aren't in the same BB, don't optimize.
6341 // FIXME: We should support this by sinking the GEP.
6342 if (MemoryInst->getParent() != GEP->getParent())
6343 return false;
6344
6345 SmallVector<Value *, 2> Ops(GEP->operands());
6346
6347 bool RewriteGEP = false;
6348
6349 if (Ops[0]->getType()->isVectorTy()) {
6350 Ops[0] = getSplatValue(Ops[0]);
6351 if (!Ops[0])
6352 return false;
6353 RewriteGEP = true;
6354 }
6355
6356 unsigned FinalIndex = Ops.size() - 1;
6357
6358 // Ensure all but the last index is 0.
6359 // FIXME: This isn't strictly required. All that's required is that they are
6360 // all scalars or splats.
6361 for (unsigned i = 1; i < FinalIndex; ++i) {
6362 auto *C = dyn_cast<Constant>(Ops[i]);
6363 if (!C)
6364 return false;
6365 if (isa<VectorType>(C->getType()))
6366 C = C->getSplatValue();
6367 auto *CI = dyn_cast_or_null<ConstantInt>(C);
6368 if (!CI || !CI->isZero())
6369 return false;
6370 // Scalarize the index if needed.
6371 Ops[i] = CI;
6372 }
6373
6374 // Try to scalarize the final index.
6375 if (Ops[FinalIndex]->getType()->isVectorTy()) {
6376 if (Value *V = getSplatValue(Ops[FinalIndex])) {
6377 auto *C = dyn_cast<ConstantInt>(V);
6378 // Don't scalarize all zeros vector.
6379 if (!C || !C->isZero()) {
6380 Ops[FinalIndex] = V;
6381 RewriteGEP = true;
6382 }
6383 }
6384 }
6385
6386 // If we made any changes or the we have extra operands, we need to generate
6387 // new instructions.
6388 if (!RewriteGEP && Ops.size() == 2)
6389 return false;
6390
6391 auto NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
6392
6393 IRBuilder<> Builder(MemoryInst);
6394
6395 Type *SourceTy = GEP->getSourceElementType();
6396 Type *ScalarIndexTy = DL->getIndexType(Ops[0]->getType()->getScalarType());
6397
6398 // If the final index isn't a vector, emit a scalar GEP containing all ops
6399 // and a vector GEP with all zeroes final index.
6400 if (!Ops[FinalIndex]->getType()->isVectorTy()) {
6401 NewAddr = Builder.CreateGEP(SourceTy, Ops[0], ArrayRef(Ops).drop_front());
6402 auto *IndexTy = VectorType::get(ScalarIndexTy, NumElts);
6403 auto *SecondTy = GetElementPtrInst::getIndexedType(
6404 SourceTy, ArrayRef(Ops).drop_front());
6405 NewAddr =
6406 Builder.CreateGEP(SecondTy, NewAddr, Constant::getNullValue(IndexTy));
6407 } else {
6408 Value *Base = Ops[0];
6409 Value *Index = Ops[FinalIndex];
6410
6411 // Create a scalar GEP if there are more than 2 operands.
6412 if (Ops.size() != 2) {
6413 // Replace the last index with 0.
6414 Ops[FinalIndex] =
6415 Constant::getNullValue(Ops[FinalIndex]->getType()->getScalarType());
6416 Base = Builder.CreateGEP(SourceTy, Base, ArrayRef(Ops).drop_front());
6418 SourceTy, ArrayRef(Ops).drop_front());
6419 }
6420
6421 // Now create the GEP with scalar pointer and vector index.
6422 NewAddr = Builder.CreateGEP(SourceTy, Base, Index);
6423 }
6424 } else if (!isa<Constant>(Ptr)) {
6425 // Not a GEP, maybe its a splat and we can create a GEP to enable
6426 // SelectionDAGBuilder to use it as a uniform base.
6427 Value *V = getSplatValue(Ptr);
6428 if (!V)
6429 return false;
6430
6431 auto NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
6432
6433 IRBuilder<> Builder(MemoryInst);
6434
6435 // Emit a vector GEP with a scalar pointer and all 0s vector index.
6436 Type *ScalarIndexTy = DL->getIndexType(V->getType()->getScalarType());
6437 auto *IndexTy = VectorType::get(ScalarIndexTy, NumElts);
6438 Type *ScalarTy;
6439 if (cast<IntrinsicInst>(MemoryInst)->getIntrinsicID() ==
6440 Intrinsic::masked_gather) {
6441 ScalarTy = MemoryInst->getType()->getScalarType();
6442 } else {
6443 assert(cast<IntrinsicInst>(MemoryInst)->getIntrinsicID() ==
6444 Intrinsic::masked_scatter);
6445 ScalarTy = MemoryInst->getOperand(0)->getType()->getScalarType();
6446 }
6447 NewAddr = Builder.CreateGEP(ScalarTy, V, Constant::getNullValue(IndexTy));
6448 } else {
6449 // Constant, SelectionDAGBuilder knows to check if its a splat.
6450 return false;
6451 }
6452
6453 MemoryInst->replaceUsesOfWith(Ptr, NewAddr);
6454
6455 // If we have no uses, recursively delete the value and all dead instructions
6456 // using it.
6457 if (Ptr->use_empty())
6459 Ptr, TLInfo, nullptr,
6460 [&](Value *V) { removeAllAssertingVHReferences(V); });
6461
6462 return true;
6463}
6464
6465// This is a helper for CodeGenPrepare::optimizeMulWithOverflow.
6466// Check the pattern we are interested in where there are maximum 2 uses
6467// of the intrinsic which are the extract instructions.
6469 ExtractValueInst *&OverflowExtract) {
6470 // Bail out if it's more than 2 users:
6471 if (I->hasNUsesOrMore(3))
6472 return false;
6473
6474 for (User *U : I->users()) {
6475 auto *Extract = dyn_cast<ExtractValueInst>(U);
6476 if (!Extract || Extract->getNumIndices() != 1)
6477 return false;
6478
6479 unsigned Index = Extract->getIndices()[0];
6480 if (Index == 0)
6481 MulExtract = Extract;
6482 else if (Index == 1)
6483 OverflowExtract = Extract;
6484 else
6485 return false;
6486 }
6487 return true;
6488}
6489
6490// Rewrite the mul_with_overflow intrinsic by checking if both of the
6491// operands' value ranges are within the legal type. If so, we can optimize the
6492// multiplication algorithm. This code is supposed to be written during the step
6493// of type legalization, but given that we need to reconstruct the IR which is
6494// not doable there, we do it here.
6495// The IR after the optimization will look like:
6496// entry:
6497// if signed:
6498// ( (lhs_lo>>BW-1) ^ lhs_hi) || ( (rhs_lo>>BW-1) ^ rhs_hi) ? overflow,
6499// overflow_no
6500// else:
6501// (lhs_hi != 0) || (rhs_hi != 0) ? overflow, overflow_no
6502// overflow_no:
6503// overflow:
6504// overflow.res:
6505// \returns true if optimization was applied
6506// TODO: This optimization can be further improved to optimize branching on
6507// overflow where the 'overflow_no' BB can branch directly to the false
6508// successor of overflow, but that would add additional complexity so we leave
6509// it for future work.
6510bool CodeGenPrepare::optimizeMulWithOverflow(Instruction *I, bool IsSigned,
6511 ModifyDT &ModifiedDT) {
6512 // Check if target supports this optimization.
6514 I->getContext(),
6515 TLI->getValueType(*DL, I->getType()->getContainedType(0))))
6516 return false;
6517
6518 ExtractValueInst *MulExtract = nullptr, *OverflowExtract = nullptr;
6519 if (!matchOverflowPattern(I, MulExtract, OverflowExtract))
6520 return false;
6521
6522 // Keep track of the instruction to stop reoptimizing it again.
6523 InsertedInsts.insert(I);
6524
6525 Value *LHS = I->getOperand(0);
6526 Value *RHS = I->getOperand(1);
6527 Type *Ty = LHS->getType();
6528 unsigned VTHalfBitWidth = Ty->getScalarSizeInBits() / 2;
6529 Type *LegalTy = Ty->getWithNewBitWidth(VTHalfBitWidth);
6530
6531 // New BBs:
6532 BasicBlock *OverflowEntryBB =
6533 splitBlockBefore(I->getParent(), I, DTU, LI, nullptr, "");
6534 OverflowEntryBB->takeName(I->getParent());
6535 // Keep the 'br' instruction that is generated as a result of the split to be
6536 // erased/replaced later.
6537 Instruction *OldTerminator = OverflowEntryBB->getTerminator();
6538 BasicBlock *NoOverflowBB =
6539 BasicBlock::Create(I->getContext(), "overflow.no", I->getFunction());
6540 NoOverflowBB->moveAfter(OverflowEntryBB);
6541 BasicBlock *OverflowBB =
6542 BasicBlock::Create(I->getContext(), "overflow", I->getFunction());
6543 OverflowBB->moveAfter(NoOverflowBB);
6544
6545 // BB overflow.entry:
6546 IRBuilder<> Builder(OverflowEntryBB);
6547 // Extract low and high halves of LHS:
6548 Value *LoLHS = Builder.CreateTrunc(LHS, LegalTy, "lo.lhs");
6549 Value *HiLHS = Builder.CreateLShr(LHS, VTHalfBitWidth, "lhs.lsr");
6550 HiLHS = Builder.CreateTrunc(HiLHS, LegalTy, "hi.lhs");
6551
6552 // Extract low and high halves of RHS:
6553 Value *LoRHS = Builder.CreateTrunc(RHS, LegalTy, "lo.rhs");
6554 Value *HiRHS = Builder.CreateLShr(RHS, VTHalfBitWidth, "rhs.lsr");
6555 HiRHS = Builder.CreateTrunc(HiRHS, LegalTy, "hi.rhs");
6556
6557 Value *IsAnyBitTrue;
6558 if (IsSigned) {
6559 Value *SignLoLHS =
6560 Builder.CreateAShr(LoLHS, VTHalfBitWidth - 1, "sign.lo.lhs");
6561 Value *SignLoRHS =
6562 Builder.CreateAShr(LoRHS, VTHalfBitWidth - 1, "sign.lo.rhs");
6563 Value *XorLHS = Builder.CreateXor(HiLHS, SignLoLHS);
6564 Value *XorRHS = Builder.CreateXor(HiRHS, SignLoRHS);
6565 Value *Or = Builder.CreateOr(XorLHS, XorRHS, "or.lhs.rhs");
6566 IsAnyBitTrue = Builder.CreateCmp(ICmpInst::ICMP_NE, Or,
6567 ConstantInt::getNullValue(Or->getType()));
6568 } else {
6569 Value *CmpLHS = Builder.CreateCmp(ICmpInst::ICMP_NE, HiLHS,
6570 ConstantInt::getNullValue(LegalTy));
6571 Value *CmpRHS = Builder.CreateCmp(ICmpInst::ICMP_NE, HiRHS,
6572 ConstantInt::getNullValue(LegalTy));
6573 IsAnyBitTrue = Builder.CreateOr(CmpLHS, CmpRHS, "or.lhs.rhs");
6574 }
6575 Builder.CreateCondBr(IsAnyBitTrue, OverflowBB, NoOverflowBB);
6576
6577 // BB overflow.no:
6578 Builder.SetInsertPoint(NoOverflowBB);
6579 Value *ExtLoLHS, *ExtLoRHS;
6580 if (IsSigned) {
6581 ExtLoLHS = Builder.CreateSExt(LoLHS, Ty, "lo.lhs.ext");
6582 ExtLoRHS = Builder.CreateSExt(LoRHS, Ty, "lo.rhs.ext");
6583 } else {
6584 ExtLoLHS = Builder.CreateZExt(LoLHS, Ty, "lo.lhs.ext");
6585 ExtLoRHS = Builder.CreateZExt(LoRHS, Ty, "lo.rhs.ext");
6586 }
6587
6588 Value *Mul = Builder.CreateMul(ExtLoLHS, ExtLoRHS, "mul.overflow.no");
6589
6590 // Create the 'overflow.res' BB to merge the results of
6591 // the two paths:
6592 BasicBlock *OverflowResBB = I->getParent();
6593 OverflowResBB->setName("overflow.res");
6594
6595 // BB overflow.no: jump to overflow.res BB
6596 Builder.CreateBr(OverflowResBB);
6597 // No we don't need the old terminator in overflow.entry BB, erase it:
6598 OldTerminator->eraseFromParent();
6599
6600 // BB overflow.res:
6601 Builder.SetInsertPoint(OverflowResBB, OverflowResBB->getFirstInsertionPt());
6602 // Create PHI nodes to merge results from no.overflow BB and overflow BB to
6603 // replace the extract instructions.
6604 PHINode *OverflowResPHI = Builder.CreatePHI(Ty, 2),
6605 *OverflowFlagPHI =
6606 Builder.CreatePHI(IntegerType::getInt1Ty(I->getContext()), 2);
6607
6608 // Add the incoming values from no.overflow BB and later from overflow BB.
6609 OverflowResPHI->addIncoming(Mul, NoOverflowBB);
6610 OverflowFlagPHI->addIncoming(ConstantInt::getFalse(I->getContext()),
6611 NoOverflowBB);
6612
6613 // Replace all users of MulExtract and OverflowExtract to use the PHI nodes.
6614 if (MulExtract) {
6615 MulExtract->replaceAllUsesWith(OverflowResPHI);
6616 MulExtract->eraseFromParent();
6617 }
6618 if (OverflowExtract) {
6619 OverflowExtract->replaceAllUsesWith(OverflowFlagPHI);
6620 OverflowExtract->eraseFromParent();
6621 }
6622
6623 // Remove the intrinsic from parent (overflow.res BB) as it will be part of
6624 // overflow BB
6625 I->removeFromParent();
6626 // BB overflow:
6627 I->insertInto(OverflowBB, OverflowBB->end());
6628 Builder.SetInsertPoint(OverflowBB, OverflowBB->end());
6629 Value *MulOverflow = Builder.CreateExtractValue(I, {0}, "mul.overflow");
6630 Value *OverflowFlag = Builder.CreateExtractValue(I, {1}, "overflow.flag");
6631 Builder.CreateBr(OverflowResBB);
6632
6633 // Add The Extracted values to the PHINodes in the overflow.res BB.
6634 OverflowResPHI->addIncoming(MulOverflow, OverflowBB);
6635 OverflowFlagPHI->addIncoming(OverflowFlag, OverflowBB);
6636
6637 DTU->applyUpdates({{DominatorTree::Insert, OverflowEntryBB, OverflowBB},
6638 {DominatorTree::Insert, OverflowEntryBB, NoOverflowBB},
6639 {DominatorTree::Insert, NoOverflowBB, OverflowResBB},
6640 {DominatorTree::Delete, OverflowEntryBB, OverflowResBB},
6641 {DominatorTree::Insert, OverflowBB, OverflowResBB}});
6642
6643 ModifiedDT = ModifyDT::ModifyBBDT;
6644 return true;
6645}
6646
6647/// If there are any memory operands, use OptimizeMemoryInst to sink their
6648/// address computing into the block when possible / profitable.
6649bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
6650 bool MadeChange = false;
6651
6652 const TargetRegisterInfo *TRI =
6654 TargetLowering::AsmOperandInfoVector TargetConstraints =
6655 TLI->ParseConstraints(*DL, TRI, *CS);
6656 unsigned ArgNo = 0;
6657 for (TargetLowering::AsmOperandInfo &OpInfo : TargetConstraints) {
6658 // Compute the constraint code and ConstraintType to use.
6659 TLI->ComputeConstraintToUse(OpInfo, SDValue());
6660
6661 // TODO: Also handle C_Address?
6662 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
6663 OpInfo.isIndirect) {
6664 Value *OpVal = CS->getArgOperand(ArgNo++);
6665 MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
6666 } else if (OpInfo.Type == InlineAsm::isInput)
6667 ArgNo++;
6668 }
6669
6670 return MadeChange;
6671}
6672
6673/// Check if all the uses of \p Val are equivalent (or free) zero or
6674/// sign extensions.
6675static bool hasSameExtUse(Value *Val, const TargetLowering &TLI) {
6676 assert(!Val->use_empty() && "Input must have at least one use");
6677 const Instruction *FirstUser = cast<Instruction>(*Val->user_begin());
6678 bool IsSExt = isa<SExtInst>(FirstUser);
6679 Type *ExtTy = FirstUser->getType();
6680 for (const User *U : Val->users()) {
6681 const Instruction *UI = cast<Instruction>(U);
6682 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
6683 return false;
6684 Type *CurTy = UI->getType();
6685 // Same input and output types: Same instruction after CSE.
6686 if (CurTy == ExtTy)
6687 continue;
6688
6689 // If IsSExt is true, we are in this situation:
6690 // a = Val
6691 // b = sext ty1 a to ty2
6692 // c = sext ty1 a to ty3
6693 // Assuming ty2 is shorter than ty3, this could be turned into:
6694 // a = Val
6695 // b = sext ty1 a to ty2
6696 // c = sext ty2 b to ty3
6697 // However, the last sext is not free.
6698 if (IsSExt)
6699 return false;
6700
6701 // This is a ZExt, maybe this is free to extend from one type to another.
6702 // In that case, we would not account for a different use.
6703 Type *NarrowTy;
6704 Type *LargeTy;
6705 if (ExtTy->getScalarType()->getIntegerBitWidth() >
6706 CurTy->getScalarType()->getIntegerBitWidth()) {
6707 NarrowTy = CurTy;
6708 LargeTy = ExtTy;
6709 } else {
6710 NarrowTy = ExtTy;
6711 LargeTy = CurTy;
6712 }
6713
6714 if (!TLI.isZExtFree(NarrowTy, LargeTy))
6715 return false;
6716 }
6717 // All uses are the same or can be derived from one another for free.
6718 return true;
6719}
6720
6721/// Try to speculatively promote extensions in \p Exts and continue
6722/// promoting through newly promoted operands recursively as far as doing so is
6723/// profitable. Save extensions profitably moved up, in \p ProfitablyMovedExts.
6724/// When some promotion happened, \p TPT contains the proper state to revert
6725/// them.
6726///
6727/// \return true if some promotion happened, false otherwise.
6728bool CodeGenPrepare::tryToPromoteExts(
6729 TypePromotionTransaction &TPT, const SmallVectorImpl<Instruction *> &Exts,
6730 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
6731 unsigned CreatedInstsCost) {
6732 bool Promoted = false;
6733
6734 // Iterate over all the extensions to try to promote them.
6735 for (auto *I : Exts) {
6736 // Early check if we directly have ext(load).
6737 if (isa<LoadInst>(I->getOperand(0))) {
6738 ProfitablyMovedExts.push_back(I);
6739 continue;
6740 }
6741
6742 // Check whether or not we want to do any promotion. The reason we have
6743 // this check inside the for loop is to catch the case where an extension
6744 // is directly fed by a load because in such case the extension can be moved
6745 // up without any promotion on its operands.
6747 return false;
6748
6749 // Get the action to perform the promotion.
6750 TypePromotionHelper::Action TPH =
6751 TypePromotionHelper::getAction(I, InsertedInsts, *TLI, PromotedInsts);
6752 // Check if we can promote.
6753 if (!TPH) {
6754 // Save the current extension as we cannot move up through its operand.
6755 ProfitablyMovedExts.push_back(I);
6756 continue;
6757 }
6758
6759 // Save the current state.
6760 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
6761 TPT.getRestorationPoint();
6762 SmallVector<Instruction *, 4> NewExts;
6763 unsigned NewCreatedInstsCost = 0;
6764 unsigned ExtCost = !TLI->isExtFree(I);
6765 // Promote.
6766 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
6767 &NewExts, nullptr, *TLI);
6768 assert(PromotedVal &&
6769 "TypePromotionHelper should have filtered out those cases");
6770
6771 // We would be able to merge only one extension in a load.
6772 // Therefore, if we have more than 1 new extension we heuristically
6773 // cut this search path, because it means we degrade the code quality.
6774 // With exactly 2, the transformation is neutral, because we will merge
6775 // one extension but leave one. However, we optimistically keep going,
6776 // because the new extension may be removed too. Also avoid replacing a
6777 // single free extension with multiple extensions, as this increases the
6778 // number of IR instructions while not providing any savings.
6779 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
6780 // FIXME: It would be possible to propagate a negative value instead of
6781 // conservatively ceiling it to 0.
6782 TotalCreatedInstsCost =
6783 std::max((long long)0, (TotalCreatedInstsCost - ExtCost));
6784 if (!StressExtLdPromotion &&
6785 (TotalCreatedInstsCost > 1 ||
6786 !isPromotedInstructionLegal(*TLI, *DL, PromotedVal) ||
6787 (ExtCost == 0 && NewExts.size() > 1))) {
6788 // This promotion is not profitable, rollback to the previous state, and
6789 // save the current extension in ProfitablyMovedExts as the latest
6790 // speculative promotion turned out to be unprofitable.
6791 TPT.rollback(LastKnownGood);
6792 ProfitablyMovedExts.push_back(I);
6793 continue;
6794 }
6795 // Continue promoting NewExts as far as doing so is profitable.
6796 SmallVector<Instruction *, 2> NewlyMovedExts;
6797 (void)tryToPromoteExts(TPT, NewExts, NewlyMovedExts, TotalCreatedInstsCost);
6798 bool NewPromoted = false;
6799 for (auto *ExtInst : NewlyMovedExts) {
6800 Instruction *MovedExt = cast<Instruction>(ExtInst);
6801 Value *ExtOperand = MovedExt->getOperand(0);
6802 // If we have reached to a load, we need this extra profitability check
6803 // as it could potentially be merged into an ext(load).
6804 if (isa<LoadInst>(ExtOperand) &&
6805 !(StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
6806 (ExtOperand->hasOneUse() || hasSameExtUse(ExtOperand, *TLI))))
6807 continue;
6808
6809 ProfitablyMovedExts.push_back(MovedExt);
6810 NewPromoted = true;
6811 }
6812
6813 // If none of speculative promotions for NewExts is profitable, rollback
6814 // and save the current extension (I) as the last profitable extension.
6815 if (!NewPromoted) {
6816 TPT.rollback(LastKnownGood);
6817 ProfitablyMovedExts.push_back(I);
6818 continue;
6819 }
6820 // The promotion is profitable.
6821 Promoted = true;
6822 }
6823 return Promoted;
6824}
6825
6826/// Merging redundant sexts when one is dominating the other.
6827bool CodeGenPrepare::mergeSExts(Function &F) {
6828 bool Changed = false;
6829 for (auto &Entry : ValToSExtendedUses) {
6830 SExts &Insts = Entry.second;
6831 SExts CurPts;
6832 for (Instruction *Inst : Insts) {
6833 if (RemovedInsts.count(Inst) || !isa<SExtInst>(Inst) ||
6834 Inst->getOperand(0) != Entry.first)
6835 continue;
6836 bool inserted = false;
6837 for (auto &Pt : CurPts) {
6838 if (getDT().dominates(Inst, Pt)) {
6839 replaceAllUsesWith(Pt, Inst, FreshBBs, IsHugeFunc);
6840 RemovedInsts.insert(Pt);
6841 Pt->removeFromParent();
6842 Pt = Inst;
6843 inserted = true;
6844 Changed = true;
6845 break;
6846 }
6847 if (!getDT().dominates(Pt, Inst))
6848 // Give up if we need to merge in a common dominator as the
6849 // experiments show it is not profitable.
6850 continue;
6851 replaceAllUsesWith(Inst, Pt, FreshBBs, IsHugeFunc);
6852 RemovedInsts.insert(Inst);
6853 Inst->removeFromParent();
6854 inserted = true;
6855 Changed = true;
6856 break;
6857 }
6858 if (!inserted)
6859 CurPts.push_back(Inst);
6860 }
6861 }
6862 return Changed;
6863}
6864
6865// Splitting large data structures so that the GEPs accessing them can have
6866// smaller offsets so that they can be sunk to the same blocks as their users.
6867// For example, a large struct starting from %base is split into two parts
6868// where the second part starts from %new_base.
6869//
6870// Before:
6871// BB0:
6872// %base =
6873//
6874// BB1:
6875// %gep0 = gep %base, off0
6876// %gep1 = gep %base, off1
6877// %gep2 = gep %base, off2
6878//
6879// BB2:
6880// %load1 = load %gep0
6881// %load2 = load %gep1
6882// %load3 = load %gep2
6883//
6884// After:
6885// BB0:
6886// %base =
6887// %new_base = gep %base, off0
6888//
6889// BB1:
6890// %new_gep0 = %new_base
6891// %new_gep1 = gep %new_base, off1 - off0
6892// %new_gep2 = gep %new_base, off2 - off0
6893//
6894// BB2:
6895// %load1 = load i32, i32* %new_gep0
6896// %load2 = load i32, i32* %new_gep1
6897// %load3 = load i32, i32* %new_gep2
6898//
6899// %new_gep1 and %new_gep2 can be sunk to BB2 now after the splitting because
6900// their offsets are smaller enough to fit into the addressing mode.
6901bool CodeGenPrepare::splitLargeGEPOffsets() {
6902 bool Changed = false;
6903 for (auto &Entry : LargeOffsetGEPMap) {
6904 Value *OldBase = Entry.first;
6905 SmallVectorImpl<std::pair<AssertingVH<GetElementPtrInst>, int64_t>>
6906 &LargeOffsetGEPs = Entry.second;
6907 auto compareGEPOffset =
6908 [&](const std::pair<GetElementPtrInst *, int64_t> &LHS,
6909 const std::pair<GetElementPtrInst *, int64_t> &RHS) {
6910 if (LHS.first == RHS.first)
6911 return false;
6912 if (LHS.second != RHS.second)
6913 return LHS.second < RHS.second;
6914 return LargeOffsetGEPID[LHS.first] < LargeOffsetGEPID[RHS.first];
6915 };
6916 // Sorting all the GEPs of the same data structures based on the offsets.
6917 llvm::sort(LargeOffsetGEPs, compareGEPOffset);
6918 LargeOffsetGEPs.erase(llvm::unique(LargeOffsetGEPs), LargeOffsetGEPs.end());
6919 // Skip if all the GEPs have the same offsets.
6920 if (LargeOffsetGEPs.front().second == LargeOffsetGEPs.back().second)
6921 continue;
6922 GetElementPtrInst *BaseGEP = LargeOffsetGEPs.begin()->first;
6923 int64_t BaseOffset = LargeOffsetGEPs.begin()->second;
6924 Value *NewBaseGEP = nullptr;
6925
6926 auto createNewBase = [&](int64_t BaseOffset, Value *OldBase,
6927 GetElementPtrInst *GEP) {
6928 LLVMContext &Ctx = GEP->getContext();
6929 Type *PtrIdxTy = DL->getIndexType(GEP->getType());
6930 Type *I8PtrTy =
6931 PointerType::get(Ctx, GEP->getType()->getPointerAddressSpace());
6932
6933 BasicBlock::iterator NewBaseInsertPt;
6934 BasicBlock *NewBaseInsertBB;
6935 if (auto *BaseI = dyn_cast<Instruction>(OldBase)) {
6936 // If the base of the struct is an instruction, the new base will be
6937 // inserted close to it.
6938 NewBaseInsertBB = BaseI->getParent();
6939 if (isa<PHINode>(BaseI))
6940 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
6941 else if (InvokeInst *Invoke = dyn_cast<InvokeInst>(BaseI)) {
6942 NewBaseInsertBB =
6943 SplitEdge(NewBaseInsertBB, Invoke->getNormalDest(), &getDT(), LI);
6944 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
6945 } else
6946 NewBaseInsertPt = std::next(BaseI->getIterator());
6947 } else {
6948 // If the current base is an argument or global value, the new base
6949 // will be inserted to the entry block.
6950 NewBaseInsertBB = &BaseGEP->getFunction()->getEntryBlock();
6951 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
6952 }
6953 IRBuilder<> NewBaseBuilder(NewBaseInsertBB, NewBaseInsertPt);
6954 // Create a new base.
6955 // TODO: Avoid implicit trunc?
6956 // See https://github.com/llvm/llvm-project/issues/112510.
6957 Value *BaseIndex =
6958 ConstantInt::getSigned(PtrIdxTy, BaseOffset, /*ImplicitTrunc=*/true);
6959 NewBaseGEP = OldBase;
6960 if (NewBaseGEP->getType() != I8PtrTy)
6961 NewBaseGEP = NewBaseBuilder.CreatePointerCast(NewBaseGEP, I8PtrTy);
6962 NewBaseGEP =
6963 NewBaseBuilder.CreatePtrAdd(NewBaseGEP, BaseIndex, "splitgep");
6964 NewGEPBases.insert(NewBaseGEP);
6965 return;
6966 };
6967
6968 // Check whether all the offsets can be encoded with prefered common base.
6969 if (int64_t PreferBase = TLI->getPreferredLargeGEPBaseOffset(
6970 LargeOffsetGEPs.front().second, LargeOffsetGEPs.back().second)) {
6971 BaseOffset = PreferBase;
6972 // Create a new base if the offset of the BaseGEP can be decoded with one
6973 // instruction.
6974 createNewBase(BaseOffset, OldBase, BaseGEP);
6975 }
6976
6977 auto *LargeOffsetGEP = LargeOffsetGEPs.begin();
6978 while (LargeOffsetGEP != LargeOffsetGEPs.end()) {
6979 GetElementPtrInst *GEP = LargeOffsetGEP->first;
6980 int64_t Offset = LargeOffsetGEP->second;
6981 if (Offset != BaseOffset) {
6982 TargetLowering::AddrMode AddrMode;
6983 AddrMode.HasBaseReg = true;
6984 AddrMode.BaseOffs = Offset - BaseOffset;
6985 // The result type of the GEP might not be the type of the memory
6986 // access.
6987 if (!TLI->isLegalAddressingMode(*DL, AddrMode,
6988 GEP->getResultElementType(),
6989 GEP->getAddressSpace())) {
6990 // We need to create a new base if the offset to the current base is
6991 // too large to fit into the addressing mode. So, a very large struct
6992 // may be split into several parts.
6993 BaseGEP = GEP;
6994 BaseOffset = Offset;
6995 NewBaseGEP = nullptr;
6996 }
6997 }
6998
6999 // Generate a new GEP to replace the current one.
7000 Type *PtrIdxTy = DL->getIndexType(GEP->getType());
7001
7002 if (!NewBaseGEP) {
7003 // Create a new base if we don't have one yet. Find the insertion
7004 // pointer for the new base first.
7005 createNewBase(BaseOffset, OldBase, GEP);
7006 }
7007
7008 IRBuilder<> Builder(GEP);
7009 Value *NewGEP = NewBaseGEP;
7010 if (Offset != BaseOffset) {
7011 // Calculate the new offset for the new GEP.
7012 Value *Index = ConstantInt::get(PtrIdxTy, Offset - BaseOffset);
7013 NewGEP = Builder.CreatePtrAdd(NewBaseGEP, Index);
7014 }
7015 replaceAllUsesWith(GEP, NewGEP, FreshBBs, IsHugeFunc);
7016 LargeOffsetGEPID.erase(GEP);
7017 LargeOffsetGEP = LargeOffsetGEPs.erase(LargeOffsetGEP);
7018 GEP->eraseFromParent();
7019 Changed = true;
7020 }
7021 }
7022 return Changed;
7023}
7024
7025bool CodeGenPrepare::optimizePhiType(
7026 PHINode *I, SmallPtrSetImpl<PHINode *> &Visited,
7027 SmallPtrSetImpl<Instruction *> &DeletedInstrs) {
7028 // We are looking for a collection on interconnected phi nodes that together
7029 // only use loads/bitcasts and are used by stores/bitcasts, and the bitcasts
7030 // are of the same type. Convert the whole set of nodes to the type of the
7031 // bitcast.
7032 Type *PhiTy = I->getType();
7033 Type *ConvertTy = nullptr;
7034 if (Visited.count(I) ||
7035 (!I->getType()->isIntegerTy() && !I->getType()->isFloatingPointTy()))
7036 return false;
7037
7038 SmallVector<Instruction *, 4> Worklist;
7039 Worklist.push_back(cast<Instruction>(I));
7040 SmallPtrSet<PHINode *, 4> PhiNodes;
7041 SmallPtrSet<ConstantData *, 4> Constants;
7042 PhiNodes.insert(I);
7043 Visited.insert(I);
7044 SmallPtrSet<Instruction *, 4> Defs;
7045 SmallPtrSet<Instruction *, 4> Uses;
7046 // This works by adding extra bitcasts between load/stores and removing
7047 // existing bitcasts. If we have a phi(bitcast(load)) or a store(bitcast(phi))
7048 // we can get in the situation where we remove a bitcast in one iteration
7049 // just to add it again in the next. We need to ensure that at least one
7050 // bitcast we remove are anchored to something that will not change back.
7051 bool AnyAnchored = false;
7052
7053 while (!Worklist.empty()) {
7054 Instruction *II = Worklist.pop_back_val();
7055
7056 if (auto *Phi = dyn_cast<PHINode>(II)) {
7057 // Handle Defs, which might also be PHI's
7058 for (Value *V : Phi->incoming_values()) {
7059 if (auto *OpPhi = dyn_cast<PHINode>(V)) {
7060 if (!PhiNodes.count(OpPhi)) {
7061 if (!Visited.insert(OpPhi).second)
7062 return false;
7063 PhiNodes.insert(OpPhi);
7064 Worklist.push_back(OpPhi);
7065 }
7066 } else if (auto *OpLoad = dyn_cast<LoadInst>(V)) {
7067 if (!OpLoad->isSimple())
7068 return false;
7069 if (Defs.insert(OpLoad).second)
7070 Worklist.push_back(OpLoad);
7071 } else if (auto *OpEx = dyn_cast<ExtractElementInst>(V)) {
7072 if (Defs.insert(OpEx).second)
7073 Worklist.push_back(OpEx);
7074 } else if (auto *OpBC = dyn_cast<BitCastInst>(V)) {
7075 if (!ConvertTy)
7076 ConvertTy = OpBC->getOperand(0)->getType();
7077 if (OpBC->getOperand(0)->getType() != ConvertTy)
7078 return false;
7079 if (Defs.insert(OpBC).second) {
7080 Worklist.push_back(OpBC);
7081 AnyAnchored |= !isa<LoadInst>(OpBC->getOperand(0)) &&
7082 !isa<ExtractElementInst>(OpBC->getOperand(0));
7083 }
7084 } else if (auto *OpC = dyn_cast<ConstantData>(V))
7085 Constants.insert(OpC);
7086 else
7087 return false;
7088 }
7089 }
7090
7091 // Handle uses which might also be phi's
7092 for (User *V : II->users()) {
7093 if (auto *OpPhi = dyn_cast<PHINode>(V)) {
7094 if (!PhiNodes.count(OpPhi)) {
7095 if (Visited.count(OpPhi))
7096 return false;
7097 PhiNodes.insert(OpPhi);
7098 Visited.insert(OpPhi);
7099 Worklist.push_back(OpPhi);
7100 }
7101 } else if (auto *OpStore = dyn_cast<StoreInst>(V)) {
7102 if (!OpStore->isSimple() || OpStore->getOperand(0) != II)
7103 return false;
7104 Uses.insert(OpStore);
7105 } else if (auto *OpBC = dyn_cast<BitCastInst>(V)) {
7106 if (!ConvertTy)
7107 ConvertTy = OpBC->getType();
7108 if (OpBC->getType() != ConvertTy)
7109 return false;
7110 Uses.insert(OpBC);
7111 AnyAnchored |=
7112 any_of(OpBC->users(), [](User *U) { return !isa<StoreInst>(U); });
7113 } else {
7114 return false;
7115 }
7116 }
7117 }
7118
7119 if (!ConvertTy || !AnyAnchored || PhiTy == ConvertTy ||
7120 !TLI->shouldConvertPhiType(PhiTy, ConvertTy))
7121 return false;
7122
7123 LLVM_DEBUG(dbgs() << "Converting " << *I << "\n and connected nodes to "
7124 << *ConvertTy << "\n");
7125
7126 // Create all the new phi nodes of the new type, and bitcast any loads to the
7127 // correct type.
7128 ValueToValueMap ValMap;
7129 for (ConstantData *C : Constants)
7130 ValMap[C] = ConstantExpr::getBitCast(C, ConvertTy);
7131 for (Instruction *D : Defs) {
7132 if (isa<BitCastInst>(D)) {
7133 ValMap[D] = D->getOperand(0);
7134 DeletedInstrs.insert(D);
7135 } else {
7136 BasicBlock::iterator insertPt = std::next(D->getIterator());
7137 ValMap[D] = new BitCastInst(D, ConvertTy, D->getName() + ".bc", insertPt);
7138 }
7139 }
7140 for (PHINode *Phi : PhiNodes)
7141 ValMap[Phi] = PHINode::Create(ConvertTy, Phi->getNumIncomingValues(),
7142 Phi->getName() + ".tc", Phi->getIterator());
7143 // Pipe together all the PhiNodes.
7144 for (PHINode *Phi : PhiNodes) {
7145 PHINode *NewPhi = cast<PHINode>(ValMap[Phi]);
7146 for (int i = 0, e = Phi->getNumIncomingValues(); i < e; i++)
7147 NewPhi->addIncoming(ValMap[Phi->getIncomingValue(i)],
7148 Phi->getIncomingBlock(i));
7149 Visited.insert(NewPhi);
7150 }
7151 // And finally pipe up the stores and bitcasts
7152 for (Instruction *U : Uses) {
7153 if (isa<BitCastInst>(U)) {
7154 DeletedInstrs.insert(U);
7155 replaceAllUsesWith(U, ValMap[U->getOperand(0)], FreshBBs, IsHugeFunc);
7156 } else {
7157 U->setOperand(0, new BitCastInst(ValMap[U->getOperand(0)], PhiTy, "bc",
7158 U->getIterator()));
7159 }
7160 }
7161
7162 // Save the removed phis to be deleted later.
7163 DeletedInstrs.insert_range(PhiNodes);
7164 return true;
7165}
7166
7167bool CodeGenPrepare::optimizePhiTypes(Function &F) {
7168 if (!OptimizePhiTypes)
7169 return false;
7170
7171 bool Changed = false;
7172 SmallPtrSet<PHINode *, 4> Visited;
7173 SmallPtrSet<Instruction *, 4> DeletedInstrs;
7174
7175 // Attempt to optimize all the phis in the functions to the correct type.
7176 for (auto &BB : F)
7177 for (auto &Phi : BB.phis())
7178 Changed |= optimizePhiType(&Phi, Visited, DeletedInstrs);
7179
7180 // Remove any old phi's that have been converted.
7181 for (auto *I : DeletedInstrs) {
7182 replaceAllUsesWith(I, PoisonValue::get(I->getType()), FreshBBs, IsHugeFunc);
7183 I->eraseFromParent();
7184 }
7185
7186 return Changed;
7187}
7188
7189/// Return true, if an ext(load) can be formed from an extension in
7190/// \p MovedExts.
7191bool CodeGenPrepare::canFormExtLd(
7192 const SmallVectorImpl<Instruction *> &MovedExts, LoadInst *&LI,
7193 Instruction *&Inst, bool HasPromoted) {
7194 for (auto *MovedExtInst : MovedExts) {
7195 if (isa<LoadInst>(MovedExtInst->getOperand(0))) {
7196 LI = cast<LoadInst>(MovedExtInst->getOperand(0));
7197 Inst = MovedExtInst;
7198 break;
7199 }
7200 }
7201 if (!LI)
7202 return false;
7203
7204 // If they're already in the same block, there's nothing to do.
7205 // Make the cheap checks first if we did not promote.
7206 // If we promoted, we need to check if it is indeed profitable.
7207 if (!HasPromoted && LI->getParent() == Inst->getParent())
7208 return false;
7209
7210 return TLI->isExtLoad(LI, Inst, *DL);
7211}
7212
7213/// Move a zext or sext fed by a load into the same basic block as the load,
7214/// unless conditions are unfavorable. This allows SelectionDAG to fold the
7215/// extend into the load.
7216///
7217/// E.g.,
7218/// \code
7219/// %ld = load i32* %addr
7220/// %add = add nuw i32 %ld, 4
7221/// %zext = zext i32 %add to i64
7222// \endcode
7223/// =>
7224/// \code
7225/// %ld = load i32* %addr
7226/// %zext = zext i32 %ld to i64
7227/// %add = add nuw i64 %zext, 4
7228/// \encode
7229/// Note that the promotion in %add to i64 is done in tryToPromoteExts(), which
7230/// allow us to match zext(load i32*) to i64.
7231///
7232/// Also, try to promote the computations used to obtain a sign extended
7233/// value used into memory accesses.
7234/// E.g.,
7235/// \code
7236/// a = add nsw i32 b, 3
7237/// d = sext i32 a to i64
7238/// e = getelementptr ..., i64 d
7239/// \endcode
7240/// =>
7241/// \code
7242/// f = sext i32 b to i64
7243/// a = add nsw i64 f, 3
7244/// e = getelementptr ..., i64 a
7245/// \endcode
7246///
7247/// \p Inst[in/out] the extension may be modified during the process if some
7248/// promotions apply.
7249bool CodeGenPrepare::optimizeExt(Instruction *&Inst) {
7250 bool AllowPromotionWithoutCommonHeader = false;
7251 /// See if it is an interesting sext operations for the address type
7252 /// promotion before trying to promote it, e.g., the ones with the right
7253 /// type and used in memory accesses.
7254 bool ATPConsiderable = TTI->shouldConsiderAddressTypePromotion(
7255 *Inst, AllowPromotionWithoutCommonHeader);
7256 TypePromotionTransaction TPT(RemovedInsts);
7257 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
7258 TPT.getRestorationPoint();
7260 SmallVector<Instruction *, 2> SpeculativelyMovedExts;
7261 Exts.push_back(Inst);
7262
7263 bool HasPromoted = tryToPromoteExts(TPT, Exts, SpeculativelyMovedExts);
7264
7265 // Look for a load being extended.
7266 LoadInst *LI = nullptr;
7267 Instruction *ExtFedByLoad;
7268
7269 // Try to promote a chain of computation if it allows to form an extended
7270 // load.
7271 if (canFormExtLd(SpeculativelyMovedExts, LI, ExtFedByLoad, HasPromoted)) {
7272 assert(LI && ExtFedByLoad && "Expect a valid load and extension");
7273 TPT.commit();
7274 // Move the extend into the same block as the load.
7275 ExtFedByLoad->moveAfter(LI);
7276 ++NumExtsMoved;
7277 Inst = ExtFedByLoad;
7278 return true;
7279 }
7280
7281 // Continue promoting SExts if known as considerable depending on targets.
7282 if (ATPConsiderable &&
7283 performAddressTypePromotion(Inst, AllowPromotionWithoutCommonHeader,
7284 HasPromoted, TPT, SpeculativelyMovedExts))
7285 return true;
7286
7287 TPT.rollback(LastKnownGood);
7288 return false;
7289}
7290
7291// Perform address type promotion if doing so is profitable.
7292// If AllowPromotionWithoutCommonHeader == false, we should find other sext
7293// instructions that sign extended the same initial value. However, if
7294// AllowPromotionWithoutCommonHeader == true, we expect promoting the
7295// extension is just profitable.
7296bool CodeGenPrepare::performAddressTypePromotion(
7297 Instruction *&Inst, bool AllowPromotionWithoutCommonHeader,
7298 bool HasPromoted, TypePromotionTransaction &TPT,
7299 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts) {
7300 bool Promoted = false;
7301 SmallPtrSet<Instruction *, 1> UnhandledExts;
7302 bool AllSeenFirst = true;
7303 for (auto *I : SpeculativelyMovedExts) {
7304 Value *HeadOfChain = I->getOperand(0);
7305 auto AlreadySeen = SeenChainsForSExt.find(HeadOfChain);
7306 // If there is an unhandled SExt which has the same header, try to promote
7307 // it as well.
7308 if (AlreadySeen != SeenChainsForSExt.end()) {
7309 if (AlreadySeen->second != nullptr)
7310 UnhandledExts.insert(AlreadySeen->second);
7311 AllSeenFirst = false;
7312 }
7313 }
7314
7315 if (!AllSeenFirst || (AllowPromotionWithoutCommonHeader &&
7316 SpeculativelyMovedExts.size() == 1)) {
7317 TPT.commit();
7318 if (HasPromoted)
7319 Promoted = true;
7320 for (auto *I : SpeculativelyMovedExts) {
7321 Value *HeadOfChain = I->getOperand(0);
7322 SeenChainsForSExt[HeadOfChain] = nullptr;
7323 ValToSExtendedUses[HeadOfChain].push_back(I);
7324 }
7325 // Update Inst as promotion happen.
7326 Inst = SpeculativelyMovedExts.pop_back_val();
7327 } else {
7328 // This is the first chain visited from the header, keep the current chain
7329 // as unhandled. Defer to promote this until we encounter another SExt
7330 // chain derived from the same header.
7331 for (auto *I : SpeculativelyMovedExts) {
7332 Value *HeadOfChain = I->getOperand(0);
7333 SeenChainsForSExt[HeadOfChain] = Inst;
7334 }
7335 return false;
7336 }
7337
7338 if (!AllSeenFirst && !UnhandledExts.empty())
7339 for (auto *VisitedSExt : UnhandledExts) {
7340 if (RemovedInsts.count(VisitedSExt))
7341 continue;
7342 TypePromotionTransaction TPT(RemovedInsts);
7344 SmallVector<Instruction *, 2> Chains;
7345 Exts.push_back(VisitedSExt);
7346 bool HasPromoted = tryToPromoteExts(TPT, Exts, Chains);
7347 TPT.commit();
7348 if (HasPromoted)
7349 Promoted = true;
7350 for (auto *I : Chains) {
7351 Value *HeadOfChain = I->getOperand(0);
7352 // Mark this as handled.
7353 SeenChainsForSExt[HeadOfChain] = nullptr;
7354 ValToSExtendedUses[HeadOfChain].push_back(I);
7355 }
7356 }
7357 return Promoted;
7358}
7359
7360bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
7361 BasicBlock *DefBB = I->getParent();
7362
7363 // If the result of a {s|z}ext and its source are both live out, rewrite all
7364 // other uses of the source with result of extension.
7365 Value *Src = I->getOperand(0);
7366 if (Src->hasOneUse())
7367 return false;
7368
7369 // Only do this xform if truncating is free.
7370 if (!TLI->isTruncateFree(I->getType(), Src->getType()))
7371 return false;
7372
7373 // Only safe to perform the optimization if the source is also defined in
7374 // this block.
7375 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
7376 return false;
7377
7378 bool DefIsLiveOut = false;
7379 for (User *U : I->users()) {
7381
7382 // Figure out which BB this ext is used in.
7383 BasicBlock *UserBB = UI->getParent();
7384 if (UserBB == DefBB)
7385 continue;
7386 DefIsLiveOut = true;
7387 break;
7388 }
7389 if (!DefIsLiveOut)
7390 return false;
7391
7392 // Make sure none of the uses are PHI nodes.
7393 for (User *U : Src->users()) {
7395 BasicBlock *UserBB = UI->getParent();
7396 if (UserBB == DefBB)
7397 continue;
7398 // Be conservative. We don't want this xform to end up introducing
7399 // reloads just before load / store instructions.
7400 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
7401 return false;
7402 }
7403
7404 // InsertedTruncs - Only insert one trunc in each block once.
7405 DenseMap<BasicBlock *, Instruction *> InsertedTruncs;
7406
7407 bool MadeChange = false;
7408 for (Use &U : make_early_inc_range(Src->uses())) {
7409 Instruction *User = cast<Instruction>(U.getUser());
7410
7411 // Figure out which BB this ext is used in.
7412 BasicBlock *UserBB = User->getParent();
7413 if (UserBB == DefBB)
7414 continue;
7415
7416 // Both src and def are live in this block. Rewrite the use.
7417 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
7418
7419 if (!InsertedTrunc) {
7420 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
7421 assert(InsertPt != UserBB->end());
7422 InsertedTrunc = new TruncInst(I, Src->getType(), "");
7423 InsertedTrunc->insertBefore(*UserBB, InsertPt);
7424 InsertedInsts.insert(InsertedTrunc);
7425 }
7426
7427 // Replace a use of the {s|z}ext source with a use of the result.
7428 U = InsertedTrunc;
7429 ++NumExtUses;
7430 MadeChange = true;
7431 }
7432
7433 return MadeChange;
7434}
7435
7436// Find loads whose uses only use some of the loaded value's bits. Add an "and"
7437// just after the load if the target can fold this into one extload instruction,
7438// with the hope of eliminating some of the other later "and" instructions using
7439// the loaded value. "and"s that are made trivially redundant by the insertion
7440// of the new "and" are removed by this function, while others (e.g. those whose
7441// path from the load goes through a phi) are left for isel to potentially
7442// remove.
7443//
7444// For example:
7445//
7446// b0:
7447// x = load i32
7448// ...
7449// b1:
7450// y = and x, 0xff
7451// z = use y
7452//
7453// becomes:
7454//
7455// b0:
7456// x = load i32
7457// x' = and x, 0xff
7458// ...
7459// b1:
7460// z = use x'
7461//
7462// whereas:
7463//
7464// b0:
7465// x1 = load i32
7466// ...
7467// b1:
7468// x2 = load i32
7469// ...
7470// b2:
7471// x = phi x1, x2
7472// y = and x, 0xff
7473//
7474// becomes (after a call to optimizeLoadExt for each load):
7475//
7476// b0:
7477// x1 = load i32
7478// x1' = and x1, 0xff
7479// ...
7480// b1:
7481// x2 = load i32
7482// x2' = and x2, 0xff
7483// ...
7484// b2:
7485// x = phi x1', x2'
7486// y = and x, 0xff
7487bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
7488 if (!Load->isSimple() || !Load->getType()->isIntOrPtrTy())
7489 return false;
7490
7491 // Skip loads we've already transformed.
7492 if (Load->hasOneUse() &&
7493 InsertedInsts.count(cast<Instruction>(*Load->user_begin())))
7494 return false;
7495
7496 // Look at all uses of Load, looking through phis, to determine how many bits
7497 // of the loaded value are needed.
7498 SmallVector<Instruction *, 8> WorkList;
7499 SmallPtrSet<Instruction *, 16> Visited;
7500 SmallVector<Instruction *, 8> AndsToMaybeRemove;
7501 SmallVector<Instruction *, 8> DropFlags;
7502 for (auto *U : Load->users())
7503 WorkList.push_back(cast<Instruction>(U));
7504
7505 EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
7506 unsigned BitWidth = LoadResultVT.getSizeInBits();
7507 // If the BitWidth is 0, do not try to optimize the type
7508 if (BitWidth == 0)
7509 return false;
7510
7511 APInt DemandBits(BitWidth, 0);
7512 APInt WidestAndBits(BitWidth, 0);
7513
7514 while (!WorkList.empty()) {
7515 Instruction *I = WorkList.pop_back_val();
7516
7517 // Break use-def graph loops.
7518 if (!Visited.insert(I).second)
7519 continue;
7520
7521 // For a PHI node, push all of its users.
7522 if (auto *Phi = dyn_cast<PHINode>(I)) {
7523 for (auto *U : Phi->users())
7524 WorkList.push_back(cast<Instruction>(U));
7525 continue;
7526 }
7527
7528 switch (I->getOpcode()) {
7529 case Instruction::And: {
7530 auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
7531 if (!AndC)
7532 return false;
7533 APInt AndBits = AndC->getValue();
7534 DemandBits |= AndBits;
7535 // Keep track of the widest and mask we see.
7536 if (AndBits.ugt(WidestAndBits))
7537 WidestAndBits = AndBits;
7538 if (AndBits == WidestAndBits && I->getOperand(0) == Load)
7539 AndsToMaybeRemove.push_back(I);
7540 break;
7541 }
7542
7543 case Instruction::Shl: {
7544 auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
7545 if (!ShlC)
7546 return false;
7547 uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
7548 DemandBits.setLowBits(BitWidth - ShiftAmt);
7549 DropFlags.push_back(I);
7550 break;
7551 }
7552
7553 case Instruction::Trunc: {
7554 EVT TruncVT = TLI->getValueType(*DL, I->getType());
7555 unsigned TruncBitWidth = TruncVT.getSizeInBits();
7556 DemandBits.setLowBits(TruncBitWidth);
7557 DropFlags.push_back(I);
7558 break;
7559 }
7560
7561 default:
7562 return false;
7563 }
7564 }
7565
7566 uint32_t ActiveBits = DemandBits.getActiveBits();
7567 // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
7568 // target even if isLoadLegal says an i1 EXTLOAD is valid. For example,
7569 // for the AArch64 target isLoadLegal(i32, i1, ..., ZEXTLOAD, false) returns
7570 // true, but (and (load x) 1) is not matched as a single instruction, rather
7571 // as a LDR followed by an AND.
7572 // TODO: Look into removing this restriction by fixing backends to either
7573 // return false for isLoadLegal for i1 or have them select this pattern to
7574 // a single instruction.
7575 //
7576 // Also avoid hoisting if we didn't see any ands with the exact DemandBits
7577 // mask, since these are the only ands that will be removed by isel.
7578 if (ActiveBits <= 1 || !DemandBits.isMask(ActiveBits) ||
7579 WidestAndBits != DemandBits)
7580 return false;
7581
7582 LLVMContext &Ctx = Load->getType()->getContext();
7583 Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
7584 EVT TruncVT = TLI->getValueType(*DL, TruncTy);
7585
7586 // Reject cases that won't be matched as extloads.
7587 if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
7588 !TLI->isLoadLegal(LoadResultVT, TruncVT, Load->getAlign(),
7589 Load->getPointerAddressSpace(), ISD::ZEXTLOAD, false))
7590 return false;
7591
7592 IRBuilder<> Builder(Load->getNextNode());
7593 auto *NewAnd = cast<Instruction>(
7594 Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
7595 // Mark this instruction as "inserted by CGP", so that other
7596 // optimizations don't touch it.
7597 InsertedInsts.insert(NewAnd);
7598
7599 // Replace all uses of load with new and (except for the use of load in the
7600 // new and itself).
7601 replaceAllUsesWith(Load, NewAnd, FreshBBs, IsHugeFunc);
7602 NewAnd->setOperand(0, Load);
7603
7604 // Remove any and instructions that are now redundant.
7605 for (auto *And : AndsToMaybeRemove)
7606 // Check that the and mask is the same as the one we decided to put on the
7607 // new and.
7608 if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
7609 replaceAllUsesWith(And, NewAnd, FreshBBs, IsHugeFunc);
7610 if (&*CurInstIterator == And)
7611 CurInstIterator = std::next(And->getIterator());
7612 And->eraseFromParent();
7613 ++NumAndUses;
7614 }
7615
7616 // NSW flags may not longer hold.
7617 for (auto *Inst : DropFlags)
7618 Inst->setHasNoSignedWrap(false);
7619
7620 ++NumAndsAdded;
7621 return true;
7622}
7623
7624/// Check if V (an operand of a select instruction) is an expensive instruction
7625/// that is only used once.
7627 auto *I = dyn_cast<Instruction>(V);
7628 // If it's safe to speculatively execute, then it should not have side
7629 // effects; therefore, it's safe to sink and possibly *not* execute.
7630 return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
7631 TTI->isExpensiveToSpeculativelyExecute(I);
7632}
7633
7634/// Returns true if a SelectInst should be turned into an explicit branch.
7636 const TargetLowering *TLI,
7637 SelectInst *SI) {
7638 // If even a predictable select is cheap, then a branch can't be cheaper.
7639 if (!TLI->isPredictableSelectExpensive())
7640 return false;
7641
7642 // FIXME: This should use the same heuristics as IfConversion to determine
7643 // whether a select is better represented as a branch.
7644
7645 // If metadata tells us that the select condition is obviously predictable,
7646 // then we want to replace the select with a branch.
7647 uint64_t TrueWeight, FalseWeight;
7648 if (extractBranchWeights(*SI, TrueWeight, FalseWeight)) {
7649 uint64_t Max = std::max(TrueWeight, FalseWeight);
7650 uint64_t Sum = TrueWeight + FalseWeight;
7651 if (Sum != 0) {
7652 auto Probability = BranchProbability::getBranchProbability(Max, Sum);
7653 if (Probability > TTI->getPredictableBranchThreshold())
7654 return true;
7655 }
7656 }
7657
7658 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
7659
7660 // If a branch is predictable, an out-of-order CPU can avoid blocking on its
7661 // comparison condition. If the compare has more than one use, there's
7662 // probably another cmov or setcc around, so it's not worth emitting a branch.
7663 if (!Cmp || !Cmp->hasOneUse())
7664 return false;
7665
7666 // If either operand of the select is expensive and only needed on one side
7667 // of the select, we should form a branch.
7668 if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
7669 sinkSelectOperand(TTI, SI->getFalseValue()))
7670 return true;
7671
7672 return false;
7673}
7674
7675/// If \p isTrue is true, return the true value of \p SI, otherwise return
7676/// false value of \p SI. If the true/false value of \p SI is defined by any
7677/// select instructions in \p Selects, look through the defining select
7678/// instruction until the true/false value is not defined in \p Selects.
7679static Value *
7681 const SmallPtrSet<const Instruction *, 2> &Selects) {
7682 Value *V = nullptr;
7683
7684 for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI);
7685 DefSI = dyn_cast<SelectInst>(V)) {
7686 assert(DefSI->getCondition() == SI->getCondition() &&
7687 "The condition of DefSI does not match with SI");
7688 V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
7689 }
7690
7691 assert(V && "Failed to get select true/false value");
7692 return V;
7693}
7694
7695bool CodeGenPrepare::optimizeShiftInst(BinaryOperator *Shift) {
7696 assert(Shift->isShift() && "Expected a shift");
7697
7698 // If this is (1) a vector shift, (2) shifts by scalars are cheaper than
7699 // general vector shifts, and (3) the shift amount is a select-of-splatted
7700 // values, hoist the shifts before the select:
7701 // shift Op0, (select Cond, TVal, FVal) -->
7702 // select Cond, (shift Op0, TVal), (shift Op0, FVal)
7703 //
7704 // This is inverting a generic IR transform when we know that the cost of a
7705 // general vector shift is more than the cost of 2 shift-by-scalars.
7706 // We can't do this effectively in SDAG because we may not be able to
7707 // determine if the select operands are splats from within a basic block.
7708 Type *Ty = Shift->getType();
7709 if (!Ty->isVectorTy() || !TTI->isVectorShiftByScalarCheap(Ty))
7710 return false;
7711 Value *Cond, *TVal, *FVal;
7712 if (!match(Shift->getOperand(1),
7713 m_OneUse(m_Select(m_Value(Cond), m_Value(TVal), m_Value(FVal)))))
7714 return false;
7715 if (!isSplatValue(TVal) || !isSplatValue(FVal))
7716 return false;
7717
7718 IRBuilder<> Builder(Shift);
7719 BinaryOperator::BinaryOps Opcode = Shift->getOpcode();
7720 Value *NewTVal = Builder.CreateBinOp(Opcode, Shift->getOperand(0), TVal);
7721 Value *NewFVal = Builder.CreateBinOp(Opcode, Shift->getOperand(0), FVal);
7722 Value *NewSel = Builder.CreateSelect(Cond, NewTVal, NewFVal);
7723 replaceAllUsesWith(Shift, NewSel, FreshBBs, IsHugeFunc);
7724 Shift->eraseFromParent();
7725 return true;
7726}
7727
7728bool CodeGenPrepare::optimizeFunnelShift(IntrinsicInst *Fsh) {
7729 Intrinsic::ID Opcode = Fsh->getIntrinsicID();
7730 assert((Opcode == Intrinsic::fshl || Opcode == Intrinsic::fshr) &&
7731 "Expected a funnel shift");
7732
7733 // If this is (1) a vector funnel shift, (2) shifts by scalars are cheaper
7734 // than general vector shifts, and (3) the shift amount is select-of-splatted
7735 // values, hoist the funnel shifts before the select:
7736 // fsh Op0, Op1, (select Cond, TVal, FVal) -->
7737 // select Cond, (fsh Op0, Op1, TVal), (fsh Op0, Op1, FVal)
7738 //
7739 // This is inverting a generic IR transform when we know that the cost of a
7740 // general vector shift is more than the cost of 2 shift-by-scalars.
7741 // We can't do this effectively in SDAG because we may not be able to
7742 // determine if the select operands are splats from within a basic block.
7743 Type *Ty = Fsh->getType();
7744 if (!Ty->isVectorTy() || !TTI->isVectorShiftByScalarCheap(Ty))
7745 return false;
7746 Value *Cond, *TVal, *FVal;
7747 if (!match(Fsh->getOperand(2),
7748 m_OneUse(m_Select(m_Value(Cond), m_Value(TVal), m_Value(FVal)))))
7749 return false;
7750 if (!isSplatValue(TVal) || !isSplatValue(FVal))
7751 return false;
7752
7753 IRBuilder<> Builder(Fsh);
7754 Value *X = Fsh->getOperand(0), *Y = Fsh->getOperand(1);
7755 Value *NewTVal = Builder.CreateIntrinsic(Opcode, Ty, {X, Y, TVal});
7756 Value *NewFVal = Builder.CreateIntrinsic(Opcode, Ty, {X, Y, FVal});
7757 Value *NewSel = Builder.CreateSelect(Cond, NewTVal, NewFVal);
7758 replaceAllUsesWith(Fsh, NewSel, FreshBBs, IsHugeFunc);
7759 Fsh->eraseFromParent();
7760 return true;
7761}
7762
7763/// If we have a SelectInst that will likely profit from branch prediction,
7764/// turn it into a branch.
7765bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
7767 return false;
7768
7769 // If the SelectOptimize pass is enabled, selects have already been optimized.
7771 return false;
7772
7773 // Find all consecutive select instructions that share the same condition.
7775 ASI.push_back(SI);
7777 It != SI->getParent()->end(); ++It) {
7778 SelectInst *I = dyn_cast<SelectInst>(&*It);
7779 if (I && SI->getCondition() == I->getCondition()) {
7780 ASI.push_back(I);
7781 } else {
7782 break;
7783 }
7784 }
7785
7786 SelectInst *LastSI = ASI.back();
7787 // Increment the current iterator to skip all the rest of select instructions
7788 // because they will be either "not lowered" or "all lowered" to branch.
7789 CurInstIterator = std::next(LastSI->getIterator());
7790 // Examine debug-info attached to the consecutive select instructions. They
7791 // won't be individually optimised by optimizeInst, so we need to perform
7792 // DbgVariableRecord maintenence here instead.
7793 for (SelectInst *SI : ArrayRef(ASI).drop_front())
7794 fixupDbgVariableRecordsOnInst(*SI);
7795
7796 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
7797
7798 // Can we convert the 'select' to CF ?
7799 if (VectorCond || SI->getMetadata(LLVMContext::MD_unpredictable))
7800 return false;
7801
7802 TargetLowering::SelectSupportKind SelectKind;
7803 if (SI->getType()->isVectorTy())
7804 SelectKind = TargetLowering::ScalarCondVectorVal;
7805 else
7806 SelectKind = TargetLowering::ScalarValSelect;
7807
7808 if (TLI->isSelectSupported(SelectKind) &&
7810 llvm::shouldOptimizeForSize(SI->getParent(), PSI, BFI)))
7811 return false;
7812
7813 // Transform a sequence like this:
7814 // start:
7815 // %cmp = cmp uge i32 %a, %b
7816 // %sel = select i1 %cmp, i32 %c, i32 %d
7817 //
7818 // Into:
7819 // start:
7820 // %cmp = cmp uge i32 %a, %b
7821 // %cmp.frozen = freeze %cmp
7822 // br i1 %cmp.frozen, label %select.true, label %select.false
7823 // select.true:
7824 // br label %select.end
7825 // select.false:
7826 // br label %select.end
7827 // select.end:
7828 // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
7829 //
7830 // %cmp should be frozen, otherwise it may introduce undefined behavior.
7831 // In addition, we may sink instructions that produce %c or %d from
7832 // the entry block into the destination(s) of the new branch.
7833 // If the true or false blocks do not contain a sunken instruction, that
7834 // block and its branch may be optimized away. In that case, one side of the
7835 // first branch will point directly to select.end, and the corresponding PHI
7836 // predecessor block will be the start block.
7837 // The CFG is altered here and we update the DominatorTree and the LoopInfo,
7838 // but we don't set a ModifiedDT flag to avoid restarting the function walk in
7839 // runOnFunction for each select optimized.
7840
7841 // Collect values that go on the true side and the values that go on the false
7842 // side.
7843 SmallVector<Instruction *> TrueInstrs, FalseInstrs;
7844 for (SelectInst *SI : ASI) {
7845 if (Value *V = SI->getTrueValue(); sinkSelectOperand(TTI, V))
7846 TrueInstrs.push_back(cast<Instruction>(V));
7847 if (Value *V = SI->getFalseValue(); sinkSelectOperand(TTI, V))
7848 FalseInstrs.push_back(cast<Instruction>(V));
7849 }
7850
7851 // Split the select block, according to how many (if any) values go on each
7852 // side.
7853 BasicBlock *StartBlock = SI->getParent();
7854 BasicBlock::iterator SplitPt = std::next(BasicBlock::iterator(LastSI));
7855 // We should split before any debug-info.
7856 SplitPt.setHeadBit(true);
7857
7858 IRBuilder<> IB(SI);
7859 auto *CondFr = IB.CreateFreeze(SI->getCondition(), SI->getName() + ".frozen");
7860
7861 BasicBlock *TrueBlock = nullptr;
7862 BasicBlock *FalseBlock = nullptr;
7863 BasicBlock *EndBlock = nullptr;
7864 UncondBrInst *TrueBranch = nullptr;
7865 UncondBrInst *FalseBranch = nullptr;
7866 if (TrueInstrs.size() == 0) {
7867 FalseBranch = cast<UncondBrInst>(
7868 SplitBlockAndInsertIfElse(CondFr, SplitPt, false, nullptr, DTU, LI));
7869 FalseBlock = FalseBranch->getParent();
7870 EndBlock = cast<BasicBlock>(FalseBranch->getOperand(0));
7871 } else if (FalseInstrs.size() == 0) {
7872 TrueBranch = cast<UncondBrInst>(
7873 SplitBlockAndInsertIfThen(CondFr, SplitPt, false, nullptr, DTU, LI));
7874 TrueBlock = TrueBranch->getParent();
7875 EndBlock = TrueBranch->getSuccessor();
7876 } else {
7877 Instruction *ThenTerm = nullptr;
7878 Instruction *ElseTerm = nullptr;
7879 SplitBlockAndInsertIfThenElse(CondFr, SplitPt, &ThenTerm, &ElseTerm,
7880 nullptr, DTU, LI);
7881 TrueBranch = cast<UncondBrInst>(ThenTerm);
7882 FalseBranch = cast<UncondBrInst>(ElseTerm);
7883 TrueBlock = TrueBranch->getParent();
7884 FalseBlock = FalseBranch->getParent();
7885 EndBlock = TrueBranch->getSuccessor();
7886 }
7887
7888 EndBlock->setName("select.end");
7889 if (TrueBlock)
7890 TrueBlock->setName("select.true.sink");
7891 if (FalseBlock)
7892 FalseBlock->setName(FalseInstrs.size() == 0 ? "select.false"
7893 : "select.false.sink");
7894
7895 if (IsHugeFunc) {
7896 if (TrueBlock)
7897 FreshBBs.insert(TrueBlock);
7898 if (FalseBlock)
7899 FreshBBs.insert(FalseBlock);
7900 FreshBBs.insert(EndBlock);
7901 }
7902
7903 BFI->setBlockFreq(EndBlock, BFI->getBlockFreq(StartBlock));
7904
7905 static const unsigned MD[] = {
7906 LLVMContext::MD_prof, LLVMContext::MD_unpredictable,
7907 LLVMContext::MD_make_implicit, LLVMContext::MD_dbg};
7908 StartBlock->getTerminator()->copyMetadata(*SI, MD);
7909
7910 // Sink expensive instructions into the conditional blocks to avoid executing
7911 // them speculatively.
7912 for (Instruction *I : TrueInstrs)
7913 I->moveBefore(TrueBranch->getIterator());
7914 for (Instruction *I : FalseInstrs)
7915 I->moveBefore(FalseBranch->getIterator());
7916
7917 // If we did not create a new block for one of the 'true' or 'false' paths
7918 // of the condition, it means that side of the branch goes to the end block
7919 // directly and the path originates from the start block from the point of
7920 // view of the new PHI.
7921 if (TrueBlock == nullptr)
7922 TrueBlock = StartBlock;
7923 else if (FalseBlock == nullptr)
7924 FalseBlock = StartBlock;
7925
7926 SmallPtrSet<const Instruction *, 2> INS(llvm::from_range, ASI);
7927 // Use reverse iterator because later select may use the value of the
7928 // earlier select, and we need to propagate value through earlier select
7929 // to get the PHI operand.
7930 for (SelectInst *SI : llvm::reverse(ASI)) {
7931 // The select itself is replaced with a PHI Node.
7932 PHINode *PN = PHINode::Create(SI->getType(), 2, "");
7933 PN->insertBefore(EndBlock->begin());
7934 PN->takeName(SI);
7935 PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock);
7936 PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock);
7937 PN->setDebugLoc(SI->getDebugLoc());
7938
7939 replaceAllUsesWith(SI, PN, FreshBBs, IsHugeFunc);
7940 SI->eraseFromParent();
7941 INS.erase(SI);
7942 ++NumSelectsExpanded;
7943 }
7944
7945 // Instruct OptimizeBlock to skip to the next block.
7946 CurInstIterator = StartBlock->end();
7947 return true;
7948}
7949
7950/// Some targets only accept certain types for splat inputs. For example a VDUP
7951/// in MVE takes a GPR (integer) register, and the instruction that incorporate
7952/// a VDUP (such as a VADD qd, qm, rm) also require a gpr register.
7953bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
7954 // Accept shuf(insertelem(undef/poison, val, 0), undef/poison, <0,0,..>) only
7956 m_Undef(), m_ZeroMask())))
7957 return false;
7958 Type *NewType = TLI->shouldConvertSplatType(SVI);
7959 if (!NewType)
7960 return false;
7961
7962 auto *SVIVecType = cast<FixedVectorType>(SVI->getType());
7963 assert(!NewType->isVectorTy() && "Expected a scalar type!");
7964 assert(NewType->getScalarSizeInBits() == SVIVecType->getScalarSizeInBits() &&
7965 "Expected a type of the same size!");
7966 auto *NewVecType =
7967 FixedVectorType::get(NewType, SVIVecType->getNumElements());
7968
7969 // Create a bitcast (shuffle (insert (bitcast(..))))
7970 IRBuilder<> Builder(SVI->getContext());
7971 Builder.SetInsertPoint(SVI);
7972 Value *BC1 = Builder.CreateBitCast(
7973 cast<Instruction>(SVI->getOperand(0))->getOperand(1), NewType);
7974 Value *Shuffle = Builder.CreateVectorSplat(NewVecType->getNumElements(), BC1);
7975 Value *BC2 = Builder.CreateBitCast(Shuffle, SVIVecType);
7976
7977 replaceAllUsesWith(SVI, BC2, FreshBBs, IsHugeFunc);
7979 SVI, TLInfo, nullptr,
7980 [&](Value *V) { removeAllAssertingVHReferences(V); });
7981
7982 // Also hoist the bitcast up to its operand if it they are not in the same
7983 // block.
7984 if (auto *BCI = dyn_cast<Instruction>(BC1))
7985 if (auto *Op = dyn_cast<Instruction>(BCI->getOperand(0)))
7986 if (BCI->getParent() != Op->getParent() && !isa<PHINode>(Op) &&
7987 !Op->isTerminator() && !Op->isEHPad())
7988 BCI->moveAfter(Op);
7989
7990 return true;
7991}
7992
7993bool CodeGenPrepare::tryToSinkFreeOperands(Instruction *I) {
7994 // If the operands of I can be folded into a target instruction together with
7995 // I, duplicate and sink them.
7996 SmallVector<Use *, 4> OpsToSink;
7997 if (!TTI->isProfitableToSinkOperands(I, OpsToSink))
7998 return false;
7999
8000 // OpsToSink can contain multiple uses in a use chain (e.g.
8001 // (%u1 with %u1 = shufflevector), (%u2 with %u2 = zext %u1)). The dominating
8002 // uses must come first, so we process the ops in reverse order so as to not
8003 // create invalid IR.
8004 BasicBlock *TargetBB = I->getParent();
8005 bool Changed = false;
8006 SmallVector<Use *, 4> ToReplace;
8007 Instruction *InsertPoint = I;
8008 for (Use *U : reverse(OpsToSink)) {
8009 auto *UI = cast<Instruction>(U->get());
8010 if (isa<PHINode>(UI) || UI->mayHaveSideEffects() || UI->mayReadFromMemory())
8011 continue;
8012 if (UI->getParent() == TargetBB) {
8013 if (UI->comesBefore(InsertPoint))
8014 InsertPoint = UI;
8015 continue;
8016 }
8017 ToReplace.push_back(U);
8018 }
8019
8020 SetVector<Instruction *> MaybeDead;
8021 DenseMap<Instruction *, Instruction *> NewInstructions;
8022 for (Use *U : ToReplace) {
8023 auto *UI = cast<Instruction>(U->get());
8024 Instruction *NI = UI->clone();
8025
8026 if (IsHugeFunc) {
8027 // Now we clone an instruction, its operands' defs may sink to this BB
8028 // now. So we put the operands defs' BBs into FreshBBs to do optimization.
8029 for (Value *Op : NI->operands())
8030 if (auto *OpDef = dyn_cast<Instruction>(Op))
8031 FreshBBs.insert(OpDef->getParent());
8032 }
8033
8034 NewInstructions[UI] = NI;
8035 MaybeDead.insert(UI);
8036 LLVM_DEBUG(dbgs() << "Sinking " << *UI << " to user " << *I << "\n");
8037 NI->insertBefore(InsertPoint->getIterator());
8038 InsertPoint = NI;
8039 InsertedInsts.insert(NI);
8040
8041 // Update the use for the new instruction, making sure that we update the
8042 // sunk instruction uses, if it is part of a chain that has already been
8043 // sunk.
8044 Instruction *OldI = cast<Instruction>(U->getUser());
8045 if (auto It = NewInstructions.find(OldI); It != NewInstructions.end())
8046 It->second->setOperand(U->getOperandNo(), NI);
8047 else
8048 U->set(NI);
8049 Changed = true;
8050 }
8051
8052 // Remove instructions that are dead after sinking.
8053 for (auto *I : MaybeDead) {
8054 if (!I->hasNUsesOrMore(1)) {
8055 LLVM_DEBUG(dbgs() << "Removing dead instruction: " << *I << "\n");
8056 I->eraseFromParent();
8057 }
8058 }
8059
8060 return Changed;
8061}
8062
8063bool CodeGenPrepare::optimizeSwitchType(SwitchInst *SI) {
8064 Value *Cond = SI->getCondition();
8065 Type *OldType = Cond->getType();
8066 LLVMContext &Context = Cond->getContext();
8067 EVT OldVT = TLI->getValueType(*DL, OldType);
8069 unsigned RegWidth = RegType.getSizeInBits();
8070
8071 if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
8072 return false;
8073
8074 // If the register width is greater than the type width, expand the condition
8075 // of the switch instruction and each case constant to the width of the
8076 // register. By widening the type of the switch condition, subsequent
8077 // comparisons (for case comparisons) will not need to be extended to the
8078 // preferred register width, so we will potentially eliminate N-1 extends,
8079 // where N is the number of cases in the switch.
8080 auto *NewType = Type::getIntNTy(Context, RegWidth);
8081
8082 // Extend the switch condition and case constants using the target preferred
8083 // extend unless the switch condition is a function argument with an extend
8084 // attribute. In that case, we can avoid an unnecessary mask/extension by
8085 // matching the argument extension instead.
8086 Instruction::CastOps ExtType = Instruction::ZExt;
8087 // Some targets prefer SExt over ZExt.
8088 if (TLI->isSExtCheaperThanZExt(OldVT, RegType))
8089 ExtType = Instruction::SExt;
8090
8091 if (auto *Arg = dyn_cast<Argument>(Cond)) {
8092 if (Arg->hasSExtAttr())
8093 ExtType = Instruction::SExt;
8094 if (Arg->hasZExtAttr())
8095 ExtType = Instruction::ZExt;
8096 }
8097
8098 auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
8099 ExtInst->insertBefore(SI->getIterator());
8100 ExtInst->setDebugLoc(SI->getDebugLoc());
8101 SI->setCondition(ExtInst);
8102 for (auto Case : SI->cases()) {
8103 const APInt &NarrowConst = Case.getCaseValue()->getValue();
8104 APInt WideConst = (ExtType == Instruction::ZExt)
8105 ? NarrowConst.zext(RegWidth)
8106 : NarrowConst.sext(RegWidth);
8107 Case.setValue(ConstantInt::get(Context, WideConst));
8108 }
8109
8110 return true;
8111}
8112
8113bool CodeGenPrepare::optimizeSwitchPhiConstants(SwitchInst *SI) {
8114 // The SCCP optimization tends to produce code like this:
8115 // switch(x) { case 42: phi(42, ...) }
8116 // Materializing the constant for the phi-argument needs instructions; So we
8117 // change the code to:
8118 // switch(x) { case 42: phi(x, ...) }
8119
8120 Value *Condition = SI->getCondition();
8121 // Avoid endless loop in degenerate case.
8122 if (isa<ConstantInt>(*Condition))
8123 return false;
8124
8125 bool Changed = false;
8126 BasicBlock *SwitchBB = SI->getParent();
8127 Type *ConditionType = Condition->getType();
8128
8129 for (const SwitchInst::CaseHandle &Case : SI->cases()) {
8130 ConstantInt *CaseValue = Case.getCaseValue();
8131 BasicBlock *CaseBB = Case.getCaseSuccessor();
8132 // Set to true if we previously checked that `CaseBB` is only reached by
8133 // a single case from this switch.
8134 bool CheckedForSinglePred = false;
8135 for (PHINode &PHI : CaseBB->phis()) {
8136 Type *PHIType = PHI.getType();
8137 // If ZExt is free then we can also catch patterns like this:
8138 // switch((i32)x) { case 42: phi((i64)42, ...); }
8139 // and replace `(i64)42` with `zext i32 %x to i64`.
8140 bool TryZExt =
8141 PHIType->isIntegerTy() &&
8142 PHIType->getIntegerBitWidth() > ConditionType->getIntegerBitWidth() &&
8143 TLI->isZExtFree(ConditionType, PHIType);
8144 if (PHIType == ConditionType || TryZExt) {
8145 // Set to true to skip this case because of multiple preds.
8146 bool SkipCase = false;
8147 Value *Replacement = nullptr;
8148 for (unsigned I = 0, E = PHI.getNumIncomingValues(); I != E; I++) {
8149 Value *PHIValue = PHI.getIncomingValue(I);
8150 if (PHIValue != CaseValue) {
8151 if (!TryZExt)
8152 continue;
8153 ConstantInt *PHIValueInt = dyn_cast<ConstantInt>(PHIValue);
8154 if (!PHIValueInt ||
8155 PHIValueInt->getValue() !=
8156 CaseValue->getValue().zext(PHIType->getIntegerBitWidth()))
8157 continue;
8158 }
8159 if (PHI.getIncomingBlock(I) != SwitchBB)
8160 continue;
8161 // We cannot optimize if there are multiple case labels jumping to
8162 // this block. This check may get expensive when there are many
8163 // case labels so we test for it last.
8164 if (!CheckedForSinglePred) {
8165 CheckedForSinglePred = true;
8166 if (SI->findCaseDest(CaseBB) == nullptr) {
8167 SkipCase = true;
8168 break;
8169 }
8170 }
8171
8172 if (Replacement == nullptr) {
8173 if (PHIValue == CaseValue) {
8174 Replacement = Condition;
8175 } else {
8176 IRBuilder<> Builder(SI);
8177 Replacement = Builder.CreateZExt(Condition, PHIType);
8178 }
8179 }
8180 PHI.setIncomingValue(I, Replacement);
8181 Changed = true;
8182 }
8183 if (SkipCase)
8184 break;
8185 }
8186 }
8187 }
8188 return Changed;
8189}
8190
8191bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
8192 bool Changed = optimizeSwitchType(SI);
8193 Changed |= optimizeSwitchPhiConstants(SI);
8194 return Changed;
8195}
8196
8197namespace {
8198
8199/// Helper class to promote a scalar operation to a vector one.
8200/// This class is used to move downward extractelement transition.
8201/// E.g.,
8202/// a = vector_op <2 x i32>
8203/// b = extractelement <2 x i32> a, i32 0
8204/// c = scalar_op b
8205/// store c
8206///
8207/// =>
8208/// a = vector_op <2 x i32>
8209/// c = vector_op a (equivalent to scalar_op on the related lane)
8210/// * d = extractelement <2 x i32> c, i32 0
8211/// * store d
8212/// Assuming both extractelement and store can be combine, we get rid of the
8213/// transition.
8214class VectorPromoteHelper {
8215 /// DataLayout associated with the current module.
8216 const DataLayout &DL;
8217
8218 /// Used to perform some checks on the legality of vector operations.
8219 const TargetLowering &TLI;
8220
8221 /// Used to estimated the cost of the promoted chain.
8222 const TargetTransformInfo &TTI;
8223
8224 /// The transition being moved downwards.
8225 Instruction *Transition;
8226
8227 /// The sequence of instructions to be promoted.
8228 SmallVector<Instruction *, 4> InstsToBePromoted;
8229
8230 /// Cost of combining a store and an extract.
8231 unsigned StoreExtractCombineCost;
8232
8233 /// Instruction that will be combined with the transition.
8234 Instruction *CombineInst = nullptr;
8235
8236 /// The instruction that represents the current end of the transition.
8237 /// Since we are faking the promotion until we reach the end of the chain
8238 /// of computation, we need a way to get the current end of the transition.
8239 Instruction *getEndOfTransition() const {
8240 if (InstsToBePromoted.empty())
8241 return Transition;
8242 return InstsToBePromoted.back();
8243 }
8244
8245 /// Return the index of the original value in the transition.
8246 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
8247 /// c, is at index 0.
8248 unsigned getTransitionOriginalValueIdx() const {
8249 assert(isa<ExtractElementInst>(Transition) &&
8250 "Other kind of transitions are not supported yet");
8251 return 0;
8252 }
8253
8254 /// Return the index of the index in the transition.
8255 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
8256 /// is at index 1.
8257 unsigned getTransitionIdx() const {
8258 assert(isa<ExtractElementInst>(Transition) &&
8259 "Other kind of transitions are not supported yet");
8260 return 1;
8261 }
8262
8263 /// Get the type of the transition.
8264 /// This is the type of the original value.
8265 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
8266 /// transition is <2 x i32>.
8267 Type *getTransitionType() const {
8268 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
8269 }
8270
8271 /// Promote \p ToBePromoted by moving \p Def downward through.
8272 /// I.e., we have the following sequence:
8273 /// Def = Transition <ty1> a to <ty2>
8274 /// b = ToBePromoted <ty2> Def, ...
8275 /// =>
8276 /// b = ToBePromoted <ty1> a, ...
8277 /// Def = Transition <ty1> ToBePromoted to <ty2>
8278 void promoteImpl(Instruction *ToBePromoted);
8279
8280 /// Check whether or not it is profitable to promote all the
8281 /// instructions enqueued to be promoted.
8282 bool isProfitableToPromote() {
8283 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
8284 unsigned Index = isa<ConstantInt>(ValIdx)
8285 ? cast<ConstantInt>(ValIdx)->getZExtValue()
8286 : -1;
8287 Type *PromotedType = getTransitionType();
8288
8289 StoreInst *ST = cast<StoreInst>(CombineInst);
8290 unsigned AS = ST->getPointerAddressSpace();
8291 // Check if this store is supported.
8293 TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
8294 ST->getAlign())) {
8295 // If this is not supported, there is no way we can combine
8296 // the extract with the store.
8297 return false;
8298 }
8299
8300 // The scalar chain of computation has to pay for the transition
8301 // scalar to vector.
8302 // The vector chain has to account for the combining cost.
8305 InstructionCost ScalarCost =
8306 TTI.getVectorInstrCost(*Transition, PromotedType, CostKind, Index);
8307 InstructionCost VectorCost = StoreExtractCombineCost;
8308 for (const auto &Inst : InstsToBePromoted) {
8309 // Compute the cost.
8310 // By construction, all instructions being promoted are arithmetic ones.
8311 // Moreover, one argument is a constant that can be viewed as a splat
8312 // constant.
8313 Value *Arg0 = Inst->getOperand(0);
8314 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
8315 isa<ConstantFP>(Arg0);
8316 TargetTransformInfo::OperandValueInfo Arg0Info, Arg1Info;
8317 if (IsArg0Constant)
8319 else
8321
8322 ScalarCost += TTI.getArithmeticInstrCost(
8323 Inst->getOpcode(), Inst->getType(), CostKind, Arg0Info, Arg1Info);
8324 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
8325 CostKind, Arg0Info, Arg1Info);
8326 }
8327 LLVM_DEBUG(
8328 dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
8329 << ScalarCost << "\nVector: " << VectorCost << '\n');
8330 return ScalarCost > VectorCost;
8331 }
8332
8333 /// Generate a constant vector with \p Val with the same
8334 /// number of elements as the transition.
8335 /// \p UseSplat defines whether or not \p Val should be replicated
8336 /// across the whole vector.
8337 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
8338 /// otherwise we generate a vector with as many poison as possible:
8339 /// <poison, ..., poison, Val, poison, ..., poison> where \p Val is only
8340 /// used at the index of the extract.
8341 Value *getConstantVector(Constant *Val, bool UseSplat) const {
8342 unsigned ExtractIdx = std::numeric_limits<unsigned>::max();
8343 if (!UseSplat) {
8344 // If we cannot determine where the constant must be, we have to
8345 // use a splat constant.
8346 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
8347 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
8348 ExtractIdx = CstVal->getSExtValue();
8349 else
8350 UseSplat = true;
8351 }
8352
8353 ElementCount EC = cast<VectorType>(getTransitionType())->getElementCount();
8354 if (UseSplat)
8355 return ConstantVector::getSplat(EC, Val);
8356
8357 if (!EC.isScalable()) {
8358 SmallVector<Constant *, 4> ConstVec;
8359 PoisonValue *PoisonVal = PoisonValue::get(Val->getType());
8360 for (unsigned Idx = 0; Idx != EC.getKnownMinValue(); ++Idx) {
8361 if (Idx == ExtractIdx)
8362 ConstVec.push_back(Val);
8363 else
8364 ConstVec.push_back(PoisonVal);
8365 }
8366 return ConstantVector::get(ConstVec);
8367 } else
8369 "Generate scalable vector for non-splat is unimplemented");
8370 }
8371
8372 /// Check if promoting to a vector type an operand at \p OperandIdx
8373 /// in \p Use can trigger undefined behavior.
8374 static bool canCauseUndefinedBehavior(const Instruction *Use,
8375 unsigned OperandIdx) {
8376 // This is not safe to introduce undef when the operand is on
8377 // the right hand side of a division-like instruction.
8378 if (OperandIdx != 1)
8379 return false;
8380 switch (Use->getOpcode()) {
8381 default:
8382 return false;
8383 case Instruction::SDiv:
8384 case Instruction::UDiv:
8385 case Instruction::SRem:
8386 case Instruction::URem:
8387 return true;
8388 case Instruction::FDiv:
8389 case Instruction::FRem:
8390 return !Use->hasNoNaNs();
8391 }
8392 llvm_unreachable(nullptr);
8393 }
8394
8395public:
8396 VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
8397 const TargetTransformInfo &TTI, Instruction *Transition,
8398 unsigned CombineCost)
8399 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
8400 StoreExtractCombineCost(CombineCost) {
8401 assert(Transition && "Do not know how to promote null");
8402 }
8403
8404 /// Check if we can promote \p ToBePromoted to \p Type.
8405 bool canPromote(const Instruction *ToBePromoted) const {
8406 // We could support CastInst too.
8407 return isa<BinaryOperator>(ToBePromoted);
8408 }
8409
8410 /// Check if it is profitable to promote \p ToBePromoted
8411 /// by moving downward the transition through.
8412 bool shouldPromote(const Instruction *ToBePromoted) const {
8413 // Promote only if all the operands can be statically expanded.
8414 // Indeed, we do not want to introduce any new kind of transitions.
8415 for (const Use &U : ToBePromoted->operands()) {
8416 const Value *Val = U.get();
8417 if (Val == getEndOfTransition()) {
8418 // If the use is a division and the transition is on the rhs,
8419 // we cannot promote the operation, otherwise we may create a
8420 // division by zero.
8421 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
8422 return false;
8423 continue;
8424 }
8425 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
8426 !isa<ConstantFP>(Val))
8427 return false;
8428 }
8429 // Check that the resulting operation is legal.
8430 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
8431 if (!ISDOpcode)
8432 return false;
8433 return StressStoreExtract ||
8435 ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
8436 }
8437
8438 /// Check whether or not \p Use can be combined
8439 /// with the transition.
8440 /// I.e., is it possible to do Use(Transition) => AnotherUse?
8441 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
8442
8443 /// Record \p ToBePromoted as part of the chain to be promoted.
8444 void enqueueForPromotion(Instruction *ToBePromoted) {
8445 InstsToBePromoted.push_back(ToBePromoted);
8446 }
8447
8448 /// Set the instruction that will be combined with the transition.
8449 void recordCombineInstruction(Instruction *ToBeCombined) {
8450 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
8451 CombineInst = ToBeCombined;
8452 }
8453
8454 /// Promote all the instructions enqueued for promotion if it is
8455 /// is profitable.
8456 /// \return True if the promotion happened, false otherwise.
8457 bool promote() {
8458 // Check if there is something to promote.
8459 // Right now, if we do not have anything to combine with,
8460 // we assume the promotion is not profitable.
8461 if (InstsToBePromoted.empty() || !CombineInst)
8462 return false;
8463
8464 // Check cost.
8465 if (!StressStoreExtract && !isProfitableToPromote())
8466 return false;
8467
8468 // Promote.
8469 for (auto &ToBePromoted : InstsToBePromoted)
8470 promoteImpl(ToBePromoted);
8471 InstsToBePromoted.clear();
8472 return true;
8473 }
8474};
8475
8476} // end anonymous namespace
8477
8478void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
8479 // At this point, we know that all the operands of ToBePromoted but Def
8480 // can be statically promoted.
8481 // For Def, we need to use its parameter in ToBePromoted:
8482 // b = ToBePromoted ty1 a
8483 // Def = Transition ty1 b to ty2
8484 // Move the transition down.
8485 // 1. Replace all uses of the promoted operation by the transition.
8486 // = ... b => = ... Def.
8487 assert(ToBePromoted->getType() == Transition->getType() &&
8488 "The type of the result of the transition does not match "
8489 "the final type");
8490 ToBePromoted->replaceAllUsesWith(Transition);
8491 // 2. Update the type of the uses.
8492 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
8493 Type *TransitionTy = getTransitionType();
8494 ToBePromoted->mutateType(TransitionTy);
8495 // 3. Update all the operands of the promoted operation with promoted
8496 // operands.
8497 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
8498 for (Use &U : ToBePromoted->operands()) {
8499 Value *Val = U.get();
8500 Value *NewVal = nullptr;
8501 if (Val == Transition)
8502 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
8503 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
8504 isa<ConstantFP>(Val)) {
8505 // Use a splat constant if it is not safe to use undef.
8506 NewVal = getConstantVector(
8507 cast<Constant>(Val),
8508 isa<UndefValue>(Val) ||
8509 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
8510 } else
8511 llvm_unreachable("Did you modified shouldPromote and forgot to update "
8512 "this?");
8513 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
8514 }
8515 Transition->moveAfter(ToBePromoted);
8516 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
8517}
8518
8519/// Some targets can do store(extractelement) with one instruction.
8520/// Try to push the extractelement towards the stores when the target
8521/// has this feature and this is profitable.
8522bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
8523 unsigned CombineCost = std::numeric_limits<unsigned>::max();
8524 if (DisableStoreExtract ||
8527 Inst->getOperand(1), CombineCost)))
8528 return false;
8529
8530 // At this point we know that Inst is a vector to scalar transition.
8531 // Try to move it down the def-use chain, until:
8532 // - We can combine the transition with its single use
8533 // => we got rid of the transition.
8534 // - We escape the current basic block
8535 // => we would need to check that we are moving it at a cheaper place and
8536 // we do not do that for now.
8537 BasicBlock *Parent = Inst->getParent();
8538 LLVM_DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
8539 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
8540 // If the transition has more than one use, assume this is not going to be
8541 // beneficial.
8542 while (Inst->hasOneUse()) {
8543 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
8544 LLVM_DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
8545
8546 if (ToBePromoted->getParent() != Parent) {
8547 LLVM_DEBUG(dbgs() << "Instruction to promote is in a different block ("
8548 << ToBePromoted->getParent()->getName()
8549 << ") than the transition (" << Parent->getName()
8550 << ").\n");
8551 return false;
8552 }
8553
8554 if (VPH.canCombine(ToBePromoted)) {
8555 LLVM_DEBUG(dbgs() << "Assume " << *Inst << '\n'
8556 << "will be combined with: " << *ToBePromoted << '\n');
8557 VPH.recordCombineInstruction(ToBePromoted);
8558 bool Changed = VPH.promote();
8559 NumStoreExtractExposed += Changed;
8560 return Changed;
8561 }
8562
8563 LLVM_DEBUG(dbgs() << "Try promoting.\n");
8564 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
8565 return false;
8566
8567 LLVM_DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
8568
8569 VPH.enqueueForPromotion(ToBePromoted);
8570 Inst = ToBePromoted;
8571 }
8572 return false;
8573}
8574
8575/// For the instruction sequence of store below, F and I values
8576/// are bundled together as an i64 value before being stored into memory.
8577/// Sometimes it is more efficient to generate separate stores for F and I,
8578/// which can remove the bitwise instructions or sink them to colder places.
8579///
8580/// (store (or (zext (bitcast F to i32) to i64),
8581/// (shl (zext I to i64), 32)), addr) -->
8582/// (store F, addr) and (store I, addr+4)
8583///
8584/// Similarly, splitting for other merged store can also be beneficial, like:
8585/// For pair of {i32, i32}, i64 store --> two i32 stores.
8586/// For pair of {i32, i16}, i64 store --> two i32 stores.
8587/// For pair of {i16, i16}, i32 store --> two i16 stores.
8588/// For pair of {i16, i8}, i32 store --> two i16 stores.
8589/// For pair of {i8, i8}, i16 store --> two i8 stores.
8590///
8591/// We allow each target to determine specifically which kind of splitting is
8592/// supported.
8593///
8594/// The store patterns are commonly seen from the simple code snippet below
8595/// if only std::make_pair(...) is sroa transformed before inlined into hoo.
8596/// void goo(const std::pair<int, float> &);
8597/// hoo() {
8598/// ...
8599/// goo(std::make_pair(tmp, ftmp));
8600/// ...
8601/// }
8602///
8603/// Although we already have similar splitting in DAG Combine, we duplicate
8604/// it in CodeGenPrepare to catch the case in which pattern is across
8605/// multiple BBs. The logic in DAG Combine is kept to catch case generated
8606/// during code expansion.
8608 const TargetLowering &TLI) {
8609 // Handle simple but common cases only.
8610 Type *StoreType = SI.getValueOperand()->getType();
8611
8612 // The code below assumes shifting a value by <number of bits>,
8613 // whereas scalable vectors would have to be shifted by
8614 // <2log(vscale) + number of bits> in order to store the
8615 // low/high parts. Bailing out for now.
8616 if (StoreType->isScalableTy())
8617 return false;
8618
8619 if (!DL.typeSizeEqualsStoreSize(StoreType) ||
8620 DL.getTypeSizeInBits(StoreType) == 0)
8621 return false;
8622
8623 unsigned HalfValBitSize = DL.getTypeSizeInBits(StoreType) / 2;
8624 Type *SplitStoreType = Type::getIntNTy(SI.getContext(), HalfValBitSize);
8625 if (!DL.typeSizeEqualsStoreSize(SplitStoreType))
8626 return false;
8627
8628 // Don't split the store if it is volatile or atomic.
8629 if (!SI.isSimple())
8630 return false;
8631
8632 // Match the following patterns:
8633 // (store (or (zext LValue to i64),
8634 // (shl (zext HValue to i64), 32)), HalfValBitSize)
8635 // or
8636 // (store (or (shl (zext HValue to i64), 32)), HalfValBitSize)
8637 // (zext LValue to i64),
8638 // Expect both operands of OR and the first operand of SHL have only
8639 // one use.
8640 Value *LValue, *HValue;
8641 if (!match(SI.getValueOperand(),
8644 m_SpecificInt(HalfValBitSize))))))
8645 return false;
8646
8647 // Check LValue and HValue are int with size less or equal than 32.
8648 if (!LValue->getType()->isIntegerTy() ||
8649 DL.getTypeSizeInBits(LValue->getType()) > HalfValBitSize ||
8650 !HValue->getType()->isIntegerTy() ||
8651 DL.getTypeSizeInBits(HValue->getType()) > HalfValBitSize)
8652 return false;
8653
8654 // If LValue/HValue is a bitcast instruction, use the EVT before bitcast
8655 // as the input of target query.
8656 auto *LBC = dyn_cast<BitCastInst>(LValue);
8657 auto *HBC = dyn_cast<BitCastInst>(HValue);
8658 EVT LowTy = LBC ? EVT::getEVT(LBC->getOperand(0)->getType())
8659 : EVT::getEVT(LValue->getType());
8660 EVT HighTy = HBC ? EVT::getEVT(HBC->getOperand(0)->getType())
8661 : EVT::getEVT(HValue->getType());
8662 if (!ForceSplitStore && !TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
8663 return false;
8664
8665 // Start to split store.
8666 IRBuilder<> Builder(SI.getContext());
8667 Builder.SetInsertPoint(&SI);
8668
8669 // If LValue/HValue is a bitcast in another BB, create a new one in current
8670 // BB so it may be merged with the splitted stores by dag combiner.
8671 if (LBC && LBC->getParent() != SI.getParent())
8672 LValue = Builder.CreateBitCast(LBC->getOperand(0), LBC->getType());
8673 if (HBC && HBC->getParent() != SI.getParent())
8674 HValue = Builder.CreateBitCast(HBC->getOperand(0), HBC->getType());
8675
8676 bool IsLE = SI.getDataLayout().isLittleEndian();
8677 auto CreateSplitStore = [&](Value *V, bool Upper) {
8678 V = Builder.CreateZExtOrBitCast(V, SplitStoreType);
8679 Value *Addr = SI.getPointerOperand();
8680 Align Alignment = SI.getAlign();
8681 const bool IsOffsetStore = (IsLE && Upper) || (!IsLE && !Upper);
8682 if (IsOffsetStore) {
8683 Addr = Builder.CreateGEP(
8684 SplitStoreType, Addr,
8685 ConstantInt::get(Type::getInt32Ty(SI.getContext()), 1));
8686
8687 // When splitting the store in half, naturally one half will retain the
8688 // alignment of the original wider store, regardless of whether it was
8689 // over-aligned or not, while the other will require adjustment.
8690 Alignment = commonAlignment(Alignment, HalfValBitSize / 8);
8691 }
8692 Builder.CreateAlignedStore(V, Addr, Alignment);
8693 };
8694
8695 CreateSplitStore(LValue, false);
8696 CreateSplitStore(HValue, true);
8697
8698 // Delete the old store.
8699 SI.eraseFromParent();
8700 return true;
8701}
8702
8703// Return true if the GEP has two operands, the first operand is of a sequential
8704// type, and the second operand is a constant.
8707 return GEP->getNumOperands() == 2 && I.isSequential() &&
8708 isa<ConstantInt>(GEP->getOperand(1));
8709}
8710
8711// Try unmerging GEPs to reduce liveness interference (register pressure) across
8712// IndirectBr edges. Since IndirectBr edges tend to touch on many blocks,
8713// reducing liveness interference across those edges benefits global register
8714// allocation. Currently handles only certain cases.
8715//
8716// For example, unmerge %GEPI and %UGEPI as below.
8717//
8718// ---------- BEFORE ----------
8719// SrcBlock:
8720// ...
8721// %GEPIOp = ...
8722// ...
8723// %GEPI = gep %GEPIOp, Idx
8724// ...
8725// indirectbr ... [ label %DstB0, label %DstB1, ... label %DstBi ... ]
8726// (* %GEPI is alive on the indirectbr edges due to other uses ahead)
8727// (* %GEPIOp is alive on the indirectbr edges only because of it's used by
8728// %UGEPI)
8729//
8730// DstB0: ... (there may be a gep similar to %UGEPI to be unmerged)
8731// DstB1: ... (there may be a gep similar to %UGEPI to be unmerged)
8732// ...
8733//
8734// DstBi:
8735// ...
8736// %UGEPI = gep %GEPIOp, UIdx
8737// ...
8738// ---------------------------
8739//
8740// ---------- AFTER ----------
8741// SrcBlock:
8742// ... (same as above)
8743// (* %GEPI is still alive on the indirectbr edges)
8744// (* %GEPIOp is no longer alive on the indirectbr edges as a result of the
8745// unmerging)
8746// ...
8747//
8748// DstBi:
8749// ...
8750// %UGEPI = gep %GEPI, (UIdx-Idx)
8751// ...
8752// ---------------------------
8753//
8754// The register pressure on the IndirectBr edges is reduced because %GEPIOp is
8755// no longer alive on them.
8756//
8757// We try to unmerge GEPs here in CodGenPrepare, as opposed to limiting merging
8758// of GEPs in the first place in InstCombiner::visitGetElementPtrInst() so as
8759// not to disable further simplications and optimizations as a result of GEP
8760// merging.
8761//
8762// Note this unmerging may increase the length of the data flow critical path
8763// (the path from %GEPIOp to %UGEPI would go through %GEPI), which is a tradeoff
8764// between the register pressure and the length of data-flow critical
8765// path. Restricting this to the uncommon IndirectBr case would minimize the
8766// impact of potentially longer critical path, if any, and the impact on compile
8767// time.
8769 const TargetTransformInfo *TTI) {
8770 BasicBlock *SrcBlock = GEPI->getParent();
8771 // Check that SrcBlock ends with an IndirectBr. If not, give up. The common
8772 // (non-IndirectBr) cases exit early here.
8773 if (!isa<IndirectBrInst>(SrcBlock->getTerminator()))
8774 return false;
8775 // Check that GEPI is a simple gep with a single constant index.
8776 if (!GEPSequentialConstIndexed(GEPI))
8777 return false;
8778 ConstantInt *GEPIIdx = cast<ConstantInt>(GEPI->getOperand(1));
8779 // Check that GEPI is a cheap one.
8780 if (TTI->getIntImmCost(GEPIIdx->getValue(), GEPIIdx->getType(),
8783 return false;
8784 Value *GEPIOp = GEPI->getOperand(0);
8785 // Check that GEPIOp is an instruction that's also defined in SrcBlock.
8786 if (!isa<Instruction>(GEPIOp))
8787 return false;
8788 auto *GEPIOpI = cast<Instruction>(GEPIOp);
8789 if (GEPIOpI->getParent() != SrcBlock)
8790 return false;
8791 // Check that GEP is used outside the block, meaning it's alive on the
8792 // IndirectBr edge(s).
8793 if (llvm::none_of(GEPI->users(), [&](User *Usr) {
8794 if (auto *I = dyn_cast<Instruction>(Usr)) {
8795 if (I->getParent() != SrcBlock) {
8796 return true;
8797 }
8798 }
8799 return false;
8800 }))
8801 return false;
8802 // The second elements of the GEP chains to be unmerged.
8803 std::vector<GetElementPtrInst *> UGEPIs;
8804 // Check each user of GEPIOp to check if unmerging would make GEPIOp not alive
8805 // on IndirectBr edges.
8806 for (User *Usr : GEPIOp->users()) {
8807 if (Usr == GEPI)
8808 continue;
8809 // Check if Usr is an Instruction. If not, give up.
8810 if (!isa<Instruction>(Usr))
8811 return false;
8812 auto *UI = cast<Instruction>(Usr);
8813 // Check if Usr in the same block as GEPIOp, which is fine, skip.
8814 if (UI->getParent() == SrcBlock)
8815 continue;
8816 // Check if Usr is a GEP. If not, give up.
8817 if (!isa<GetElementPtrInst>(Usr))
8818 return false;
8819 auto *UGEPI = cast<GetElementPtrInst>(Usr);
8820 // Check if UGEPI is a simple gep with a single constant index and GEPIOp is
8821 // the pointer operand to it. If so, record it in the vector. If not, give
8822 // up.
8823 if (!GEPSequentialConstIndexed(UGEPI))
8824 return false;
8825 if (UGEPI->getOperand(0) != GEPIOp)
8826 return false;
8827 if (UGEPI->getSourceElementType() != GEPI->getSourceElementType())
8828 return false;
8829 if (GEPIIdx->getType() !=
8830 cast<ConstantInt>(UGEPI->getOperand(1))->getType())
8831 return false;
8832 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
8833 if (TTI->getIntImmCost(UGEPIIdx->getValue(), UGEPIIdx->getType(),
8836 return false;
8837 UGEPIs.push_back(UGEPI);
8838 }
8839 if (UGEPIs.size() == 0)
8840 return false;
8841 // Check the materializing cost of (Uidx-Idx).
8842 for (GetElementPtrInst *UGEPI : UGEPIs) {
8843 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
8844 APInt NewIdx = UGEPIIdx->getValue() - GEPIIdx->getValue();
8846 NewIdx, GEPIIdx->getType(), TargetTransformInfo::TCK_SizeAndLatency);
8847 if (ImmCost > TargetTransformInfo::TCC_Basic)
8848 return false;
8849 }
8850 // Now unmerge between GEPI and UGEPIs.
8851 for (GetElementPtrInst *UGEPI : UGEPIs) {
8852 UGEPI->setOperand(0, GEPI);
8853 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
8854 auto NewIdx = UGEPIIdx->getValue() - GEPIIdx->getValue();
8855 Constant *NewUGEPIIdx = ConstantInt::get(GEPIIdx->getType(), NewIdx);
8856 UGEPI->setOperand(1, NewUGEPIIdx);
8857
8858 auto SourceFlags = GEPI->getNoWrapFlags();
8859 // Intersect flags to avoid UB in updated GEP.
8860 auto TargetFlags =
8861 UGEPI->getNoWrapFlags().intersectForOffsetAdd(SourceFlags);
8862 // If UGEPI now has a negative index, drop the nuw flag.
8863 if (NewIdx.isNegative() && TargetFlags.hasNoUnsignedWrap())
8864 TargetFlags = TargetFlags.withoutNoUnsignedWrap();
8865 UGEPI->setNoWrapFlags(TargetFlags);
8866 }
8867 // After unmerging, verify that GEPIOp is actually only used in SrcBlock (not
8868 // alive on IndirectBr edges).
8869 assert(llvm::none_of(GEPIOp->users(),
8870 [&](User *Usr) {
8871 return cast<Instruction>(Usr)->getParent() != SrcBlock;
8872 }) &&
8873 "GEPIOp is used outside SrcBlock");
8874 return true;
8875}
8876
8877static bool optimizeBranch(CondBrInst *Branch, const TargetLowering &TLI,
8879 bool IsHugeFunc) {
8880 // Try and convert
8881 // %c = icmp ult %x, 8
8882 // br %c, bla, blb
8883 // %tc = lshr %x, 3
8884 // to
8885 // %tc = lshr %x, 3
8886 // %c = icmp eq %tc, 0
8887 // br %c, bla, blb
8888 // Creating the cmp to zero can be better for the backend, especially if the
8889 // lshr produces flags that can be used automatically.
8890 if (!TLI.preferZeroCompareBranch())
8891 return false;
8892
8893 ICmpInst *Cmp = dyn_cast<ICmpInst>(Branch->getCondition());
8894 if (!Cmp || !isa<ConstantInt>(Cmp->getOperand(1)) || !Cmp->hasOneUse())
8895 return false;
8896
8897 Value *X = Cmp->getOperand(0);
8898 if (!X->hasUseList())
8899 return false;
8900
8901 APInt CmpC = cast<ConstantInt>(Cmp->getOperand(1))->getValue();
8902
8903 for (auto *U : X->users()) {
8905 // A quick dominance check
8906 if (!UI ||
8907 (UI->getParent() != Branch->getParent() &&
8908 UI->getParent() != Branch->getSuccessor(0) &&
8909 UI->getParent() != Branch->getSuccessor(1)) ||
8910 (UI->getParent() != Branch->getParent() &&
8911 !UI->getParent()->getSinglePredecessor()))
8912 continue;
8913
8914 if (CmpC.isPowerOf2() && Cmp->getPredicate() == ICmpInst::ICMP_ULT &&
8915 match(UI, m_Shr(m_Specific(X), m_SpecificInt(CmpC.logBase2())))) {
8916 IRBuilder<> Builder(Branch);
8917 if (UI->getParent() != Branch->getParent())
8918 UI->moveBefore(Branch->getIterator());
8920 Value *NewCmp = Builder.CreateCmp(ICmpInst::ICMP_EQ, UI,
8921 ConstantInt::get(UI->getType(), 0));
8922 LLVM_DEBUG(dbgs() << "Converting " << *Cmp << "\n");
8923 LLVM_DEBUG(dbgs() << " to compare on zero: " << *NewCmp << "\n");
8924 replaceAllUsesWith(Cmp, NewCmp, FreshBBs, IsHugeFunc);
8925 return true;
8926 }
8927 if (Cmp->isEquality() &&
8928 (match(UI, m_Add(m_Specific(X), m_SpecificInt(-CmpC))) ||
8929 match(UI, m_Sub(m_Specific(X), m_SpecificInt(CmpC))) ||
8930 match(UI, m_Xor(m_Specific(X), m_SpecificInt(CmpC))))) {
8931 IRBuilder<> Builder(Branch);
8932 if (UI->getParent() != Branch->getParent())
8933 UI->moveBefore(Branch->getIterator());
8935 Value *NewCmp = Builder.CreateCmp(Cmp->getPredicate(), UI,
8936 ConstantInt::get(UI->getType(), 0));
8937 LLVM_DEBUG(dbgs() << "Converting " << *Cmp << "\n");
8938 LLVM_DEBUG(dbgs() << " to compare on zero: " << *NewCmp << "\n");
8939 replaceAllUsesWith(Cmp, NewCmp, FreshBBs, IsHugeFunc);
8940 return true;
8941 }
8942 }
8943 return false;
8944}
8945
8946bool CodeGenPrepare::optimizeInst(Instruction *I, ModifyDT &ModifiedDT) {
8947 bool AnyChange = false;
8948 AnyChange = fixupDbgVariableRecordsOnInst(*I);
8949
8950 // Bail out if we inserted the instruction to prevent optimizations from
8951 // stepping on each other's toes.
8952 if (InsertedInsts.count(I))
8953 return AnyChange;
8954
8955 // TODO: Move into the switch on opcode below here.
8956 if (PHINode *P = dyn_cast<PHINode>(I)) {
8957 // It is possible for very late stage optimizations (such as SimplifyCFG)
8958 // to introduce PHI nodes too late to be cleaned up. If we detect such a
8959 // trivial PHI, go ahead and zap it here.
8960 if (Value *V = simplifyInstruction(P, {*DL, TLInfo})) {
8961 LargeOffsetGEPMap.erase(P);
8962 replaceAllUsesWith(P, V, FreshBBs, IsHugeFunc);
8963 P->eraseFromParent();
8964 ++NumPHIsElim;
8965 return true;
8966 }
8967 return AnyChange;
8968 }
8969
8970 if (CastInst *CI = dyn_cast<CastInst>(I)) {
8971 // If the source of the cast is a constant, then this should have
8972 // already been constant folded. The only reason NOT to constant fold
8973 // it is if something (e.g. LSR) was careful to place the constant
8974 // evaluation in a block other than then one that uses it (e.g. to hoist
8975 // the address of globals out of a loop). If this is the case, we don't
8976 // want to forward-subst the cast.
8977 if (auto *BCI = dyn_cast<BitCastInst>(CI)) {
8978 // Hoist bitcasts of illegal types to reduce cross-block register pressure
8979 // and prevent register splitting.
8980 if (optimizeBitCast(BCI, *TLI, *DL)) {
8981 return true;
8982 }
8983 }
8984
8985 if (isa<Constant>(CI->getOperand(0)))
8986 return AnyChange;
8987
8988 if (OptimizeNoopCopyExpression(CI, *TLI, *DL))
8989 return true;
8990
8992 isa<TruncInst>(I)) &&
8994 I, LI->getLoopFor(I->getParent()), *TTI))
8995 return true;
8996
8997 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
8998 /// Sink a zext or sext into its user blocks if the target type doesn't
8999 /// fit in one register
9000 if (TLI->getTypeAction(CI->getContext(),
9001 TLI->getValueType(*DL, CI->getType())) ==
9002 TargetLowering::TypeExpandInteger) {
9003 return SinkCast(CI);
9004 } else {
9006 I, LI->getLoopFor(I->getParent()), *TTI))
9007 return true;
9008
9009 bool MadeChange = optimizeExt(I);
9010 return MadeChange | optimizeExtUses(I);
9011 }
9012 }
9013 return AnyChange;
9014 }
9015
9016 if (auto *Cmp = dyn_cast<CmpInst>(I))
9017 if (optimizeCmp(Cmp, ModifiedDT))
9018 return true;
9019
9020 if (match(I, m_URem(m_Value(), m_Value())))
9021 if (optimizeURem(I))
9022 return true;
9023
9024 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
9025 LI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
9026 bool Modified = optimizeLoadExt(LI);
9027 unsigned AS = LI->getPointerAddressSpace();
9028 Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
9029 return Modified;
9030 }
9031
9032 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
9033 if (splitMergedValStore(*SI, *DL, *TLI))
9034 return true;
9035 SI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
9036 unsigned AS = SI->getPointerAddressSpace();
9037 return optimizeMemoryInst(I, SI->getOperand(1),
9038 SI->getOperand(0)->getType(), AS);
9039 }
9040
9041 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
9042 unsigned AS = RMW->getPointerAddressSpace();
9043 return optimizeMemoryInst(I, RMW->getPointerOperand(), RMW->getType(), AS);
9044 }
9045
9046 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(I)) {
9047 unsigned AS = CmpX->getPointerAddressSpace();
9048 return optimizeMemoryInst(I, CmpX->getPointerOperand(),
9049 CmpX->getCompareOperand()->getType(), AS);
9050 }
9051
9052 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
9053
9054 if (BinOp && BinOp->getOpcode() == Instruction::And && EnableAndCmpSinking &&
9055 sinkAndCmp0Expression(BinOp, *TLI, InsertedInsts))
9056 return true;
9057
9058 // TODO: Move this into the switch on opcode - it handles shifts already.
9059 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
9060 BinOp->getOpcode() == Instruction::LShr)) {
9061 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
9062 if (CI && TLI->hasExtractBitsInsn())
9063 if (OptimizeExtractBits(BinOp, CI, *TLI, *DL))
9064 return true;
9065 }
9066
9067 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
9068 if (GEPI->hasAllZeroIndices()) {
9069 /// The GEP operand must be a pointer, so must its result -> BitCast
9070 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
9071 GEPI->getName(), GEPI->getIterator());
9072 NC->setDebugLoc(GEPI->getDebugLoc());
9073 replaceAllUsesWith(GEPI, NC, FreshBBs, IsHugeFunc);
9075 GEPI, TLInfo, nullptr,
9076 [&](Value *V) { removeAllAssertingVHReferences(V); });
9077 ++NumGEPsElim;
9078 optimizeInst(NC, ModifiedDT);
9079 return true;
9080 }
9082 return true;
9083 }
9084 }
9085
9086 if (FreezeInst *FI = dyn_cast<FreezeInst>(I)) {
9087 // freeze(icmp a, const)) -> icmp (freeze a), const
9088 // This helps generate efficient conditional jumps.
9089 Instruction *CmpI = nullptr;
9090 if (ICmpInst *II = dyn_cast<ICmpInst>(FI->getOperand(0)))
9091 CmpI = II;
9092 else if (FCmpInst *F = dyn_cast<FCmpInst>(FI->getOperand(0)))
9093 CmpI = F->getFastMathFlags().none() ? F : nullptr;
9094
9095 if (CmpI && CmpI->hasOneUse()) {
9096 auto Op0 = CmpI->getOperand(0), Op1 = CmpI->getOperand(1);
9097 bool Const0 = isa<ConstantInt>(Op0) || isa<ConstantFP>(Op0) ||
9099 bool Const1 = isa<ConstantInt>(Op1) || isa<ConstantFP>(Op1) ||
9101 if (Const0 || Const1) {
9102 if (!Const0 || !Const1) {
9103 auto *F = new FreezeInst(Const0 ? Op1 : Op0, "", CmpI->getIterator());
9104 F->takeName(FI);
9105 CmpI->setOperand(Const0 ? 1 : 0, F);
9106 }
9107 replaceAllUsesWith(FI, CmpI, FreshBBs, IsHugeFunc);
9108 FI->eraseFromParent();
9109 return true;
9110 }
9111 }
9112 return AnyChange;
9113 }
9114
9115 if (tryToSinkFreeOperands(I))
9116 return true;
9117
9118 switch (I->getOpcode()) {
9119 case Instruction::Shl:
9120 case Instruction::LShr:
9121 case Instruction::AShr:
9122 return optimizeShiftInst(cast<BinaryOperator>(I));
9123 case Instruction::Call:
9124 return optimizeCallInst(cast<CallInst>(I), ModifiedDT);
9125 case Instruction::Select:
9126 return optimizeSelectInst(cast<SelectInst>(I));
9127 case Instruction::ShuffleVector:
9128 return optimizeShuffleVectorInst(cast<ShuffleVectorInst>(I));
9129 case Instruction::Switch:
9130 return optimizeSwitchInst(cast<SwitchInst>(I));
9131 case Instruction::ExtractElement:
9132 return optimizeExtractElementInst(cast<ExtractElementInst>(I));
9133 case Instruction::CondBr:
9134 return optimizeBranch(cast<CondBrInst>(I), *TLI, FreshBBs, IsHugeFunc);
9135 }
9136
9137 return AnyChange;
9138}
9139
9140/// Given an OR instruction, check to see if this is a bitreverse
9141/// idiom. If so, insert the new intrinsic and return true.
9142bool CodeGenPrepare::makeBitReverse(Instruction &I) {
9143 if (!I.getType()->isIntegerTy() ||
9145 TLI->getValueType(*DL, I.getType(), true)))
9146 return false;
9147
9148 SmallVector<Instruction *, 4> Insts;
9149 if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts))
9150 return false;
9151 Instruction *LastInst = Insts.back();
9152 replaceAllUsesWith(&I, LastInst, FreshBBs, IsHugeFunc);
9154 &I, TLInfo, nullptr,
9155 [&](Value *V) { removeAllAssertingVHReferences(V); });
9156 return true;
9157}
9158
9159// In this pass we look for GEP and cast instructions that are used
9160// across basic blocks and rewrite them to improve basic-block-at-a-time
9161// selection.
9162bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, ModifyDT &ModifiedDT) {
9163 SunkAddrs.clear();
9164 bool MadeChange = false;
9165
9166 do {
9167 CurInstIterator = BB.begin();
9168 ModifiedDT = ModifyDT::NotModifyDT;
9169 while (CurInstIterator != BB.end()) {
9170 MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
9171 if (ModifiedDT != ModifyDT::NotModifyDT) {
9172 // For huge function we tend to quickly go though the inner optmization
9173 // opportunities in the BB. So we go back to the BB head to re-optimize
9174 // each instruction instead of go back to the function head.
9175 if (IsHugeFunc)
9176 break;
9177 return true;
9178 }
9179 }
9180 } while (ModifiedDT == ModifyDT::ModifyInstDT);
9181
9182 bool MadeBitReverse = true;
9183 while (MadeBitReverse) {
9184 MadeBitReverse = false;
9185 for (auto &I : reverse(BB)) {
9186 if (makeBitReverse(I)) {
9187 MadeBitReverse = MadeChange = true;
9188 break;
9189 }
9190 }
9191 }
9192 MadeChange |= dupRetToEnableTailCallOpts(&BB, ModifiedDT);
9193
9194 return MadeChange;
9195}
9196
9197bool CodeGenPrepare::fixupDbgVariableRecordsOnInst(Instruction &I) {
9198 bool AnyChange = false;
9199 for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange()))
9200 AnyChange |= fixupDbgVariableRecord(DVR);
9201 return AnyChange;
9202}
9203
9204// FIXME: should updating debug-info really cause the "changed" flag to fire,
9205// which can cause a function to be reprocessed?
9206bool CodeGenPrepare::fixupDbgVariableRecord(DbgVariableRecord &DVR) {
9207 if (DVR.Type != DbgVariableRecord::LocationType::Value &&
9208 DVR.Type != DbgVariableRecord::LocationType::Assign)
9209 return false;
9210
9211 // Does this DbgVariableRecord refer to a sunk address calculation?
9212 bool AnyChange = false;
9213 SmallDenseSet<Value *> LocationOps(DVR.location_ops().begin(),
9214 DVR.location_ops().end());
9215 for (Value *Location : LocationOps) {
9216 WeakTrackingVH SunkAddrVH = SunkAddrs[Location];
9217 Value *SunkAddr = SunkAddrVH.pointsToAliveValue() ? SunkAddrVH : nullptr;
9218 if (SunkAddr) {
9219 // Point dbg.value at locally computed address, which should give the best
9220 // opportunity to be accurately lowered. This update may change the type
9221 // of pointer being referred to; however this makes no difference to
9222 // debugging information, and we can't generate bitcasts that may affect
9223 // codegen.
9224 DVR.replaceVariableLocationOp(Location, SunkAddr);
9225 AnyChange = true;
9226 }
9227 }
9228 return AnyChange;
9229}
9230
9232 DVR->removeFromParent();
9233 BasicBlock *VIBB = VI->getParent();
9234 if (isa<PHINode>(VI))
9235 VIBB->insertDbgRecordBefore(DVR, VIBB->getFirstInsertionPt());
9236 else
9237 VIBB->insertDbgRecordAfter(DVR, &*VI);
9238}
9239
9240// A llvm.dbg.value may be using a value before its definition, due to
9241// optimizations in this pass and others. Scan for such dbg.values, and rescue
9242// them by moving the dbg.value to immediately after the value definition.
9243// FIXME: Ideally this should never be necessary, and this has the potential
9244// to re-order dbg.value intrinsics.
9245bool CodeGenPrepare::placeDbgValues(Function &F) {
9246 bool MadeChange = false;
9247 DominatorTree &DT = getDT();
9248
9249 auto DbgProcessor = [&](auto *DbgItem, Instruction *Position) {
9250 SmallVector<Instruction *, 4> VIs;
9251 for (Value *V : DbgItem->location_ops())
9252 if (Instruction *VI = dyn_cast_or_null<Instruction>(V))
9253 VIs.push_back(VI);
9254
9255 // This item may depend on multiple instructions, complicating any
9256 // potential sink. This block takes the defensive approach, opting to
9257 // "undef" the item if it has more than one instruction and any of them do
9258 // not dominate iem.
9259 for (Instruction *VI : VIs) {
9260 if (VI->isTerminator())
9261 continue;
9262
9263 // If VI is a phi in a block with an EHPad terminator, we can't insert
9264 // after it.
9265 if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
9266 continue;
9267
9268 // If the defining instruction dominates the dbg.value, we do not need
9269 // to move the dbg.value.
9270 if (DT.dominates(VI, Position))
9271 continue;
9272
9273 // If we depend on multiple instructions and any of them doesn't
9274 // dominate this DVI, we probably can't salvage it: moving it to
9275 // after any of the instructions could cause us to lose the others.
9276 if (VIs.size() > 1) {
9277 LLVM_DEBUG(
9278 dbgs()
9279 << "Unable to find valid location for Debug Value, undefing:\n"
9280 << *DbgItem);
9281 DbgItem->setKillLocation();
9282 break;
9283 }
9284
9285 LLVM_DEBUG(dbgs() << "Moving Debug Value before :\n"
9286 << *DbgItem << ' ' << *VI);
9287 DbgInserterHelper(DbgItem, VI->getIterator());
9288 MadeChange = true;
9289 ++NumDbgValueMoved;
9290 }
9291 };
9292
9293 for (BasicBlock &BB : F) {
9294 for (Instruction &Insn : llvm::make_early_inc_range(BB)) {
9295 // Process any DbgVariableRecord records attached to this
9296 // instruction.
9297 for (DbgVariableRecord &DVR : llvm::make_early_inc_range(
9298 filterDbgVars(Insn.getDbgRecordRange()))) {
9299 if (DVR.Type != DbgVariableRecord::LocationType::Value)
9300 continue;
9301 DbgProcessor(&DVR, &Insn);
9302 }
9303 }
9304 }
9305
9306 return MadeChange;
9307}
9308
9309// Group scattered pseudo probes in a block to favor SelectionDAG. Scattered
9310// probes can be chained dependencies of other regular DAG nodes and block DAG
9311// combine optimizations.
9312bool CodeGenPrepare::placePseudoProbes(Function &F) {
9313 bool MadeChange = false;
9314 for (auto &Block : F) {
9315 // Move the rest probes to the beginning of the block.
9316 auto FirstInst = Block.getFirstInsertionPt();
9317 while (FirstInst != Block.end() && FirstInst->isDebugOrPseudoInst())
9318 ++FirstInst;
9319 BasicBlock::iterator I(FirstInst);
9320 I++;
9321 while (I != Block.end()) {
9322 if (auto *II = dyn_cast<PseudoProbeInst>(I++)) {
9323 II->moveBefore(FirstInst);
9324 MadeChange = true;
9325 }
9326 }
9327 }
9328 return MadeChange;
9329}
9330
9331/// Some targets prefer to split a conditional branch like:
9332/// \code
9333/// %0 = icmp ne i32 %a, 0
9334/// %1 = icmp ne i32 %b, 0
9335/// %or.cond = or i1 %0, %1
9336/// br i1 %or.cond, label %TrueBB, label %FalseBB
9337/// \endcode
9338/// into multiple branch instructions like:
9339/// \code
9340/// bb1:
9341/// %0 = icmp ne i32 %a, 0
9342/// br i1 %0, label %TrueBB, label %bb2
9343/// bb2:
9344/// %1 = icmp ne i32 %b, 0
9345/// br i1 %1, label %TrueBB, label %FalseBB
9346/// \endcode
9347/// This usually allows instruction selection to do even further optimizations
9348/// and combine the compare with the branch instruction. Currently this is
9349/// applied for targets which have "cheap" jump instructions.
9350///
9351/// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
9352///
9353bool CodeGenPrepare::splitBranchCondition(Function &F) {
9354 if (!TM->Options.EnableFastISel || TLI->isJumpExpensive())
9355 return false;
9356
9357 bool MadeChange = false;
9358 for (auto &BB : F) {
9359 // Does this BB end with the following?
9360 // %cond1 = icmp|fcmp|binary instruction ...
9361 // %cond2 = icmp|fcmp|binary instruction ...
9362 // %cond.or = or|and i1 %cond1, cond2
9363 // br i1 %cond.or label %dest1, label %dest2"
9364 Instruction *LogicOp;
9365 BasicBlock *TBB, *FBB;
9366 if (!match(BB.getTerminator(),
9367 m_Br(m_OneUse(m_Instruction(LogicOp)), TBB, FBB)))
9368 continue;
9369
9370 auto *Br1 = cast<CondBrInst>(BB.getTerminator());
9371 if (Br1->getMetadata(LLVMContext::MD_unpredictable))
9372 continue;
9373
9374 // The merging of mostly empty BB can cause a degenerate branch.
9375 if (TBB == FBB)
9376 continue;
9377
9378 unsigned Opc;
9379 Value *Cond1, *Cond2;
9380 if (match(LogicOp,
9381 m_LogicalAnd(m_OneUse(m_Value(Cond1)), m_OneUse(m_Value(Cond2)))))
9382 Opc = Instruction::And;
9383 else if (match(LogicOp, m_LogicalOr(m_OneUse(m_Value(Cond1)),
9384 m_OneUse(m_Value(Cond2)))))
9385 Opc = Instruction::Or;
9386 else
9387 continue;
9388
9389 auto IsGoodCond = [](Value *Cond) {
9390 return match(
9391 Cond,
9393 m_LogicalOr(m_Value(), m_Value()))));
9394 };
9395 if (!IsGoodCond(Cond1) || !IsGoodCond(Cond2))
9396 continue;
9397
9398 LLVM_DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
9399
9400 // Create a new BB.
9401 auto *TmpBB =
9402 BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split",
9403 BB.getParent(), BB.getNextNode());
9404 if (IsHugeFunc)
9405 FreshBBs.insert(TmpBB);
9406
9407 // Update original basic block by using the first condition directly by the
9408 // branch instruction and removing the no longer needed and/or instruction.
9409 Br1->setCondition(Cond1);
9410 LogicOp->eraseFromParent();
9411
9412 // Depending on the condition we have to either replace the true or the
9413 // false successor of the original branch instruction.
9414 if (Opc == Instruction::And)
9415 Br1->setSuccessor(0, TmpBB);
9416 else
9417 Br1->setSuccessor(1, TmpBB);
9418
9419 // Fill in the new basic block.
9420 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
9421 if (auto *I = dyn_cast<Instruction>(Cond2)) {
9422 I->removeFromParent();
9423 I->insertBefore(Br2->getIterator());
9424 }
9425
9426 // Update PHI nodes in both successors. The original BB needs to be
9427 // replaced in one successor's PHI nodes, because the branch comes now from
9428 // the newly generated BB (NewBB). In the other successor we need to add one
9429 // incoming edge to the PHI nodes, because both branch instructions target
9430 // now the same successor. Depending on the original branch condition
9431 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
9432 // we perform the correct update for the PHI nodes.
9433 // This doesn't change the successor order of the just created branch
9434 // instruction (or any other instruction).
9435 if (Opc == Instruction::Or)
9436 std::swap(TBB, FBB);
9437
9438 // Replace the old BB with the new BB.
9439 TBB->replacePhiUsesWith(&BB, TmpBB);
9440
9441 // Add another incoming edge from the new BB.
9442 for (PHINode &PN : FBB->phis()) {
9443 auto *Val = PN.getIncomingValueForBlock(&BB);
9444 PN.addIncoming(Val, TmpBB);
9445 }
9446
9447 if (Loop *L = LI->getLoopFor(&BB))
9448 L->addBasicBlockToLoop(TmpBB, *LI);
9449
9450 // The edge we need to delete starts at BB and ends at whatever TBB ends
9451 // up pointing to.
9452 DTU->applyUpdates({{DominatorTree::Insert, &BB, TmpBB},
9453 {DominatorTree::Insert, TmpBB, TBB},
9454 {DominatorTree::Insert, TmpBB, FBB},
9455 {DominatorTree::Delete, &BB, TBB}});
9456
9457 // Update the branch weights (from SelectionDAGBuilder::
9458 // FindMergedConditions).
9459 if (Opc == Instruction::Or) {
9460 // Codegen X | Y as:
9461 // BB1:
9462 // jmp_if_X TBB
9463 // jmp TmpBB
9464 // TmpBB:
9465 // jmp_if_Y TBB
9466 // jmp FBB
9467 //
9468
9469 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
9470 // The requirement is that
9471 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
9472 // = TrueProb for original BB.
9473 // Assuming the original weights are A and B, one choice is to set BB1's
9474 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
9475 // assumes that
9476 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
9477 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
9478 // TmpBB, but the math is more complicated.
9479 uint64_t TrueWeight, FalseWeight;
9480 if (extractBranchWeights(*Br1, TrueWeight, FalseWeight)) {
9481 uint64_t NewTrueWeight = TrueWeight;
9482 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
9483 setFittedBranchWeights(*Br1, {NewTrueWeight, NewFalseWeight},
9484 hasBranchWeightOrigin(*Br1));
9485
9486 NewTrueWeight = TrueWeight;
9487 NewFalseWeight = 2 * FalseWeight;
9488 setFittedBranchWeights(*Br2, {NewTrueWeight, NewFalseWeight},
9489 /*IsExpected=*/false);
9490 }
9491 } else {
9492 // Codegen X & Y as:
9493 // BB1:
9494 // jmp_if_X TmpBB
9495 // jmp FBB
9496 // TmpBB:
9497 // jmp_if_Y TBB
9498 // jmp FBB
9499 //
9500 // This requires creation of TmpBB after CurBB.
9501
9502 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
9503 // The requirement is that
9504 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
9505 // = FalseProb for original BB.
9506 // Assuming the original weights are A and B, one choice is to set BB1's
9507 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
9508 // assumes that
9509 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
9510 uint64_t TrueWeight, FalseWeight;
9511 if (extractBranchWeights(*Br1, TrueWeight, FalseWeight)) {
9512 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
9513 uint64_t NewFalseWeight = FalseWeight;
9514 setFittedBranchWeights(*Br1, {NewTrueWeight, NewFalseWeight},
9515 /*IsExpected=*/false);
9516
9517 NewTrueWeight = 2 * TrueWeight;
9518 NewFalseWeight = FalseWeight;
9519 setFittedBranchWeights(*Br2, {NewTrueWeight, NewFalseWeight},
9520 /*IsExpected=*/false);
9521 }
9522 }
9523
9524 MadeChange = true;
9525
9526 LLVM_DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
9527 TmpBB->dump());
9528 }
9529 return MadeChange;
9530}
#define Success
return SDValue()
static unsigned getIntrinsicID(const SDNode *N)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
AMDGPU Register Bank Select
Rewrite undef for PHI
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
This file contains the simple types necessary to represent the attributes associated with functions a...
static const Function * getParent(const Value *V)
#define X(NUM, ENUM, NAME)
Definition ELF.h:857
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static bool sinkAndCmp0Expression(Instruction *AndI, const TargetLowering &TLI, SetOfInstrs &InsertedInsts)
Duplicate and sink the given 'and' instruction into user blocks where it is used in a compare to allo...
static bool SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI, DenseMap< BasicBlock *, BinaryOperator * > &InsertedShifts, const TargetLowering &TLI, const DataLayout &DL)
Sink both shift and truncate instruction to the use of truncate's BB.
static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP, SmallVectorImpl< Value * > &OffsetV)
static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V)
Check if V (an operand of a select instruction) is an expensive instruction that is only used once.
static bool isExtractBitsCandidateUse(Instruction *User)
Check if the candidates could be combined with a shift instruction, which includes:
static cl::opt< unsigned > MaxAddressUsersToScan("cgp-max-address-users-to-scan", cl::init(100), cl::Hidden, cl::desc("Max number of address users to look at"))
static bool optimizeBitCast(BitCastInst *BCI, const TargetLowering &TLI, const DataLayout &DL)
Hoists bitcasts to the source block to reduce register pressure.
static cl::opt< bool > OptimizePhiTypes("cgp-optimize-phi-types", cl::Hidden, cl::init(true), cl::desc("Enable converting phi types in CodeGenPrepare"))
static cl::opt< bool > DisableStoreExtract("disable-cgp-store-extract", cl::Hidden, cl::init(false), cl::desc("Disable store(extract) optimizations in CodeGenPrepare"))
static bool foldFCmpToFPClassTest(CmpInst *Cmp, const TargetLowering &TLI, const DataLayout &DL)
static cl::opt< bool > ProfileUnknownInSpecialSection("profile-unknown-in-special-section", cl::Hidden, cl::desc("In profiling mode like sampleFDO, if a function doesn't have " "profile, we cannot tell the function is cold for sure because " "it may be a function newly added without ever being sampled. " "With the flag enabled, compiler can put such profile unknown " "functions into a special section, so runtime system can choose " "to handle it in a different way than .text section, to save " "RAM for example. "))
static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI, const TargetLowering &TLI, const DataLayout &DL)
Sink the shift right instruction into user blocks if the uses could potentially be combined with this...
static cl::opt< bool > DisableExtLdPromotion("disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false), cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in " "CodeGenPrepare"))
static cl::opt< bool > DisablePreheaderProtect("disable-preheader-prot", cl::Hidden, cl::init(false), cl::desc("Disable protection against removing loop preheaders"))
static cl::opt< bool > AddrSinkCombineBaseOffs("addr-sink-combine-base-offs", cl::Hidden, cl::init(true), cl::desc("Allow combining of BaseOffs field in Address sinking."))
static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI, const DataLayout &DL)
If the specified cast instruction is a noop copy (e.g.
static bool splitMergedValStore(StoreInst &SI, const DataLayout &DL, const TargetLowering &TLI)
For the instruction sequence of store below, F and I values are bundled together as an i64 value befo...
static bool SinkCast(CastInst *CI)
Sink the specified cast instruction into its user blocks.
static bool swapICmpOperandsToExposeCSEOpportunities(CmpInst *Cmp)
Many architectures use the same instruction for both subtract and cmp.
static cl::opt< bool > AddrSinkCombineBaseReg("addr-sink-combine-base-reg", cl::Hidden, cl::init(true), cl::desc("Allow combining of BaseReg field in Address sinking."))
static bool FindAllMemoryUses(Instruction *I, SmallVectorImpl< std::pair< Use *, Type * > > &MemoryUses, SmallPtrSetImpl< Instruction * > &ConsideredInsts, const TargetLowering &TLI, const TargetRegisterInfo &TRI, bool OptSize, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI, unsigned &SeenInsts)
Recursively walk all the uses of I until we find a memory use.
static cl::opt< bool > StressStoreExtract("stress-cgp-store-extract", cl::Hidden, cl::init(false), cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"))
static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI, const TargetLowering *TLI, SelectInst *SI)
Returns true if a SelectInst should be turned into an explicit branch.
static std::optional< std::pair< Instruction *, Constant * > > getIVIncrement(const PHINode *PN, const LoopInfo *LI)
If given PN is an inductive variable with value IVInc coming from the backedge, and on each iteration...
static cl::opt< bool > AddrSinkCombineBaseGV("addr-sink-combine-base-gv", cl::Hidden, cl::init(true), cl::desc("Allow combining of BaseGV field in Address sinking."))
static cl::opt< bool > AddrSinkUsingGEPs("addr-sink-using-gep", cl::Hidden, cl::init(true), cl::desc("Address sinking in CGP using GEPs."))
static Value * getTrueOrFalseValue(SelectInst *SI, bool isTrue, const SmallPtrSet< const Instruction *, 2 > &Selects)
If isTrue is true, return the true value of SI, otherwise return false value of SI.
static cl::opt< bool > DisableBranchOpts("disable-cgp-branch-opts", cl::Hidden, cl::init(false), cl::desc("Disable branch optimizations in CodeGenPrepare"))
static cl::opt< bool > EnableTypePromotionMerge("cgp-type-promotion-merge", cl::Hidden, cl::desc("Enable merging of redundant sexts when one is dominating" " the other."), cl::init(true))
static cl::opt< bool > ProfileGuidedSectionPrefix("profile-guided-section-prefix", cl::Hidden, cl::init(true), cl::desc("Use profile info to add section prefix for hot/cold functions"))
static cl::opt< unsigned > HugeFuncThresholdInCGPP("cgpp-huge-func", cl::init(10000), cl::Hidden, cl::desc("Least BB number of huge function."))
static cl::opt< bool > AddrSinkNewSelects("addr-sink-new-select", cl::Hidden, cl::init(true), cl::desc("Allow creation of selects in Address sinking."))
static bool foldURemOfLoopIncrement(Instruction *Rem, const DataLayout *DL, const LoopInfo *LI, SmallPtrSet< BasicBlock *, 32 > &FreshBBs, bool IsHuge)
static bool optimizeBranch(CondBrInst *Branch, const TargetLowering &TLI, SmallPtrSet< BasicBlock *, 32 > &FreshBBs, bool IsHugeFunc)
static bool tryUnmergingGEPsAcrossIndirectBr(GetElementPtrInst *GEPI, const TargetTransformInfo *TTI)
static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal, const TargetLowering &TLI, const TargetRegisterInfo &TRI)
Check to see if all uses of OpVal by the specified inline asm call are due to memory operands.
static bool isIntrinsicOrLFToBeTailCalled(const TargetLibraryInfo *TLInfo, const CallInst *CI)
static void replaceAllUsesWith(Value *Old, Value *New, SmallPtrSet< BasicBlock *, 32 > &FreshBBs, bool IsHuge)
Replace all old uses with new ones, and push the updated BBs into FreshBBs.
static cl::opt< bool > ForceSplitStore("force-split-store", cl::Hidden, cl::init(false), cl::desc("Force store splitting no matter what the target query says."))
static bool matchOverflowPattern(Instruction *&I, ExtractValueInst *&MulExtract, ExtractValueInst *&OverflowExtract)
static void computeBaseDerivedRelocateMap(const SmallVectorImpl< GCRelocateInst * > &AllRelocateCalls, MapVector< GCRelocateInst *, SmallVector< GCRelocateInst *, 0 > > &RelocateInstMap)
static bool simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase, const SmallVectorImpl< GCRelocateInst * > &Targets)
static cl::opt< bool > AddrSinkCombineScaledReg("addr-sink-combine-scaled-reg", cl::Hidden, cl::init(true), cl::desc("Allow combining of ScaledReg field in Address sinking."))
static bool foldICmpWithDominatingICmp(CmpInst *Cmp, const TargetLowering &TLI)
For pattern like:
static bool MightBeFoldableInst(Instruction *I)
This is a little filter, which returns true if an addressing computation involving I might be folded ...
static bool matchIncrement(const Instruction *IVInc, Instruction *&LHS, Constant *&Step)
static cl::opt< bool > EnableGEPOffsetSplit("cgp-split-large-offset-gep", cl::Hidden, cl::init(true), cl::desc("Enable splitting large offset of GEP."))
static cl::opt< bool > DisableComplexAddrModes("disable-complex-addr-modes", cl::Hidden, cl::init(false), cl::desc("Disables combining addressing modes with different parts " "in optimizeMemoryInst."))
static cl::opt< bool > EnableICMP_EQToICMP_ST("cgp-icmp-eq2icmp-st", cl::Hidden, cl::init(false), cl::desc("Enable ICMP_EQ to ICMP_S(L|G)T conversion."))
static cl::opt< bool > VerifyBFIUpdates("cgp-verify-bfi-updates", cl::Hidden, cl::init(false), cl::desc("Enable BFI update verification for " "CodeGenPrepare."))
static cl::opt< bool > BBSectionsGuidedSectionPrefix("bbsections-guided-section-prefix", cl::Hidden, cl::init(true), cl::desc("Use the basic-block-sections profile to determine the text " "section prefix for hot functions. Functions with " "basic-block-sections profile will be placed in `.text.hot` " "regardless of their FDO profile info. Other functions won't be " "impacted, i.e., their prefixes will be decided by FDO/sampleFDO " "profiles."))
static bool isRemOfLoopIncrementWithLoopInvariant(Instruction *Rem, const LoopInfo *LI, Value *&RemAmtOut, Value *&AddInstOut, Value *&AddOffsetOut, PHINode *&LoopIncrPNOut)
static bool isIVIncrement(const Value *V, const LoopInfo *LI)
static cl::opt< bool > DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false), cl::desc("Disable GC optimizations in CodeGenPrepare"))
static bool GEPSequentialConstIndexed(GetElementPtrInst *GEP)
static void DbgInserterHelper(DbgVariableRecord *DVR, BasicBlock::iterator VI)
static bool isPromotedInstructionLegal(const TargetLowering &TLI, const DataLayout &DL, Value *Val)
Check whether or not Val is a legal instruction for TLI.
static cl::opt< uint64_t > FreqRatioToSkipMerge("cgp-freq-ratio-to-skip-merge", cl::Hidden, cl::init(2), cl::desc("Skip merging empty blocks if (frequency of empty block) / " "(frequency of destination block) is greater than this ratio"))
static BasicBlock::iterator findInsertPos(Value *Addr, Instruction *MemoryInst, Value *SunkAddr)
static bool IsNonLocalValue(Value *V, BasicBlock *BB)
Return true if the specified values are defined in a different basic block than BB.
static cl::opt< bool > EnableAndCmpSinking("enable-andcmp-sinking", cl::Hidden, cl::init(true), cl::desc("Enable sinking and/cmp into branches."))
static bool despeculateCountZeros(IntrinsicInst *CountZeros, DomTreeUpdater *DTU, LoopInfo *LI, const TargetLowering *TLI, const DataLayout *DL, ModifyDT &ModifiedDT, SmallPtrSet< BasicBlock *, 32 > &FreshBBs, bool IsHugeFunc)
If counting leading or trailing zeros is an expensive operation and a zero input is defined,...
static bool sinkCmpExpression(CmpInst *Cmp, const TargetLowering &TLI, const DataLayout &DL)
Sink the given CmpInst into user blocks to reduce the number of virtual registers that must be create...
static bool hasSameExtUse(Value *Val, const TargetLowering &TLI)
Check if all the uses of Val are equivalent (or free) zero or sign extensions.
static cl::opt< bool > StressExtLdPromotion("stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false), cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) " "optimization in CodeGenPrepare"))
static bool matchUAddWithOverflowConstantEdgeCases(CmpInst *Cmp, BinaryOperator *&Add)
Match special-case patterns that check for unsigned add overflow.
static cl::opt< bool > DisableSelectToBranch("disable-cgp-select2branch", cl::Hidden, cl::init(false), cl::desc("Disable select to branch conversion."))
static cl::opt< bool > DisableDeletePHIs("disable-cgp-delete-phis", cl::Hidden, cl::init(false), cl::desc("Disable elimination of dead PHI nodes."))
static cl::opt< bool > AddrSinkNewPhis("addr-sink-new-phis", cl::Hidden, cl::init(false), cl::desc("Allow creation of Phis in Address sinking."))
Defines an IR pass for CodeGen Prepare.
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:678
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static cl::opt< OutputCostKind > CostKind("cost-kind", cl::desc("Target cost kind"), cl::init(OutputCostKind::RecipThroughput), cl::values(clEnumValN(OutputCostKind::RecipThroughput, "throughput", "Reciprocal throughput"), clEnumValN(OutputCostKind::Latency, "latency", "Instruction latency"), clEnumValN(OutputCostKind::CodeSize, "code-size", "Code size"), clEnumValN(OutputCostKind::SizeAndLatency, "size-latency", "Code size and latency"), clEnumValN(OutputCostKind::All, "all", "Print all cost kinds")))
This file declares the LLVM IR specialization of the GenericCycle templates.
This file defines the DenseMap class.
static bool runOnFunction(Function &F, bool PostInlining)
#define DEBUG_TYPE
static Value * getCondition(Instruction *I)
Hexagon Common GEP
IRTranslator LLVM IR MI
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Module.h This file contains the declarations for the Module class.
This defines the Use class.
iv users
Definition IVUsers.cpp:48
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static void eraseInstruction(Instruction &I, ICFLoopSafetyInfo &SafetyInfo, MemorySSAUpdater &MSSAU)
Definition LICM.cpp:1546
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Register const TargetRegisterInfo * TRI
This file implements a map that provides insertion order iteration.
uint64_t IntrinsicInst * II
OptimizedStructLayoutField Field
#define P(N)
ppc ctr loops verify
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
This file defines the PointerIntPair class.
This file contains the declarations for profiling metadata utility functions.
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
const SmallVectorImpl< MachineOperand > & Cond
static DominatorTree getDomTree(Function &F)
static bool dominates(InstrPosIndexes &PosIndexes, const MachineInstr &A, const MachineInstr &B)
Remove Loads Into Fake Uses
This file contains some templates that are useful if you are working with the STL at all.
static bool optimizeBlock(BasicBlock &BB, bool &ModifiedDT, const TargetTransformInfo &TTI, const DataLayout &DL, bool HasBranchDivergence, DomTreeUpdater *DTU)
static bool optimizeCallInst(CallInst *CI, bool &ModifiedDT, const TargetTransformInfo &TTI, const DataLayout &DL, bool HasBranchDivergence, DomTreeUpdater *DTU)
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
static bool canCombine(MachineBasicBlock &MBB, MachineOperand &MO, unsigned CombineOpc=0)
This file describes how to lower LLVM code to machine code.
static cl::opt< bool > DisableSelectOptimize("disable-select-optimize", cl::init(true), cl::Hidden, cl::desc("Disable the select-optimization pass from running"))
Disable the select optimization pass.
Target-Independent Code Generator Pass Configuration Options pass.
This pass exposes codegen information to IR-level passes.
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
static Constant * getConstantVector(MVT VT, ArrayRef< APInt > Bits, const APInt &Undefs, LLVMContext &C)
Value * RHS
Value * LHS
BinaryOperator * Mul
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1056
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1187
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:377
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:326
bool isSignedIntN(unsigned N) const
Check if this APInt has an N-bits signed integer value.
Definition APInt.h:432
unsigned getSignificantBits() const
Get the minimum bit size for this signed APInt.
Definition APInt.h:1552
unsigned logBase2() const
Definition APInt.h:1782
LLVM_ABI APInt sext(unsigned width) const
Sign extend to a new width.
Definition APInt.cpp:1029
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:437
int64_t getSExtValue() const
Get sign extended value.
Definition APInt.h:1583
LLVM_ABI bool isStaticAlloca() const
Return true if this alloca is in the entry block of the function and is a constant size.
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
LLVM_ABI std::optional< TypeSize > getAllocationSize(const DataLayout &DL) const
Get allocation size in bytes.
void setAlignment(Align Align)
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addUsedIfAvailable()
Add the specified Pass class to the set of analyses used by this pass.
AnalysisUsage & addRequired()
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
An instruction that atomically checks whether a specified value is in a memory location,...
static unsigned getPointerOperandIndex()
an instruction that atomically reads a memory location, combines it with another value,...
static unsigned getPointerOperandIndex()
Analysis pass providing the BasicBlockSectionsProfileReader.
LLVM_ABI bool isFunctionHot(StringRef FuncName) const
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:459
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:446
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:515
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches,...
Definition BasicBlock.h:672
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
LLVM_ABI void insertDbgRecordBefore(DbgRecord *DR, InstListType::iterator Here)
Insert a DbgRecord into a block at the position given by Here.
InstListType::const_iterator const_iterator
Definition BasicBlock.h:171
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
LLVM_ABI void moveAfter(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it right after MovePos in the function M...
LLVM_ABI InstListType::const_iterator getFirstNonPHIOrDbg(bool SkipPseudoOp=true) const
Returns a pointer to the first instruction in this block that is not a PHINode or a debug intrinsic,...
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
LLVM_ABI const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
LLVM_ABI const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
LLVM_ABI void insertDbgRecordAfter(DbgRecord *DR, Instruction *I)
Insert a DbgRecord into a block at the position given by I.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
BinaryOps getOpcode() const
Definition InstrTypes.h:409
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
This class represents a no-op cast from one type to another.
Analysis pass which computes BlockFrequencyInfo.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
LLVM_ABI void setBlockFreq(const BasicBlock *BB, BlockFrequency Freq)
LLVM_ABI BlockFrequency getBlockFreq(const BasicBlock *BB) const
getblockFreq - Return block frequency.
Analysis pass which computes BranchProbabilityInfo.
static LLVM_ABI BranchProbability getBranchProbability(uint64_t Numerator, uint64_t Denominator)
bool isInlineAsm() const
Check if this call is an inline asm statement.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
bool hasFnAttr(Attribute::AttrKind Kind) const
Determine whether this call has the given attribute.
Value * getArgOperand(unsigned i) const
void setArgOperand(unsigned i, Value *v)
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
This class represents a function call, abstracting a target machine's calling convention.
This is the base class for all instructions that perform data casts.
Definition InstrTypes.h:512
static LLVM_ABI CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
This class is the base class for the comparison instructions.
Definition InstrTypes.h:728
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition InstrTypes.h:890
static LLVM_ABI CmpInst * Create(OtherOps Op, Predicate Pred, Value *S1, Value *S2, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Construct a compare instruction, given the opcode, the predicate and the two operands.
Predicate getPredicate() const
Return the predicate for this instruction.
Definition InstrTypes.h:828
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Conditional Branch instruction.
static LLVM_ABI Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI Constant * getNeg(Constant *C, bool HasNSW=false)
This is the shared class of boolean and integer constants.
Definition Constants.h:87
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:135
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition Constants.h:219
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
int64_t getSExtValue() const
Return the constant as a 64-bit integer value after it has been sign extended as appropriate for the ...
Definition Constants.h:174
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
static LLVM_ABI Constant * getSplat(ElementCount EC, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
Definition Constant.h:43
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
LLVM_ABI void removeFromParent()
Record of a variable value-assignment, aka a non instruction representation of the dbg....
LocationType Type
Classification of the debug-info record that this DbgVariableRecord represents.
LLVM_ABI void replaceVariableLocationOp(Value *OldValue, Value *NewValue, bool AllowEmpty=false)
LLVM_ABI iterator_range< location_op_iterator > location_ops() const
Get the locations corresponding to the variable referenced by the debug info intrinsic.
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:223
bool erase(const KeyT &Val)
Definition DenseMap.h:377
unsigned size() const
Definition DenseMap.h:172
iterator end()
Definition DenseMap.h:141
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:284
LLVM_ABI void deleteBB(BasicBlock *DelBB)
Delete DelBB.
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
Legacy analysis pass which computes a DominatorTree.
Definition Dominators.h:277
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
This instruction extracts a struct member or array element value from an aggregate value.
iterator_range< idx_iterator > indices() const
This instruction compares its operands according to the predicate given to the constructor.
bool none() const
Definition FMF.h:57
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:867
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
const BasicBlock & getEntryBlock() const
Definition Function.h:794
LLVM_ABI const Value * getStatepoint() const
The statepoint with which this gc.relocate is associated.
Represents calls to the gc.relocate intrinsic.
unsigned getBasePtrIndex() const
The index into the associate statepoint's argument list which contains the base pointer of the pointe...
void compute(FunctionT &F)
Compute the cycle info for a function.
DomTreeT & getDomTree()
Flush DomTree updates and return DomTree.
void applyUpdates(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
void flush()
Apply all pending updates to available trees and flush all BasicBlocks awaiting deletion.
bool isBBPendingDeletion(BasicBlockT *DelBB) const
Returns true if DelBB is awaiting deletion.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
static LLVM_ABI Type * getIndexedType(Type *Ty, ArrayRef< Value * > IdxList)
Returns the result type of a getelementptr with the given source element type and indexes.
LLVM_ABI bool canIncreaseAlignment() const
Returns true if the alignment of the value can be unilaterally increased.
Definition Globals.cpp:422
bool isThreadLocal() const
If the value is "Thread Local", its value isn't shared by the threads.
LLVM_ABI uint64_t getGlobalSize(const DataLayout &DL) const
Get the size of this global variable in bytes.
Definition Globals.cpp:640
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalVariable.
This instruction compares its operands according to the predicate given to the constructor.
bool isEquality() const
Return true if this predicate is either EQ or NE.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2910
LLVM_ABI Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following:
LLVM_ABI void removeFromParent()
This method unlinks 'this' from the containing basic block, but does not delete it.
LLVM_ABI bool isDebugOrPseudoInst() const LLVM_READONLY
Return true if the instruction is a DbgInfoIntrinsic or PseudoProbeInst.
LLVM_ABI void setHasNoSignedWrap(bool b=true)
Set or clear the nsw flag on this instruction, which must be an operator which supports this flag.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI void moveAfter(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
bool hasMetadata() const
Return true if this instruction has any metadata attached to it.
LLVM_ABI void moveBefore(InstListType::iterator InsertPos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
bool isEHPad() const
Return true if the instruction is a variety of EH-block.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Instruction * user_back()
Specialize the methods defined in Value, as we know that an instruction can only be used by other ins...
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
LLVM_ABI bool mayHaveSideEffects() const LLVM_READONLY
Return true if the instruction may have side effects.
LLVM_ABI bool comesBefore(const Instruction *Other) const
Given an instruction Other in the same basic block as this instruction, return true if this instructi...
LLVM_ABI bool mayReadFromMemory() const LLVM_READONLY
Return true if this instruction may read memory.
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
LLVM_ABI FastMathFlags getFastMathFlags() const LLVM_READONLY
Convenience function for getting all the fast-math flags, which must be an operator which supports th...
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
bool isShift() const
LLVM_ABI void dropPoisonGeneratingFlags()
Drops flags that may cause this instruction to evaluate to poison despite having non-poison inputs.
LLVM_ABI std::optional< simple_ilist< DbgRecord >::iterator > getDbgReinsertionPosition()
Return an iterator to the position of the "Next" DbgRecord after this instruction,...
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI void copyMetadata(const Instruction &SrcInst, ArrayRef< unsigned > WL=ArrayRef< unsigned >())
Copy metadata from SrcInst to this instruction.
LLVM_ABI void insertAfter(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately after the specified instruction.
A wrapper class for inspecting calls to intrinsic functions.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
An instruction for reading from memory.
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:594
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
The legacy pass manager's analysis pass to compute loop information.
Definition LoopInfo.h:619
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
static MVT getIntegerVT(unsigned BitWidth)
LLVM_ABI void replacePhiUsesWith(MachineBasicBlock *Old, MachineBasicBlock *New)
Update all phi nodes in this basic block to refer to basic block New instead of basic block Old.
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:38
iterator find(const KeyT &Key)
Definition MapVector.h:156
iterator end()
Definition MapVector.h:69
bool empty() const
Definition MapVector.h:79
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition MapVector.h:126
VectorType::iterator erase(typename VectorType::iterator Iterator)
Remove the element given by Iterator.
Definition MapVector.h:210
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
op_range incoming_values()
Value * getIncomingValueForBlock(const BasicBlock *BB) const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
PointerIntPair - This class implements a pair of a pointer and small integer.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:132
An analysis pass based on the new PM to deliver ProfileSummaryInfo.
An analysis pass based on legacy pass manager to deliver ProfileSummaryInfo.
Analysis providing profile information.
Value * getReturnValue() const
Convenience accessor. Returns null if there is no return value.
This class represents the LLVM 'select' instruction.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, const Instruction *MDFrom=nullptr)
size_type count(const_arg_type key) const
Count the number of elements of a given key in the SetVector.
Definition SetVector.h:268
void clear()
Completely clear the SetVector.
Definition SetVector.h:273
bool empty() const
Determine if the SetVector is empty or not.
Definition SetVector.h:100
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
value_type pop_back_val()
Definition SetVector.h:285
VectorType * getType() const
Overload to return most specific vector type.
size_type size() const
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
bool erase(PtrType Ptr)
Remove pointer from the set.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
void insert_range(Range &&R)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition SmallSet.h:176
bool erase(const T &V)
Definition SmallSet.h:200
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
iterator erase(const_iterator CI)
typename SuperClass::iterator iterator
void resize(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
static unsigned getPointerOperandIndex()
TypeSize getElementOffset(unsigned Idx) const
Definition DataLayout.h:774
Analysis pass providing the TargetTransformInfo.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
LibFunc getLibFunc(StringRef funcName) const
Searches for a particular function name.
int InstructionOpcodeToISD(unsigned Opcode) const
Get the ISD node that corresponds to the Instruction class opcode.
EVT getValueType(const DataLayout &DL, Type *Ty, bool AllowUnknown=false) const
Return the EVT corresponding to this LLVM type.
virtual bool isSelectSupported(SelectSupportKind) const
virtual bool isEqualityCmpFoldedWithSignedCmp() const
Return true if instruction generated for equality comparison is folded with instruction generated for...
virtual bool shouldFormOverflowOp(unsigned Opcode, EVT VT, bool MathUsed) const
Try to convert math with an overflow comparison into the corresponding DAG node operation.
virtual bool isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const
Return if the target supports combining a chain like:
virtual bool shouldOptimizeMulOverflowWithZeroHighBits(LLVMContext &Context, EVT VT) const
bool isExtLoad(const LoadInst *Load, const Instruction *Ext, const DataLayout &DL) const
Return true if Load and Ext can form an ExtLoad.
virtual bool isSExtCheaperThanZExt(EVT FromTy, EVT ToTy) const
Return true if sign-extension from FromTy to ToTy is cheaper than zero-extension.
const TargetMachine & getTargetMachine() const
virtual bool isCtpopFast(EVT VT) const
Return true if ctpop instruction is fast.
virtual bool isZExtFree(Type *FromTy, Type *ToTy) const
Return true if any actual instruction that defines a value of type FromTy implicitly zero-extends the...
bool enableExtLdPromotion() const
Return true if the target wants to use the optimization that turns ext(promotableInst1(....
virtual unsigned getNumRegisters(LLVMContext &Context, EVT VT, std::optional< MVT > RegisterVT=std::nullopt) const
Return the number of registers that this ValueType will eventually require.
virtual bool isCheapToSpeculateCttz(Type *Ty) const
Return true if it is cheap to speculate a call to intrinsic cttz.
bool isJumpExpensive() const
Return true if Flow Control is an expensive operation that should be avoided.
bool hasExtractBitsInsn() const
Return true if the target has BitExtract instructions.
virtual bool allowsMisalignedMemoryAccesses(EVT, unsigned AddrSpace=0, Align Alignment=Align(1), MachineMemOperand::Flags Flags=MachineMemOperand::MONone, unsigned *=nullptr) const
Determine if the target supports unaligned memory accesses.
bool isSlowDivBypassed() const
Returns true if target has indicated at least one type should be bypassed.
virtual bool isTruncateFree(Type *FromTy, Type *ToTy) const
Return true if it's free to truncate a value of type FromTy to type ToTy.
virtual bool hasMultipleConditionRegisters(EVT VT) const
Does the target have multiple (allocatable) condition registers that can be used to store the results...
virtual EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const
For types supported by the target, this is an identity function.
virtual MVT getPreferredSwitchConditionType(LLVMContext &Context, EVT ConditionVT) const
Returns preferred type for switch condition.
bool isCondCodeLegal(ISD::CondCode CC, MVT VT) const
Return true if the specified condition code is legal for a comparison of the specified types on this ...
virtual bool canCombineStoreAndExtract(Type *VectorTy, Value *Idx, unsigned &Cost) const
Return true if the target can combine store(extractelement VectorTy,Idx).
bool isTypeLegal(EVT VT) const
Return true if the target has native support for the specified value type.
virtual bool isFreeAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const
Returns true if a cast from SrcAS to DestAS is "cheap", such that e.g.
virtual bool shouldConsiderGEPOffsetSplit() const
bool isExtFree(const Instruction *I) const
Return true if the extension represented by I is free.
bool isOperationLegalOrCustom(unsigned Op, EVT VT, bool LegalOnly=false) const
Return true if the specified operation is legal on this target or can be made legal with custom lower...
bool isPredictableSelectExpensive() const
Return true if selects are only cheaper than branches if the branch is unlikely to be predicted right...
virtual bool isMultiStoresCheaperThanBitsMerge(EVT LTy, EVT HTy) const
Return true if it is cheaper to split the store of a merged int val from a pair of smaller values int...
virtual bool getAddrModeArguments(const IntrinsicInst *, SmallVectorImpl< Value * > &, Type *&) const
CodeGenPrepare sinks address calculations into the same BB as Load/Store instructions reading the add...
const DenseMap< unsigned int, unsigned int > & getBypassSlowDivWidths() const
Returns map of slow types for division or remainder with corresponding fast types.
virtual bool isCheapToSpeculateCtlz(Type *Ty) const
Return true if it is cheap to speculate a call to intrinsic ctlz.
virtual bool useSoftFloat() const
virtual int64_t getPreferredLargeGEPBaseOffset(int64_t MinOffset, int64_t MaxOffset) const
Return the prefered common base offset.
LegalizeTypeAction getTypeAction(LLVMContext &Context, EVT VT) const
Return how we should legalize values of this type, either it is already legal (return 'Legal') or we ...
virtual bool shouldAlignPointerArgs(CallInst *, unsigned &, Align &) const
Return true if the pointer arguments to CI should be aligned by aligning the object whose address is ...
virtual Type * shouldConvertSplatType(ShuffleVectorInst *SVI) const
Given a shuffle vector SVI representing a vector splat, return a new scalar type of size equal to SVI...
bool isLoadLegal(EVT ValVT, EVT MemVT, Align Alignment, unsigned AddrSpace, unsigned ExtType, bool Atomic) const
Return true if the specified load with extension is legal on this target.
virtual bool addressingModeSupportsTLS(const GlobalValue &) const
Returns true if the targets addressing mode can target thread local storage (TLS).
virtual bool shouldConvertPhiType(Type *From, Type *To) const
Given a set in interconnected phis of type 'From' that are loaded/stored or bitcast to type 'To',...
virtual bool isFAbsFree(EVT VT) const
Return true if an fabs operation is free to the point where it is never worthwhile to replace it with...
virtual bool preferZeroCompareBranch() const
Return true if the heuristic to prefer icmp eq zero should be used in code gen prepare.
virtual bool isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM, Type *Ty, unsigned AddrSpace, Instruction *I=nullptr) const
Return true if the addressing mode represented by AM is legal for this target, for a load/store of th...
virtual bool optimizeExtendOrTruncateConversion(Instruction *I, Loop *L, const TargetTransformInfo &TTI) const
Try to optimize extending or truncating conversion instructions (like zext, trunc,...
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
std::vector< AsmOperandInfo > AsmOperandInfoVector
virtual AsmOperandInfoVector ParseConstraints(const DataLayout &DL, const TargetRegisterInfo *TRI, const CallBase &Call) const
Split up the constraint string from the inline assembly value into the specific constraints and their...
virtual void ComputeConstraintToUse(AsmOperandInfo &OpInfo, SDValue Op, SelectionDAG *DAG=nullptr) const
Determines the constraint code and constraint type to use for the specific AsmOperandInfo,...
virtual bool mayBeEmittedAsTailCall(const CallInst *) const
Return true if the target may be able emit the call instruction as a tail call.
virtual bool isNoopAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const
Returns true if a cast between SrcAS and DestAS is a noop.
virtual const TargetSubtargetInfo * getSubtargetImpl(const Function &) const
Virtual method implemented by subclasses that returns a reference to that target's TargetSubtargetInf...
TargetOptions Options
unsigned EnableFastISel
EnableFastISel - This flag enables fast-path instruction selection which trades away generated code q...
Target-Independent Code Generator Pass Configuration Options.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
virtual const TargetLowering * getTargetLowering() const
virtual bool addrSinkUsingGEPs() const
Sink addresses into blocks using GEP instructions rather than pointer casts and arithmetic.
Wrapper pass for TargetTransformInfo.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
LLVM_ABI InstructionCost getVectorInstrCost(unsigned Opcode, Type *Val, TTI::TargetCostKind CostKind, unsigned Index=-1, const Value *Op0=nullptr, const Value *Op1=nullptr, TTI::VectorInstrContext VIC=TTI::VectorInstrContext::None) const
TargetCostKind
The kind of cost model.
@ TCK_RecipThroughput
Reciprocal throughput.
@ TCK_SizeAndLatency
The weighted sum of size and latency.
LLVM_ABI InstructionCost getIntImmCost(const APInt &Imm, Type *Ty, TargetCostKind CostKind) const
Return the expected cost of materializing for the given integer immediate of the specified type.
LLVM_ABI bool shouldConsiderAddressTypePromotion(const Instruction &I, bool &AllowPromotionWithoutCommonHeader) const
@ TCC_Basic
The cost of a typical 'add' instruction.
LLVM_ABI bool isVectorShiftByScalarCheap(Type *Ty) const
Return true if it's significantly cheaper to shift a vector by a uniform scalar than by an amount whi...
LLVM_ABI InstructionCost getArithmeticInstrCost(unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind, TTI::OperandValueInfo Opd1Info={TTI::OK_AnyValue, TTI::OP_None}, TTI::OperandValueInfo Opd2Info={TTI::OK_AnyValue, TTI::OP_None}, ArrayRef< const Value * > Args={}, const Instruction *CxtI=nullptr, const TargetLibraryInfo *TLibInfo=nullptr) const
This is an approximation of reciprocal throughput of a math/logic op.
LLVM_ABI bool isProfitableToSinkOperands(Instruction *I, SmallVectorImpl< Use * > &Ops) const
Return true if sinking I's operands to the same basic block as I is profitable, e....
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM_ABI unsigned getIntegerBitWidth() const
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:288
LLVM_ABI bool isScalableTy(SmallPtrSetImpl< const Type * > &Visited) const
Return true if this is a type whose size is a known multiple of vscale.
Definition Type.cpp:61
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:309
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:368
LLVM_ABI Type * getWithNewBitWidth(unsigned NewBitWidth) const
Given an integer or vector type, change the lane bitwidth to NewBitwidth, whilst keeping the old numb...
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:232
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
Definition Type.h:270
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:257
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:313
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition Type.h:227
BasicBlock * getSuccessor(unsigned i=0) const
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
op_range operands()
Definition User.h:267
const Use & getOperandUse(unsigned i) const
Definition User.h:220
void setOperand(unsigned i, Value *Val)
Definition User.h:212
LLVM_ABI bool replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Definition User.cpp:25
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
user_iterator user_begin()
Definition Value.h:402
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:394
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:439
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:553
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:258
iterator_range< user_iterator > users()
Definition Value.h:426
LLVM_ABI Align getPointerAlignment(const DataLayout &DL) const
Returns an alignment of the pointer value.
Definition Value.cpp:1002
LLVM_ABI bool isUsedInBasicBlock(const BasicBlock *BB) const
Check if this value is used in the specified basic block.
Definition Value.cpp:239
LLVM_ABI void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition Value.cpp:713
bool use_empty() const
Definition Value.h:346
user_iterator user_end()
Definition Value.h:410
iterator_range< use_iterator > uses()
Definition Value.h:380
void mutateType(Type *Ty)
Mutate the type of this Value to be of the specified type.
Definition Value.h:807
user_iterator_impl< User > user_iterator
Definition Value.h:391
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:400
LLVM_ABI void dump() const
Support for debugging, callable in GDB: V->dump()
bool pointsToAliveValue() const
int getNumOccurrences() const
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
constexpr bool isNonZero() const
Definition TypeSize.h:155
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
TypeSize getSequentialElementStride(const DataLayout &DL) const
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition ilist_node.h:348
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
@ Entry
Definition COFF.h:862
unsigned getAddrMode(MCInstrInfo const &MCII, MCInst const &MCI)
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
SpecificConstantMatch m_ZeroInt()
Convenience matchers for specific integer values.
AllOnesConstantMatch m_AllOnes()
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
match_bind< PHINode > m_Phi(PHINode *&PN)
Match a PHI node, capturing it if we match.
auto m_Cmp()
Matches any compare instruction and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::URem > m_URem(const LHS &L, const RHS &R)
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
BinaryOp_match< LHS, RHS, Instruction::Xor > m_Xor(const LHS &L, const RHS &R)
ap_match< APInt > m_APIntAllowPoison(const APInt *&Res)
Match APInt while allowing poison in splat vector constants.
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
bool match(Val *V, const Pattern &P)
match_bind< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
BinOpPred_match< LHS, RHS, is_right_shift_op > m_Shr(const LHS &L, const RHS &R)
Matches logical shift operations.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap, true > m_c_NUWAdd(const LHS &L, const RHS &R)
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_BinOp()
Match an arbitrary binary operation and ignore it.
ExtractValue_match< Ind, Val_t > m_ExtractValue(const Val_t &V)
Match a single index ExtractValue instruction.
auto m_Value()
Match an arbitrary value and ignore it.
auto m_Ctpop(const Opnd0 &Op0)
auto m_Constant()
Match an arbitrary Constant and ignore it.
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
TwoOps_match< V1_t, V2_t, Instruction::ShuffleVector > m_Shuffle(const V1_t &v1, const V2_t &v2)
Matches ShuffleVectorInst independently of mask value.
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
match_immconstant_ty m_ImmConstant()
Match an arbitrary immediate Constant and ignore it.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoSignedWrap > m_NSWAdd(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
UAddWithOverflow_match< LHS_t, RHS_t, Sum_t > m_UAddWithOverflow(const LHS_t &L, const RHS_t &R, const Sum_t &S)
Match an icmp instruction checking for unsigned overflow on addition.
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
brc_match< Cond_t, match_bind< BasicBlock >, match_bind< BasicBlock > > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
auto m_Undef()
Match an arbitrary undef constant.
BinaryOp_match< LHS, RHS, Instruction::Or, true > m_c_Or(const LHS &L, const RHS &R)
Matches an Or with LHS and RHS in either order.
ThreeOps_match< Val_t, Elt_t, Idx_t, Instruction::InsertElement > m_InsertElt(const Val_t &Val, const Elt_t &Elt, const Idx_t &Idx)
Matches InsertElementInst.
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
int compare(DigitsT LDigits, int16_t LScale, DigitsT RDigits, int16_t RScale)
Compare two scaled numbers.
@ CE
Windows NT (Windows on ARM)
Definition MCAsmInfo.h:51
initializer< Ty > init(const Ty &Val)
DXILDebugInfoMap run(Module &M)
@ User
could "use" a pointer
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
SmallVector< Node, 4 > NodeList
Definition RDFGraph.h:550
iterator end() const
Definition BasicBlock.h:89
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
LLVM_ABI iterator begin() const
BaseReg
Stack frame base register. Bit 0 of FREInfo.Info.
Definition SFrame.h:77
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:315
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
@ Offset
Definition DWP.cpp:577
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1765
LLVM_ABI bool RemoveRedundantDbgInstrs(BasicBlock *BB)
Try to remove redundant dbg.value instructions from given basic block.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1739
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1669
LLVM_ABI bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
If the specified value is a trivially dead instruction, delete it.
Definition Local.cpp:522
LLVM_ABI bool ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions=false, const TargetLibraryInfo *TLI=nullptr, DomTreeUpdater *DTU=nullptr)
If a terminator instruction is predicated on a constant value, convert it into an unconditional branc...
Definition Local.cpp:133
LLVM_ABI bool bypassSlowDivision(BasicBlock *BB, const DenseMap< unsigned int, unsigned int > &BypassWidth, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BranchProbabilityInfo *BPI=nullptr)
This optimization identifies DIV instructions in a BB that can be profitably bypassed and carried out...
LLVM_ABI void findDbgValues(Value *V, SmallVectorImpl< DbgVariableRecord * > &DbgVariableRecords)
Finds the dbg.values describing a value.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
APInt operator*(APInt a, uint64_t RHS)
Definition APInt.h:2262
bool isAligned(Align Lhs, uint64_t SizeInBytes)
Checks that SizeInBytes is a multiple of the alignment.
Definition Alignment.h:134
LLVM_ABI void salvageDebugInfo(const MachineRegisterInfo &MRI, MachineInstr &MI)
Assuming the instruction MI is going to be deleted, attempt to salvage debug users of MI by writing t...
Definition Utils.cpp:1675
auto successors(const MachineBasicBlock *BB)
@ Load
The value being inserted comes from a load (InsertElement only).
OuterAnalysisManagerProxy< ModuleAnalysisManager, Function > ModuleAnalysisManagerFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
LLVM_ABI ReturnInst * FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB, BasicBlock *Pred, DomTreeUpdater *DTU=nullptr)
This method duplicates the specified return instruction into a predecessor which ends in an unconditi...
bool operator!=(uint64_t V1, const APInt &V2)
Definition APInt.h:2140
constexpr from_range_t from_range
LLVM_ABI BasicBlock * splitBlockBefore(BasicBlock *Old, BasicBlock::iterator SplitPt, DomTreeUpdater *DTU, LoopInfo *LI, MemorySSAUpdater *MSSAU, const Twine &BBName="")
Split the specified block at the specified instruction SplitPt.
LLVM_ABI Instruction * SplitBlockAndInsertIfElse(Value *Cond, BasicBlock::iterator SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BasicBlock *ElseBlock=nullptr)
Similar to SplitBlockAndInsertIfThen, but the inserted block is on the false path of the branch.
LLVM_ABI bool SplitIndirectBrCriticalEdges(Function &F, bool IgnoreBlocksWithoutPHI, BranchProbabilityInfo *BPI=nullptr, BlockFrequencyInfo *BFI=nullptr, DomTreeUpdater *DTU=nullptr)
LLVM_ABI bool DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, SmallPtrSetImpl< PHINode * > *KnownNonDeadPHIs=nullptr)
Examine each PHI in the given block and delete it if it is dead.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2208
LLVM_ABI bool shouldOptimizeForSize(const MachineFunction *MF, ProfileSummaryInfo *PSI, const MachineBlockFrequencyInfo *BFI, PGSOQueryType QueryType=PGSOQueryType::Other)
Returns true if machine function MF is suggested to be size-optimized based on the profile.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:633
constexpr std::enable_if_t< std::is_signed_v< T >, std::pair< T, bool > > AddOverflow(T X, T Y)
Add two signed integers, computing the two's complement truncated result, returning a pair {result,...
Definition MathExtras.h:698
LLVM_ABI void DeleteDeadBlock(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, bool KeepOneInputPHIs=false)
Delete the specified block, which must have no predecessors.
LLVM_ABI bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true, bool IgnoreUBImplyingAttrs=true)
Return true if the instruction does not have any effects besides calculating the result and does not ...
auto unique(Range &&R, Predicate P)
Definition STLExtras.h:2134
LLVM_ABI Value * getSplatValue(const Value *V)
Get splat value if the input is a splat vector or return nullptr.
LLVM_ABI bool hasBranchWeightOrigin(const Instruction &I)
Check if Branch Weight Metadata has an "expected" field from an llvm.expect* intrinsic.
constexpr auto equal_to(T &&Arg)
Functor variant of std::equal_to that can be used as a UnaryPredicate in functional algorithms like a...
Definition STLExtras.h:2173
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
constexpr int popcount(T Value) noexcept
Count the number of set bits in a value.
Definition bit.h:156
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
LLVM_ABI Value * simplifyAddInst(Value *LHS, Value *RHS, bool IsNSW, bool IsNUW, const SimplifyQuery &Q)
Given operands for an Add, fold the result or return null.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
Align getKnownAlignment(Value *V, const DataLayout &DL, const Instruction *CxtI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr)
Try to infer an alignment for the specified pointer.
Definition Local.h:240
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
Definition STLExtras.h:2200
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1746
LLVM_ABI bool isSplatValue(const Value *V, int Index=-1, unsigned Depth=0)
Return true if each element of the vector value V is poisoned or equal to every other non-poisoned el...
LLVM_ABI bool replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV, const TargetLibraryInfo *TLI=nullptr, const DominatorTree *DT=nullptr, AssumptionCache *AC=nullptr, SmallSetVector< Instruction *, 8 > *UnsimplifiedUsers=nullptr)
Replace all uses of 'I' with 'SimpleV' and simplify the uses recursively.
auto reverse(ContainerTy &&C)
Definition STLExtras.h:407
LLVM_ABI bool recognizeBSwapOrBitReverseIdiom(Instruction *I, bool MatchBSwaps, bool MatchBitReversals, SmallVectorImpl< Instruction * > &InsertedInsts)
Try to match a bswap or bitreverse idiom.
Definition Local.cpp:3788
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1636
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
LLVM_ABI void SplitBlockAndInsertIfThenElse(Value *Cond, BasicBlock::iterator SplitBefore, Instruction **ThenTerm, Instruction **ElseTerm, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr)
SplitBlockAndInsertIfThenElse is similar to SplitBlockAndInsertIfThen, but also creates the ElseBlock...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1753
auto make_first_range(ContainerTy &&c)
Given a container of pairs, return a range over the first elements.
Definition STLExtras.h:1399
generic_gep_type_iterator<> gep_type_iterator
LLVM_ABI FunctionPass * createCodeGenPrepareLegacyPass()
createCodeGenPrepareLegacyPass - Transform the code to expose more pattern matching during instructio...
LLVM_ABI ISD::CondCode getFCmpCondCode(FCmpInst::Predicate Pred)
getFCmpCondCode - Return the ISD condition code corresponding to the given LLVM IR floating-point con...
Definition Analysis.cpp:203
LLVM_ABI bool VerifyLoopInfo
Enable verification of loop info.
Definition LoopInfo.cpp:53
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
LLVM_ABI bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
LLVM_ABI bool attributesPermitTailCall(const Function *F, const Instruction *I, const ReturnInst *Ret, const TargetLoweringBase &TLI, bool *AllowDifferingSizes=nullptr)
Test if given that the input instruction is in the tail call position, if there is an attribute misma...
Definition Analysis.cpp:588
TargetTransformInfo TTI
IRBuilder(LLVMContext &, FolderTy, InserterTy, MDNode *, ArrayRef< OperandBundleDef >) -> IRBuilder< FolderTy, InserterTy >
LLVM_ABI bool MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, MemoryDependenceResults *MemDep=nullptr, bool PredecessorWithTwoSuccessors=false, DominatorTree *DT=nullptr)
Attempts to merge a block into its predecessor, if possible.
@ Or
Bitwise or logical OR of integers.
@ Xor
Bitwise or logical XOR of integers.
@ And
Bitwise or logical AND of integers.
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
LLVM_ABI BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction.
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition STLExtras.h:2012
IntPtrTy
Definition InstrProf.h:82
DWARFExpression::Operation Op
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Return true if this function can prove that V does not have undef bits and is never poison.
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI bool VerifyDomInfo
Enables verification of dominator trees.
constexpr unsigned BitWidth
LLVM_ABI bool extractBranchWeights(const MDNode *ProfileData, SmallVectorImpl< uint32_t > &Weights)
Extract branch weights from MD_prof metadata.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
gep_type_iterator gep_type_begin(const User *GEP)
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2192
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition Alignment.h:201
constexpr std::enable_if_t< std::is_signed_v< T >, std::pair< T, bool > > MulOverflow(T X, T Y)
Multiply two signed integers, computing the two's complement truncated result, returning a pair {resu...
Definition MathExtras.h:772
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
bool pred_empty(const BasicBlock *BB)
Definition CFG.h:107
LLVM_ABI Instruction * SplitBlockAndInsertIfThen(Value *Cond, BasicBlock::iterator SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI BasicBlock * SplitEdge(BasicBlock *From, BasicBlock *To, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the edge connecting the specified blocks, and return the newly created basic block between From...
LLVM_ABI void setFittedBranchWeights(Instruction &I, ArrayRef< uint64_t > Weights, bool IsExpected, bool ElideAllZero=false)
Variant of setBranchWeights where the Weights will be fit first to uint32_t by shifting right.
std::pair< Value *, FPClassTest > fcmpToClassTest(FCmpInst::Predicate Pred, const Function &F, Value *LHS, Value *RHS, bool LookThroughSrc=true)
Returns a pair of values, which if passed to llvm.is.fpclass, returns the same result as an fcmp with...
static auto filterDbgVars(iterator_range< simple_ilist< DbgRecord >::iterator > R)
Filter the DbgRecord range to DbgVariableRecord types only and downcast.
LLVM_ABI Value * simplifyURemInst(Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for a URem, fold the result or return null.
DenseMap< const Value *, Value * > ValueToValueMap
LLVM_ABI CGPassBuilderOption getCGPassBuilderOption()
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#define NC
Definition regutils.h:42
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
Extended Value Type.
Definition ValueTypes.h:35
bool bitsGT(EVT VT) const
Return true if this has more bits than VT.
Definition ValueTypes.h:307
bool bitsLT(EVT VT) const
Return true if this has less bits than VT.
Definition ValueTypes.h:323
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition ValueTypes.h:396
static LLVM_ABI EVT getEVT(Type *Ty, bool HandleUnknown=false)
Return the value type corresponding to the specified type.
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
Definition ValueTypes.h:339
bool isRound() const
Return true if the size is a power-of-two number of bytes.
Definition ValueTypes.h:271
bool isScalableVector() const
Return true if this is a vector type where the runtime length is machine dependent.
Definition ValueTypes.h:187
bool isInteger() const
Return true if this is an integer or a vector integer type.
Definition ValueTypes.h:160
This contains information for each constraint that we are lowering.