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 (Instruction::user_iterator UI = OldI->user_begin(),
1133 E = OldI->user_end();
1134 UI != E; ++UI) {
1136 if (IsHuge)
1137 FreshBBs.insert(User->getParent());
1138 }
1139 }
1140 Old->replaceAllUsesWith(New);
1141}
1142
1143/// Eliminate a basic block that has only phi's and an unconditional branch in
1144/// it.
1145/// Indicate that the LoopInfo was modified only if it wasn't updated.
1146bool CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
1147 UncondBrInst *BI = cast<UncondBrInst>(BB->getTerminator());
1148 BasicBlock *DestBB = BI->getSuccessor();
1149
1150 LLVM_DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n"
1151 << *BB << *DestBB);
1152
1153 // If the destination block has a single pred, then this is a trivial edge,
1154 // just collapse it.
1155 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
1156 if (SinglePred != DestBB) {
1157 assert(SinglePred == BB &&
1158 "Single predecessor not the same as predecessor");
1159 // Merge DestBB into SinglePred/BB and delete it.
1160 MergeBlockIntoPredecessor(DestBB, DTU, LI);
1161 // Note: BB(=SinglePred) will not be deleted on this path.
1162 // DestBB(=its single successor) is the one that was deleted.
1163 LLVM_DEBUG(dbgs() << "AFTER:\n" << *SinglePred << "\n\n\n");
1164
1165 if (IsHugeFunc) {
1166 // Update FreshBBs to optimize the merged BB.
1167 FreshBBs.insert(SinglePred);
1168 FreshBBs.erase(DestBB);
1169 }
1170 return false;
1171 }
1172 }
1173
1174 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
1175 // to handle the new incoming edges it is about to have.
1176 for (PHINode &PN : DestBB->phis()) {
1177 // Remove the incoming value for BB, and remember it.
1178 Value *InVal = PN.removeIncomingValue(BB, false);
1179
1180 // Two options: either the InVal is a phi node defined in BB or it is some
1181 // value that dominates BB.
1182 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
1183 if (InValPhi && InValPhi->getParent() == BB) {
1184 // Add all of the input values of the input PHI as inputs of this phi.
1185 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
1186 PN.addIncoming(InValPhi->getIncomingValue(i),
1187 InValPhi->getIncomingBlock(i));
1188 } else {
1189 // Otherwise, add one instance of the dominating value for each edge that
1190 // we will be adding.
1191 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
1192 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
1193 PN.addIncoming(InVal, BBPN->getIncomingBlock(i));
1194 } else {
1195 for (BasicBlock *Pred : predecessors(BB))
1196 PN.addIncoming(InVal, Pred);
1197 }
1198 }
1199 }
1200
1201 // Preserve loop Metadata.
1202 if (BI->hasMetadata(LLVMContext::MD_loop)) {
1203 for (auto *Pred : predecessors(BB))
1204 Pred->getTerminator()->copyMetadata(*BI, LLVMContext::MD_loop);
1205 }
1206
1207 // The PHIs are now updated, change everything that refers to BB to use
1208 // DestBB and remove BB.
1210 SmallPtrSet<BasicBlock *, 8> SeenPreds;
1211 SmallPtrSet<BasicBlock *, 8> PredOfDestBB(llvm::from_range,
1212 predecessors(DestBB));
1213 for (auto *Pred : predecessors(BB)) {
1214 if (!PredOfDestBB.contains(Pred)) {
1215 if (SeenPreds.insert(Pred).second)
1216 DTUpdates.push_back({DominatorTree::Insert, Pred, DestBB});
1217 }
1218 }
1219 SeenPreds.clear();
1220 for (auto *Pred : predecessors(BB)) {
1221 if (SeenPreds.insert(Pred).second)
1222 DTUpdates.push_back({DominatorTree::Delete, Pred, BB});
1223 }
1224 DTUpdates.push_back({DominatorTree::Delete, BB, DestBB});
1225 BB->replaceAllUsesWith(DestBB);
1226 DTU->applyUpdates(DTUpdates);
1227 DTU->deleteBB(BB);
1228 ++NumBlocksElim;
1229
1230 LLVM_DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
1231 return true;
1232}
1233
1234// Computes a map of base pointer relocation instructions to corresponding
1235// derived pointer relocation instructions given a vector of all relocate calls
1237 const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
1239 &RelocateInstMap) {
1240 // Collect information in two maps: one primarily for locating the base object
1241 // while filling the second map; the second map is the final structure holding
1242 // a mapping between Base and corresponding Derived relocate calls
1244 for (auto *ThisRelocate : AllRelocateCalls) {
1245 auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
1246 ThisRelocate->getDerivedPtrIndex());
1247 RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
1248 }
1249 for (auto &Item : RelocateIdxMap) {
1250 std::pair<unsigned, unsigned> Key = Item.first;
1251 if (Key.first == Key.second)
1252 // Base relocation: nothing to insert
1253 continue;
1254
1255 GCRelocateInst *I = Item.second;
1256 auto BaseKey = std::make_pair(Key.first, Key.first);
1257
1258 // We're iterating over RelocateIdxMap so we cannot modify it.
1259 auto MaybeBase = RelocateIdxMap.find(BaseKey);
1260 if (MaybeBase == RelocateIdxMap.end())
1261 // TODO: We might want to insert a new base object relocate and gep off
1262 // that, if there are enough derived object relocates.
1263 continue;
1264
1265 RelocateInstMap[MaybeBase->second].push_back(I);
1266 }
1267}
1268
1269// Accepts a GEP and extracts the operands into a vector provided they're all
1270// small integer constants
1272 SmallVectorImpl<Value *> &OffsetV) {
1273 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
1274 // Only accept small constant integer operands
1275 auto *Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
1276 if (!Op || Op->getZExtValue() > 20)
1277 return false;
1278 }
1279
1280 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
1281 OffsetV.push_back(GEP->getOperand(i));
1282 return true;
1283}
1284
1285// Takes a RelocatedBase (base pointer relocation instruction) and Targets to
1286// replace, computes a replacement, and affects it.
1287static bool
1289 const SmallVectorImpl<GCRelocateInst *> &Targets) {
1290 bool MadeChange = false;
1291 // We must ensure the relocation of derived pointer is defined after
1292 // relocation of base pointer. If we find a relocation corresponding to base
1293 // defined earlier than relocation of base then we move relocation of base
1294 // right before found relocation. We consider only relocation in the same
1295 // basic block as relocation of base. Relocations from other basic block will
1296 // be skipped by optimization and we do not care about them.
1297 for (auto R = RelocatedBase->getParent()->getFirstInsertionPt();
1298 &*R != RelocatedBase; ++R)
1299 if (auto *RI = dyn_cast<GCRelocateInst>(R))
1300 if (RI->getStatepoint() == RelocatedBase->getStatepoint())
1301 if (RI->getBasePtrIndex() == RelocatedBase->getBasePtrIndex()) {
1302 RelocatedBase->moveBefore(RI->getIterator());
1303 MadeChange = true;
1304 break;
1305 }
1306
1307 for (GCRelocateInst *ToReplace : Targets) {
1308 assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&
1309 "Not relocating a derived object of the original base object");
1310 if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
1311 // A duplicate relocate call. TODO: coalesce duplicates.
1312 continue;
1313 }
1314
1315 if (RelocatedBase->getParent() != ToReplace->getParent()) {
1316 // Base and derived relocates are in different basic blocks.
1317 // In this case transform is only valid when base dominates derived
1318 // relocate. However it would be too expensive to check dominance
1319 // for each such relocate, so we skip the whole transformation.
1320 continue;
1321 }
1322
1323 Value *Base = ToReplace->getBasePtr();
1324 auto *Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
1325 if (!Derived || Derived->getPointerOperand() != Base)
1326 continue;
1327
1329 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
1330 continue;
1331
1332 // Create a Builder and replace the target callsite with a gep
1333 assert(RelocatedBase->getNextNode() &&
1334 "Should always have one since it's not a terminator");
1335
1336 // Insert after RelocatedBase
1337 IRBuilder<> Builder(RelocatedBase->getNextNode());
1338 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
1339
1340 // If gc_relocate does not match the actual type, cast it to the right type.
1341 // In theory, there must be a bitcast after gc_relocate if the type does not
1342 // match, and we should reuse it to get the derived pointer. But it could be
1343 // cases like this:
1344 // bb1:
1345 // ...
1346 // %g1 = call coldcc i8 addrspace(1)*
1347 // @llvm.experimental.gc.relocate.p1i8(...) br label %merge
1348 //
1349 // bb2:
1350 // ...
1351 // %g2 = call coldcc i8 addrspace(1)*
1352 // @llvm.experimental.gc.relocate.p1i8(...) br label %merge
1353 //
1354 // merge:
1355 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
1356 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
1357 //
1358 // In this case, we can not find the bitcast any more. So we insert a new
1359 // bitcast no matter there is already one or not. In this way, we can handle
1360 // all cases, and the extra bitcast should be optimized away in later
1361 // passes.
1362 Value *ActualRelocatedBase = RelocatedBase;
1363 if (RelocatedBase->getType() != Base->getType()) {
1364 ActualRelocatedBase =
1365 Builder.CreateBitCast(RelocatedBase, Base->getType());
1366 }
1367 Value *Replacement =
1368 Builder.CreateGEP(Derived->getSourceElementType(), ActualRelocatedBase,
1369 ArrayRef(OffsetV));
1370 Replacement->takeName(ToReplace);
1371 // If the newly generated derived pointer's type does not match the original
1372 // derived pointer's type, cast the new derived pointer to match it. Same
1373 // reasoning as above.
1374 Value *ActualReplacement = Replacement;
1375 if (Replacement->getType() != ToReplace->getType()) {
1376 ActualReplacement =
1377 Builder.CreateBitCast(Replacement, ToReplace->getType());
1378 }
1379 ToReplace->replaceAllUsesWith(ActualReplacement);
1380 ToReplace->eraseFromParent();
1381
1382 MadeChange = true;
1383 }
1384 return MadeChange;
1385}
1386
1387// Turns this:
1388//
1389// %base = ...
1390// %ptr = gep %base + 15
1391// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1392// %base' = relocate(%tok, i32 4, i32 4)
1393// %ptr' = relocate(%tok, i32 4, i32 5)
1394// %val = load %ptr'
1395//
1396// into this:
1397//
1398// %base = ...
1399// %ptr = gep %base + 15
1400// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1401// %base' = gc.relocate(%tok, i32 4, i32 4)
1402// %ptr' = gep %base' + 15
1403// %val = load %ptr'
1404bool CodeGenPrepare::simplifyOffsetableRelocate(GCStatepointInst &I) {
1405 bool MadeChange = false;
1406 SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
1407 for (auto *U : I.users())
1408 if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
1409 // Collect all the relocate calls associated with a statepoint
1410 AllRelocateCalls.push_back(Relocate);
1411
1412 // We need at least one base pointer relocation + one derived pointer
1413 // relocation to mangle
1414 if (AllRelocateCalls.size() < 2)
1415 return false;
1416
1417 // RelocateInstMap is a mapping from the base relocate instruction to the
1418 // corresponding derived relocate instructions
1419 MapVector<GCRelocateInst *, SmallVector<GCRelocateInst *, 0>> RelocateInstMap;
1420 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
1421 if (RelocateInstMap.empty())
1422 return false;
1423
1424 for (auto &Item : RelocateInstMap)
1425 // Item.first is the RelocatedBase to offset against
1426 // Item.second is the vector of Targets to replace
1427 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
1428 return MadeChange;
1429}
1430
1431/// Sink the specified cast instruction into its user blocks.
1432static bool SinkCast(CastInst *CI) {
1433 BasicBlock *DefBB = CI->getParent();
1434
1435 /// InsertedCasts - Only insert a cast in each block once.
1437
1438 bool MadeChange = false;
1439 for (Instruction::user_iterator UI = CI->user_begin(), E = CI->user_end();
1440 UI != E;) {
1441 Use &TheUse = UI.getUse();
1443
1444 // Figure out which BB this cast is used in. For PHI's this is the
1445 // appropriate predecessor block.
1446 BasicBlock *UserBB = User->getParent();
1447 if (PHINode *PN = dyn_cast<PHINode>(User)) {
1448 UserBB = PN->getIncomingBlock(TheUse);
1449 }
1450
1451 // Preincrement use iterator so we don't invalidate it.
1452 ++UI;
1453
1454 // The first insertion point of a block containing an EH pad is after the
1455 // pad. If the pad is the user, we cannot sink the cast past the pad.
1456 if (User->isEHPad())
1457 continue;
1458
1459 // If the block selected to receive the cast is an EH pad that does not
1460 // allow non-PHI instructions before the terminator, we can't sink the
1461 // cast.
1462 if (UserBB->getTerminator()->isEHPad())
1463 continue;
1464
1465 // If this user is in the same block as the cast, don't change the cast.
1466 if (UserBB == DefBB)
1467 continue;
1468
1469 // If we have already inserted a cast into this block, use it.
1470 CastInst *&InsertedCast = InsertedCasts[UserBB];
1471
1472 if (!InsertedCast) {
1473 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1474 assert(InsertPt != UserBB->end());
1475 InsertedCast = cast<CastInst>(CI->clone());
1476 InsertedCast->insertBefore(*UserBB, InsertPt);
1477 }
1478
1479 // Replace a use of the cast with a use of the new cast.
1480 TheUse = InsertedCast;
1481 MadeChange = true;
1482 ++NumCastUses;
1483 }
1484
1485 // If we removed all uses, nuke the cast.
1486 if (CI->use_empty()) {
1487 salvageDebugInfo(*CI);
1488 CI->eraseFromParent();
1489 MadeChange = true;
1490 }
1491
1492 return MadeChange;
1493}
1494
1495/// Hoists bitcasts to the source block to reduce register pressure
1496static bool optimizeBitCast(BitCastInst *BCI, const TargetLowering &TLI,
1497 const DataLayout &DL) {
1498 auto *SrcInst = dyn_cast<Instruction>(BCI->getOperand(0));
1499 if (!SrcInst || SrcInst->getParent() == BCI->getParent() ||
1500 SrcInst->isTerminator())
1501 return false;
1502
1503 Type *DestTy = BCI->getType();
1504 Type *SrcTy = SrcInst->getType();
1505 EVT SrcVT = TLI.getValueType(DL, SrcTy);
1506 EVT DestVT = TLI.getValueType(DL, DestTy);
1507
1508 // Bail out on scalable vectors and illegal destination types
1509 if (SrcVT.isScalableVector() || DestVT.isScalableVector())
1510 return false;
1511
1512 // Only hoist if it reduces physical register count
1513 if (TLI.getNumRegisters(BCI->getContext(), SrcVT) <=
1514 TLI.getNumRegisters(BCI->getContext(), DestVT))
1515 return false;
1516
1517 // Block large or cross-domain scalars to prevent spills and broken atomics.
1518 bool IsCrossDomain = DestTy->isFPOrFPVectorTy() != SrcTy->isFPOrFPVectorTy();
1519
1520 // A scalar is large if it requires more than one native register.
1521 unsigned NativeWidth = DL.getPointerSizeInBits();
1522 bool IsLargeScalar =
1523 !DestTy->isVectorTy() &&
1524 DL.getTypeSizeInBits(DestTy).getFixedValue() > NativeWidth;
1525
1526 if (IsCrossDomain || IsLargeScalar)
1527 return false;
1528
1529 // Hoist the bitcast
1530 BasicBlock *SrcBB = SrcInst->getParent();
1531 auto InsertPt = isa<PHINode>(SrcInst) ? SrcBB->getFirstInsertionPt()
1532 : std::next(SrcInst->getIterator());
1533 BCI->moveBefore(*SrcBB, InsertPt);
1534
1535 return true;
1536}
1537
1538/// If the specified cast instruction is a noop copy (e.g. it's casting from
1539/// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
1540/// reduce the number of virtual registers that must be created and coalesced.
1541///
1542/// Return true if any changes are made.
1544 const DataLayout &DL) {
1545 // Sink only "cheap" (or nop) address-space casts. This is a weaker condition
1546 // than sinking only nop casts, but is helpful on some platforms.
1547 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(CI)) {
1548 if (!TLI.isFreeAddrSpaceCast(DL, ASC->getSrcAddressSpace(),
1549 ASC->getDestAddressSpace()))
1550 return false;
1551 }
1552
1553 // If this is a noop copy,
1554 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
1555 EVT DstVT = TLI.getValueType(DL, CI->getType());
1556
1557 // This is an fp<->int conversion?
1558 if (SrcVT.isInteger() != DstVT.isInteger())
1559 return false;
1560
1561 // If this is an extension, it will be a zero or sign extension, which
1562 // isn't a noop.
1563 if (SrcVT.bitsLT(DstVT))
1564 return false;
1565
1566 // If these values will be promoted, find out what they will be promoted
1567 // to. This helps us consider truncates on PPC as noop copies when they
1568 // are.
1569 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
1571 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
1572 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
1574 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
1575
1576 // If, after promotion, these are the same types, this is a noop copy.
1577 if (SrcVT != DstVT)
1578 return false;
1579
1580 return SinkCast(CI);
1581}
1582
1583// Match a simple increment by constant operation. Note that if a sub is
1584// matched, the step is negated (as if the step had been canonicalized to
1585// an add, even though we leave the instruction alone.)
1586static bool matchIncrement(const Instruction *IVInc, Instruction *&LHS,
1587 Constant *&Step) {
1588 if (match(IVInc, m_Add(m_Instruction(LHS), m_Constant(Step))) ||
1590 m_Instruction(LHS), m_Constant(Step)))))
1591 return true;
1592 if (match(IVInc, m_Sub(m_Instruction(LHS), m_Constant(Step))) ||
1594 m_Instruction(LHS), m_Constant(Step))))) {
1595 Step = ConstantExpr::getNeg(Step);
1596 return true;
1597 }
1598 return false;
1599}
1600
1601/// If given \p PN is an inductive variable with value IVInc coming from the
1602/// backedge, and on each iteration it gets increased by Step, return pair
1603/// <IVInc, Step>. Otherwise, return std::nullopt.
1604static std::optional<std::pair<Instruction *, Constant *>>
1605getIVIncrement(const PHINode *PN, const LoopInfo *LI) {
1606 const Loop *L = LI->getLoopFor(PN->getParent());
1607 if (!L || L->getHeader() != PN->getParent() || !L->getLoopLatch())
1608 return std::nullopt;
1609 auto *IVInc =
1610 dyn_cast<Instruction>(PN->getIncomingValueForBlock(L->getLoopLatch()));
1611 if (!IVInc || LI->getLoopFor(IVInc->getParent()) != L)
1612 return std::nullopt;
1613 Instruction *LHS = nullptr;
1614 Constant *Step = nullptr;
1615 if (matchIncrement(IVInc, LHS, Step) && LHS == PN)
1616 return std::make_pair(IVInc, Step);
1617 return std::nullopt;
1618}
1619
1620static bool isIVIncrement(const Value *V, const LoopInfo *LI) {
1621 auto *I = dyn_cast<Instruction>(V);
1622 if (!I)
1623 return false;
1624 Instruction *LHS = nullptr;
1625 Constant *Step = nullptr;
1626 if (!matchIncrement(I, LHS, Step))
1627 return false;
1628 if (auto *PN = dyn_cast<PHINode>(LHS))
1629 if (auto IVInc = getIVIncrement(PN, LI))
1630 return IVInc->first == I;
1631 return false;
1632}
1633
1634bool CodeGenPrepare::replaceMathCmpWithIntrinsic(BinaryOperator *BO,
1635 Value *Arg0, Value *Arg1,
1636 CmpInst *Cmp,
1637 Intrinsic::ID IID) {
1638 auto IsReplacableIVIncrement = [this, &Cmp](BinaryOperator *BO) {
1639 if (!isIVIncrement(BO, LI))
1640 return false;
1641 const Loop *L = LI->getLoopFor(BO->getParent());
1642 assert(L && "L should not be null after isIVIncrement()");
1643 // Do not risk on moving increment into a child loop.
1644 if (LI->getLoopFor(Cmp->getParent()) != L)
1645 return false;
1646
1647 // Finally, we need to ensure that the insert point will dominate all
1648 // existing uses of the increment.
1649
1650 auto &DT = getDT();
1651 if (DT.dominates(Cmp->getParent(), BO->getParent()))
1652 // If we're moving up the dom tree, all uses are trivially dominated.
1653 // (This is the common case for code produced by LSR.)
1654 return true;
1655
1656 // Otherwise, special case the single use in the phi recurrence.
1657 return BO->hasOneUse() && DT.dominates(Cmp->getParent(), L->getLoopLatch());
1658 };
1659 if (BO->getParent() != Cmp->getParent() && !IsReplacableIVIncrement(BO)) {
1660 // We used to use a dominator tree here to allow multi-block optimization.
1661 // But that was problematic because:
1662 // 1. It could cause a perf regression by hoisting the math op into the
1663 // critical path.
1664 // 2. It could cause a perf regression by creating a value that was live
1665 // across multiple blocks and increasing register pressure.
1666 // 3. Use of a dominator tree could cause large compile-time regression.
1667 // This is because we recompute the DT on every change in the main CGP
1668 // run-loop. The recomputing is probably unnecessary in many cases, so if
1669 // that was fixed, using a DT here would be ok.
1670 //
1671 // There is one important particular case we still want to handle: if BO is
1672 // the IV increment. Important properties that make it profitable:
1673 // - We can speculate IV increment anywhere in the loop (as long as the
1674 // indvar Phi is its only user);
1675 // - Upon computing Cmp, we effectively compute something equivalent to the
1676 // IV increment (despite it loops differently in the IR). So moving it up
1677 // to the cmp point does not really increase register pressure.
1678 return false;
1679 }
1680
1681 // We allow matching the canonical IR (add X, C) back to (usubo X, -C).
1682 if (BO->getOpcode() == Instruction::Add &&
1683 IID == Intrinsic::usub_with_overflow) {
1684 assert(isa<Constant>(Arg1) && "Unexpected input for usubo");
1686 }
1687
1688 // Insert at the first instruction of the pair.
1689 Instruction *InsertPt = nullptr;
1690 for (Instruction &Iter : *Cmp->getParent()) {
1691 // If BO is an XOR, it is not guaranteed that it comes after both inputs to
1692 // the overflow intrinsic are defined.
1693 if ((BO->getOpcode() != Instruction::Xor && &Iter == BO) || &Iter == Cmp) {
1694 InsertPt = &Iter;
1695 break;
1696 }
1697 }
1698 assert(InsertPt != nullptr && "Parent block did not contain cmp or binop");
1699
1700 IRBuilder<> Builder(InsertPt);
1701 Value *MathOV = Builder.CreateBinaryIntrinsic(IID, Arg0, Arg1);
1702 if (BO->getOpcode() != Instruction::Xor) {
1703 Value *Math = Builder.CreateExtractValue(MathOV, 0, "math");
1704 replaceAllUsesWith(BO, Math, FreshBBs, IsHugeFunc);
1705 } else
1706 assert(BO->hasOneUse() &&
1707 "Patterns with XOr should use the BO only in the compare");
1708 Value *OV = Builder.CreateExtractValue(MathOV, 1, "ov");
1709 replaceAllUsesWith(Cmp, OV, FreshBBs, IsHugeFunc);
1710 Cmp->eraseFromParent();
1711 BO->eraseFromParent();
1712 return true;
1713}
1714
1715/// Match special-case patterns that check for unsigned add overflow.
1717 BinaryOperator *&Add) {
1718 // Add = add A, 1; Cmp = icmp eq A,-1 (overflow if A is max val)
1719 // Add = add A,-1; Cmp = icmp ne A, 0 (overflow if A is non-zero)
1720 Value *A = Cmp->getOperand(0), *B = Cmp->getOperand(1);
1721
1722 // We are not expecting non-canonical/degenerate code. Just bail out.
1723 if (isa<Constant>(A))
1724 return false;
1725
1726 ICmpInst::Predicate Pred = Cmp->getPredicate();
1727 if (Pred == ICmpInst::ICMP_EQ && match(B, m_AllOnes()))
1728 B = ConstantInt::get(B->getType(), 1);
1729 else if (Pred == ICmpInst::ICMP_NE && match(B, m_ZeroInt()))
1730 B = Constant::getAllOnesValue(B->getType());
1731 else
1732 return false;
1733
1734 // Check the users of the variable operand of the compare looking for an add
1735 // with the adjusted constant.
1736 for (User *U : A->users()) {
1737 if (match(U, m_Add(m_Specific(A), m_Specific(B)))) {
1739 return true;
1740 }
1741 }
1742 return false;
1743}
1744
1745/// Try to combine the compare into a call to the llvm.uadd.with.overflow
1746/// intrinsic. Return true if any changes were made.
1747bool CodeGenPrepare::combineToUAddWithOverflow(CmpInst *Cmp,
1748 ModifyDT &ModifiedDT) {
1749 bool EdgeCase = false;
1750 Value *A, *B;
1751 BinaryOperator *Add;
1752 if (!match(Cmp, m_UAddWithOverflow(m_Value(A), m_Value(B), m_BinOp(Add)))) {
1754 return false;
1755 // Set A and B in case we match matchUAddWithOverflowConstantEdgeCases.
1756 A = Add->getOperand(0);
1757 B = Add->getOperand(1);
1758 EdgeCase = true;
1759 }
1760
1762 TLI->getValueType(*DL, Add->getType()),
1763 Add->hasNUsesOrMore(EdgeCase ? 1 : 2)))
1764 return false;
1765
1766 // We don't want to move around uses of condition values this late, so we
1767 // check if it is legal to create the call to the intrinsic in the basic
1768 // block containing the icmp.
1769 if (Add->getParent() != Cmp->getParent() && !Add->hasOneUse())
1770 return false;
1771
1772 if (!replaceMathCmpWithIntrinsic(Add, A, B, Cmp,
1773 Intrinsic::uadd_with_overflow))
1774 return false;
1775
1776 // Reset callers - do not crash by iterating over a dead instruction.
1777 ModifiedDT = ModifyDT::ModifyInstDT;
1778 return true;
1779}
1780
1781bool CodeGenPrepare::combineToUSubWithOverflow(CmpInst *Cmp,
1782 ModifyDT &ModifiedDT) {
1783 // We are not expecting non-canonical/degenerate code. Just bail out.
1784 Value *A = Cmp->getOperand(0), *B = Cmp->getOperand(1);
1785 if (isa<Constant>(A) && isa<Constant>(B))
1786 return false;
1787
1788 // Convert (A u> B) to (A u< B) to simplify pattern matching.
1789 ICmpInst::Predicate Pred = Cmp->getPredicate();
1790 if (Pred == ICmpInst::ICMP_UGT) {
1791 std::swap(A, B);
1792 Pred = ICmpInst::ICMP_ULT;
1793 }
1794 // Convert special-case: (A == 0) is the same as (A u< 1).
1795 if (Pred == ICmpInst::ICMP_EQ && match(B, m_ZeroInt())) {
1796 B = ConstantInt::get(B->getType(), 1);
1797 Pred = ICmpInst::ICMP_ULT;
1798 }
1799 // Convert special-case: (A != 0) is the same as (0 u< A).
1800 if (Pred == ICmpInst::ICMP_NE && match(B, m_ZeroInt())) {
1801 std::swap(A, B);
1802 Pred = ICmpInst::ICMP_ULT;
1803 }
1804 if (Pred != ICmpInst::ICMP_ULT)
1805 return false;
1806
1807 // Walk the users of a variable operand of a compare looking for a subtract or
1808 // add with that same operand. Also match the 2nd operand of the compare to
1809 // the add/sub, but that may be a negated constant operand of an add.
1810 Value *CmpVariableOperand = isa<Constant>(A) ? B : A;
1811 BinaryOperator *Sub = nullptr;
1812 for (User *U : CmpVariableOperand->users()) {
1813 // A - B, A u< B --> usubo(A, B)
1814 if (match(U, m_Sub(m_Specific(A), m_Specific(B)))) {
1816 break;
1817 }
1818
1819 // A + (-C), A u< C (canonicalized form of (sub A, C))
1820 const APInt *CmpC, *AddC;
1821 if (match(U, m_Add(m_Specific(A), m_APInt(AddC))) &&
1822 match(B, m_APInt(CmpC)) && *AddC == -(*CmpC)) {
1824 break;
1825 }
1826 }
1827 if (!Sub)
1828 return false;
1829
1831 TLI->getValueType(*DL, Sub->getType()),
1832 Sub->hasNUsesOrMore(1)))
1833 return false;
1834
1835 // We don't want to move around uses of condition values this late, so we
1836 // check if it is legal to create the call to the intrinsic in the basic
1837 // block containing the icmp.
1838 if (Sub->getParent() != Cmp->getParent() && !Sub->hasOneUse())
1839 return false;
1840
1841 if (!replaceMathCmpWithIntrinsic(Sub, Sub->getOperand(0), Sub->getOperand(1),
1842 Cmp, Intrinsic::usub_with_overflow))
1843 return false;
1844
1845 // Reset callers - do not crash by iterating over a dead instruction.
1846 ModifiedDT = ModifyDT::ModifyInstDT;
1847 return true;
1848}
1849
1850// Decanonicalizes icmp+ctpop power-of-two test if ctpop is slow.
1851// The same transformation exists in DAG combiner, but we repeat it here because
1852// DAG builder can break the pattern by moving icmp into a successor block.
1853bool CodeGenPrepare::unfoldPowerOf2Test(CmpInst *Cmp) {
1854 CmpPredicate Pred;
1855 Value *X;
1856 const APInt *C;
1857
1858 // (icmp (ctpop x), c)
1859 if (!match(Cmp, m_ICmp(Pred, m_Ctpop(m_Value(X)), m_APIntAllowPoison(C))))
1860 return false;
1861
1862 // We're only interested in "is power of 2 [or zero]" patterns.
1863 bool IsStrictlyPowerOf2Test = ICmpInst::isEquality(Pred) && *C == 1;
1864 bool IsPowerOf2OrZeroTest = (Pred == CmpInst::ICMP_ULT && *C == 2) ||
1865 (Pred == CmpInst::ICMP_UGT && *C == 1);
1866 if (!IsStrictlyPowerOf2Test && !IsPowerOf2OrZeroTest)
1867 return false;
1868
1869 // Some targets have better codegen for `ctpop(x) u</u>= 2/1`than for
1870 // `ctpop(x) ==/!= 1`. If ctpop is fast, only try changing the comparison,
1871 // and otherwise expand ctpop into a few simple instructions.
1872 Type *OpTy = X->getType();
1873 if (TLI->isCtpopFast(TLI->getValueType(*DL, OpTy))) {
1874 // Look for `ctpop(x) ==/!= 1`, where `ctpop(x)` is known to be non-zero.
1875 if (!IsStrictlyPowerOf2Test || !isKnownNonZero(Cmp->getOperand(0), *DL))
1876 return false;
1877
1878 // ctpop(x) == 1 -> ctpop(x) u< 2
1879 // ctpop(x) != 1 -> ctpop(x) u> 1
1880 if (Pred == ICmpInst::ICMP_EQ) {
1881 Cmp->setOperand(1, ConstantInt::get(OpTy, 2));
1882 Cmp->setPredicate(ICmpInst::ICMP_ULT);
1883 } else {
1884 Cmp->setPredicate(ICmpInst::ICMP_UGT);
1885 }
1886 return true;
1887 }
1888
1889 Value *NewCmp;
1890 if (IsPowerOf2OrZeroTest ||
1891 (IsStrictlyPowerOf2Test && isKnownNonZero(Cmp->getOperand(0), *DL))) {
1892 // ctpop(x) u< 2 -> (x & (x - 1)) == 0
1893 // ctpop(x) u> 1 -> (x & (x - 1)) != 0
1894 IRBuilder<> Builder(Cmp);
1895 Value *Sub = Builder.CreateAdd(X, Constant::getAllOnesValue(OpTy));
1896 Value *And = Builder.CreateAnd(X, Sub);
1897 CmpInst::Predicate NewPred =
1898 (Pred == CmpInst::ICMP_ULT || Pred == CmpInst::ICMP_EQ)
1900 : CmpInst::ICMP_NE;
1901 NewCmp = Builder.CreateICmp(NewPred, And, ConstantInt::getNullValue(OpTy));
1902 } else {
1903 // ctpop(x) == 1 -> (x ^ (x - 1)) u> (x - 1)
1904 // ctpop(x) != 1 -> (x ^ (x - 1)) u<= (x - 1)
1905 IRBuilder<> Builder(Cmp);
1906 Value *Sub = Builder.CreateAdd(X, Constant::getAllOnesValue(OpTy));
1907 Value *Xor = Builder.CreateXor(X, Sub);
1908 CmpInst::Predicate NewPred =
1910 NewCmp = Builder.CreateICmp(NewPred, Xor, Sub);
1911 }
1912
1913 Cmp->replaceAllUsesWith(NewCmp);
1915 return true;
1916}
1917
1918/// Sink the given CmpInst into user blocks to reduce the number of virtual
1919/// registers that must be created and coalesced. This is a clear win except on
1920/// targets with multiple condition code registers (PowerPC), where it might
1921/// lose; some adjustment may be wanted there.
1922///
1923/// Return true if any changes are made.
1924static bool sinkCmpExpression(CmpInst *Cmp, const TargetLowering &TLI,
1925 const DataLayout &DL) {
1926 if (TLI.hasMultipleConditionRegisters(EVT::getEVT(Cmp->getType())))
1927 return false;
1928
1929 // Avoid sinking soft-FP comparisons, since this can move them into a loop.
1930 if (TLI.useSoftFloat() && isa<FCmpInst>(Cmp))
1931 return false;
1932
1933 bool UsedInPhiOrCurrentBlock = any_of(Cmp->users(), [Cmp](User *U) {
1934 return isa<PHINode>(U) ||
1935 cast<Instruction>(U)->getParent() == Cmp->getParent();
1936 });
1937
1938 // Avoid sinking larger than legal integer comparisons unless its ONLY used in
1939 // another BB.
1940 if (UsedInPhiOrCurrentBlock && Cmp->getOperand(0)->getType()->isIntegerTy() &&
1941 Cmp->getOperand(0)->getType()->getScalarSizeInBits() >
1942 DL.getLargestLegalIntTypeSizeInBits())
1943 return false;
1944
1945 // Only insert a cmp in each block once.
1947
1948 bool MadeChange = false;
1949 for (Instruction::user_iterator UI = Cmp->user_begin(), E = Cmp->user_end();
1950 UI != E;) {
1951 Use &TheUse = UI.getUse();
1953
1954 // Preincrement use iterator so we don't invalidate it.
1955 ++UI;
1956
1957 // Don't bother for PHI nodes.
1958 if (isa<PHINode>(User))
1959 continue;
1960
1961 // Figure out which BB this cmp is used in.
1962 BasicBlock *UserBB = User->getParent();
1963 BasicBlock *DefBB = Cmp->getParent();
1964
1965 // If this user is in the same block as the cmp, don't change the cmp.
1966 if (UserBB == DefBB)
1967 continue;
1968
1969 // If we have already inserted a cmp into this block, use it.
1970 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
1971
1972 if (!InsertedCmp) {
1973 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1974 assert(InsertPt != UserBB->end());
1975 InsertedCmp = CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(),
1976 Cmp->getOperand(0), Cmp->getOperand(1), "");
1977 InsertedCmp->insertBefore(*UserBB, InsertPt);
1978 // Propagate the debug info.
1979 InsertedCmp->setDebugLoc(Cmp->getDebugLoc());
1980 }
1981
1982 // Replace a use of the cmp with a use of the new cmp.
1983 TheUse = InsertedCmp;
1984 MadeChange = true;
1985 ++NumCmpUses;
1986 }
1987
1988 // If we removed all uses, nuke the cmp.
1989 if (Cmp->use_empty()) {
1990 Cmp->eraseFromParent();
1991 MadeChange = true;
1992 }
1993
1994 return MadeChange;
1995}
1996
1997/// For pattern like:
1998///
1999/// DomCond = icmp sgt/slt CmpOp0, CmpOp1 (might not be in DomBB)
2000/// ...
2001/// DomBB:
2002/// ...
2003/// br DomCond, TrueBB, CmpBB
2004/// CmpBB: (with DomBB being the single predecessor)
2005/// ...
2006/// Cmp = icmp eq CmpOp0, CmpOp1
2007/// ...
2008///
2009/// It would use two comparison on targets that lowering of icmp sgt/slt is
2010/// different from lowering of icmp eq (PowerPC). This function try to convert
2011/// 'Cmp = icmp eq CmpOp0, CmpOp1' to ' Cmp = icmp slt/sgt CmpOp0, CmpOp1'.
2012/// After that, DomCond and Cmp can use the same comparison so reduce one
2013/// comparison.
2014///
2015/// Return true if any changes are made.
2017 const TargetLowering &TLI) {
2019 return false;
2020
2021 ICmpInst::Predicate Pred = Cmp->getPredicate();
2022 if (Pred != ICmpInst::ICMP_EQ)
2023 return false;
2024
2025 // If icmp eq has users other than CondBrInst and SelectInst, converting it to
2026 // icmp slt/sgt would introduce more redundant LLVM IR.
2027 for (User *U : Cmp->users()) {
2028 if (isa<CondBrInst>(U))
2029 continue;
2030 if (isa<SelectInst>(U) && cast<SelectInst>(U)->getCondition() == Cmp)
2031 continue;
2032 return false;
2033 }
2034
2035 // This is a cheap/incomplete check for dominance - just match a single
2036 // predecessor with a conditional branch.
2037 BasicBlock *CmpBB = Cmp->getParent();
2038 BasicBlock *DomBB = CmpBB->getSinglePredecessor();
2039 if (!DomBB)
2040 return false;
2041
2042 // We want to ensure that the only way control gets to the comparison of
2043 // interest is that a less/greater than comparison on the same operands is
2044 // false.
2045 Value *DomCond;
2046 BasicBlock *TrueBB, *FalseBB;
2047 if (!match(DomBB->getTerminator(), m_Br(m_Value(DomCond), TrueBB, FalseBB)))
2048 return false;
2049 if (CmpBB != FalseBB)
2050 return false;
2051
2052 Value *CmpOp0 = Cmp->getOperand(0), *CmpOp1 = Cmp->getOperand(1);
2053 CmpPredicate DomPred;
2054 if (!match(DomCond, m_ICmp(DomPred, m_Specific(CmpOp0), m_Specific(CmpOp1))))
2055 return false;
2056 if (DomPred != ICmpInst::ICMP_SGT && DomPred != ICmpInst::ICMP_SLT)
2057 return false;
2058
2059 // Convert the equality comparison to the opposite of the dominating
2060 // comparison and swap the direction for all branch/select users.
2061 // We have conceptually converted:
2062 // Res = (a < b) ? <LT_RES> : (a == b) ? <EQ_RES> : <GT_RES>;
2063 // to
2064 // Res = (a < b) ? <LT_RES> : (a > b) ? <GT_RES> : <EQ_RES>;
2065 // And similarly for branches.
2066 for (User *U : Cmp->users()) {
2067 if (auto *BI = dyn_cast<CondBrInst>(U)) {
2068 BI->swapSuccessors();
2069 continue;
2070 }
2071 if (auto *SI = dyn_cast<SelectInst>(U)) {
2072 // Swap operands
2073 SI->swapValues();
2074 SI->swapProfMetadata();
2075 continue;
2076 }
2077 llvm_unreachable("Must be a branch or a select");
2078 }
2079 Cmp->setPredicate(CmpInst::getSwappedPredicate(DomPred));
2080 return true;
2081}
2082
2083/// Many architectures use the same instruction for both subtract and cmp. Try
2084/// to swap cmp operands to match subtract operations to allow for CSE.
2086 Value *Op0 = Cmp->getOperand(0);
2087 Value *Op1 = Cmp->getOperand(1);
2088 if (!Op0->getType()->isIntegerTy() || isa<Constant>(Op0) ||
2089 isa<Constant>(Op1) || Op0 == Op1)
2090 return false;
2091
2092 // If a subtract already has the same operands as a compare, swapping would be
2093 // bad. If a subtract has the same operands as a compare but in reverse order,
2094 // then swapping is good.
2095 int GoodToSwap = 0;
2096 unsigned NumInspected = 0;
2097 for (const User *U : Op0->users()) {
2098 // Avoid walking many users.
2099 if (++NumInspected > 128)
2100 return false;
2101 if (match(U, m_Sub(m_Specific(Op1), m_Specific(Op0))))
2102 GoodToSwap++;
2103 else if (match(U, m_Sub(m_Specific(Op0), m_Specific(Op1))))
2104 GoodToSwap--;
2105 }
2106
2107 if (GoodToSwap > 0) {
2108 Cmp->swapOperands();
2109 return true;
2110 }
2111 return false;
2112}
2113
2114static bool foldFCmpToFPClassTest(CmpInst *Cmp, const TargetLowering &TLI,
2115 const DataLayout &DL) {
2116 FCmpInst *FCmp = dyn_cast<FCmpInst>(Cmp);
2117 if (!FCmp)
2118 return false;
2119
2120 // Don't fold if the target offers free fabs and the predicate is legal.
2121 EVT VT = TLI.getValueType(DL, Cmp->getOperand(0)->getType());
2122 if (TLI.isFAbsFree(VT) &&
2124 VT.getSimpleVT()))
2125 return false;
2126
2127 // Reverse the canonicalization if it is a FP class test
2128 auto ShouldReverseTransform = [](FPClassTest ClassTest) {
2129 return ClassTest == fcInf || ClassTest == (fcInf | fcNan);
2130 };
2131 auto [ClassVal, ClassTest] =
2132 fcmpToClassTest(FCmp->getPredicate(), *FCmp->getParent()->getParent(),
2133 FCmp->getOperand(0), FCmp->getOperand(1));
2134 if (!ClassVal)
2135 return false;
2136
2137 if (!ShouldReverseTransform(ClassTest) && !ShouldReverseTransform(~ClassTest))
2138 return false;
2139
2140 IRBuilder<> Builder(Cmp);
2141 Value *IsFPClass = Builder.createIsFPClass(ClassVal, ClassTest);
2142 Cmp->replaceAllUsesWith(IsFPClass);
2144 return true;
2145}
2146
2148 Instruction *Rem, const LoopInfo *LI, Value *&RemAmtOut, Value *&AddInstOut,
2149 Value *&AddOffsetOut, PHINode *&LoopIncrPNOut) {
2150 Value *Incr, *RemAmt;
2151 // NB: If RemAmt is a power of 2 it *should* have been transformed by now.
2152 if (!match(Rem, m_URem(m_Value(Incr), m_Value(RemAmt))))
2153 return false;
2154
2155 Value *AddInst, *AddOffset;
2156 // Find out loop increment PHI.
2157 PHINode *PN = dyn_cast<PHINode>(Incr);
2158 if (PN != nullptr) {
2159 AddInst = nullptr;
2160 AddOffset = nullptr;
2161 } else {
2162 // Search through a NUW add on top of the loop increment.
2163 if (!match(Incr, m_c_NUWAdd(m_Phi(PN), m_Value(AddOffset))))
2164 return false;
2165 AddInst = Incr;
2166 }
2167
2168 if (!PN)
2169 return false;
2170
2171 // This isn't strictly necessary, what we really need is one increment and any
2172 // amount of initial values all being the same.
2173 if (PN->getNumIncomingValues() != 2)
2174 return false;
2175
2176 // Only trivially analyzable loops.
2177 Loop *L = LI->getLoopFor(PN->getParent());
2178 if (!L || !L->getLoopPreheader() || !L->getLoopLatch())
2179 return false;
2180
2181 // Req that the remainder is in the loop
2182 if (!L->contains(Rem))
2183 return false;
2184
2185 // Only works if the remainder amount is a loop invaraint
2186 if (!L->isLoopInvariant(RemAmt))
2187 return false;
2188
2189 // Only works if the AddOffset is a loop invaraint
2190 if (AddOffset && !L->isLoopInvariant(AddOffset))
2191 return false;
2192
2193 // Is the PHI a loop increment?
2194 auto LoopIncrInfo = getIVIncrement(PN, LI);
2195 if (!LoopIncrInfo)
2196 return false;
2197
2198 // We need remainder_amount % increment_amount to be zero. Increment of one
2199 // satisfies that without any special logic and is overwhelmingly the common
2200 // case.
2201 if (!match(LoopIncrInfo->second, m_One()))
2202 return false;
2203
2204 // Need the increment to not overflow.
2205 if (!match(LoopIncrInfo->first, m_c_NUWAdd(m_Specific(PN), m_Value())))
2206 return false;
2207
2208 // Set output variables.
2209 RemAmtOut = RemAmt;
2210 LoopIncrPNOut = PN;
2211 AddInstOut = AddInst;
2212 AddOffsetOut = AddOffset;
2213
2214 return true;
2215}
2216
2217// Try to transform:
2218//
2219// for(i = Start; i < End; ++i)
2220// Rem = (i nuw+ IncrLoopInvariant) u% RemAmtLoopInvariant;
2221//
2222// ->
2223//
2224// Rem = (Start nuw+ IncrLoopInvariant) % RemAmtLoopInvariant;
2225// for(i = Start; i < End; ++i, ++rem)
2226// Rem = rem == RemAmtLoopInvariant ? 0 : Rem;
2228 const LoopInfo *LI,
2230 bool IsHuge) {
2231 Value *AddOffset, *RemAmt, *AddInst;
2232 PHINode *LoopIncrPN;
2233 if (!isRemOfLoopIncrementWithLoopInvariant(Rem, LI, RemAmt, AddInst,
2234 AddOffset, LoopIncrPN))
2235 return false;
2236
2237 // Only non-constant remainder as the extra IV is probably not profitable
2238 // in that case.
2239 //
2240 // Potential TODO(1): `urem` of a const ends up as `mul` + `shift` + `add`. If
2241 // we can rule out register pressure and ensure this `urem` is executed each
2242 // iteration, its probably profitable to handle the const case as well.
2243 //
2244 // Potential TODO(2): Should we have a check for how "nested" this remainder
2245 // operation is? The new code runs every iteration so if the remainder is
2246 // guarded behind unlikely conditions this might not be worth it.
2247 if (match(RemAmt, m_ImmConstant()))
2248 return false;
2249
2250 Loop *L = LI->getLoopFor(LoopIncrPN->getParent());
2251 Value *Start = LoopIncrPN->getIncomingValueForBlock(L->getLoopPreheader());
2252 // If we have add create initial value for remainder.
2253 // The logic here is:
2254 // (urem (add nuw Start, IncrLoopInvariant), RemAmtLoopInvariant
2255 //
2256 // Only proceed if the expression simplifies (otherwise we can't fully
2257 // optimize out the urem).
2258 if (AddInst) {
2259 assert(AddOffset && "We found an add but missing values");
2260 // Without dom-condition/assumption cache we aren't likely to get much out
2261 // of a context instruction.
2262 Start = simplifyAddInst(Start, AddOffset,
2263 match(AddInst, m_NSWAdd(m_Value(), m_Value())),
2264 /*IsNUW=*/true, *DL);
2265 if (!Start)
2266 return false;
2267 }
2268
2269 // If we can't fully optimize out the `rem`, skip this transform.
2270 Start = simplifyURemInst(Start, RemAmt, *DL);
2271 if (!Start)
2272 return false;
2273
2274 // Create new remainder with induction variable.
2275 Type *Ty = Rem->getType();
2276 IRBuilder<> Builder(LoopIncrPN);
2277 PHINode *NewRem = Builder.CreatePHI(Ty, 2);
2278
2279 Builder.SetInsertPoint(cast<Instruction>(
2280 LoopIncrPN->getIncomingValueForBlock(L->getLoopLatch())));
2281 // `(add (urem x, y), 1)` is always nuw.
2282 Value *RemAdd = Builder.CreateNUWAdd(NewRem, ConstantInt::get(Ty, 1));
2283 Value *RemCmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, RemAdd, RemAmt);
2284 Value *RemSel =
2285 Builder.CreateSelect(RemCmp, Constant::getNullValue(Ty), RemAdd);
2286
2287 NewRem->addIncoming(Start, L->getLoopPreheader());
2288 NewRem->addIncoming(RemSel, L->getLoopLatch());
2289
2290 // Insert all touched BBs.
2291 FreshBBs.insert(LoopIncrPN->getParent());
2292 FreshBBs.insert(L->getLoopLatch());
2293 FreshBBs.insert(Rem->getParent());
2294 if (AddInst)
2295 FreshBBs.insert(cast<Instruction>(AddInst)->getParent());
2296 replaceAllUsesWith(Rem, NewRem, FreshBBs, IsHuge);
2297 Rem->eraseFromParent();
2298 if (AddInst && AddInst->use_empty())
2299 cast<Instruction>(AddInst)->eraseFromParent();
2300 return true;
2301}
2302
2303bool CodeGenPrepare::optimizeURem(Instruction *Rem) {
2304 if (foldURemOfLoopIncrement(Rem, DL, LI, FreshBBs, IsHugeFunc))
2305 return true;
2306 return false;
2307}
2308
2309bool CodeGenPrepare::optimizeCmp(CmpInst *Cmp, ModifyDT &ModifiedDT) {
2310 if (sinkCmpExpression(Cmp, *TLI, *DL))
2311 return true;
2312
2313 if (combineToUAddWithOverflow(Cmp, ModifiedDT))
2314 return true;
2315
2316 if (combineToUSubWithOverflow(Cmp, ModifiedDT))
2317 return true;
2318
2319 if (unfoldPowerOf2Test(Cmp))
2320 return true;
2321
2322 if (foldICmpWithDominatingICmp(Cmp, *TLI))
2323 return true;
2324
2326 return true;
2327
2328 if (foldFCmpToFPClassTest(Cmp, *TLI, *DL))
2329 return true;
2330
2331 return false;
2332}
2333
2334/// Duplicate and sink the given 'and' instruction into user blocks where it is
2335/// used in a compare to allow isel to generate better code for targets where
2336/// this operation can be combined.
2337///
2338/// Return true if any changes are made.
2340 SetOfInstrs &InsertedInsts) {
2341 // Double-check that we're not trying to optimize an instruction that was
2342 // already optimized by some other part of this pass.
2343 assert(!InsertedInsts.count(AndI) &&
2344 "Attempting to optimize already optimized and instruction");
2345 (void)InsertedInsts;
2346
2347 // Nothing to do for single use in same basic block.
2348 if (AndI->hasOneUse() &&
2349 AndI->getParent() == cast<Instruction>(*AndI->user_begin())->getParent())
2350 return false;
2351
2352 // Try to avoid cases where sinking/duplicating is likely to increase register
2353 // pressure.
2354 if (!isa<ConstantInt>(AndI->getOperand(0)) &&
2355 !isa<ConstantInt>(AndI->getOperand(1)) &&
2356 AndI->getOperand(0)->hasOneUse() && AndI->getOperand(1)->hasOneUse())
2357 return false;
2358
2359 for (auto *U : AndI->users()) {
2361
2362 // Only sink 'and' feeding icmp with 0.
2363 if (!isa<ICmpInst>(User))
2364 return false;
2365
2366 auto *CmpC = dyn_cast<ConstantInt>(User->getOperand(1));
2367 if (!CmpC || !CmpC->isZero())
2368 return false;
2369 }
2370
2371 if (!TLI.isMaskAndCmp0FoldingBeneficial(*AndI))
2372 return false;
2373
2374 LLVM_DEBUG(dbgs() << "found 'and' feeding only icmp 0;\n");
2375 LLVM_DEBUG(AndI->getParent()->dump());
2376
2377 // Push the 'and' into the same block as the icmp 0. There should only be
2378 // one (icmp (and, 0)) in each block, since CSE/GVN should have removed any
2379 // others, so we don't need to keep track of which BBs we insert into.
2380 for (Instruction::user_iterator UI = AndI->user_begin(), E = AndI->user_end();
2381 UI != E;) {
2382 Use &TheUse = UI.getUse();
2384
2385 // Preincrement use iterator so we don't invalidate it.
2386 ++UI;
2387
2388 LLVM_DEBUG(dbgs() << "sinking 'and' use: " << *User << "\n");
2389
2390 // Keep the 'and' in the same place if the use is already in the same block.
2391 Instruction *InsertPt =
2392 User->getParent() == AndI->getParent() ? AndI : User;
2393 Instruction *InsertedAnd = BinaryOperator::Create(
2394 Instruction::And, AndI->getOperand(0), AndI->getOperand(1), "",
2395 InsertPt->getIterator());
2396 // Propagate the debug info.
2397 InsertedAnd->setDebugLoc(AndI->getDebugLoc());
2398
2399 // Replace a use of the 'and' with a use of the new 'and'.
2400 TheUse = InsertedAnd;
2401 ++NumAndUses;
2402 LLVM_DEBUG(User->getParent()->dump());
2403 }
2404
2405 // We removed all uses, nuke the and.
2406 AndI->eraseFromParent();
2407 return true;
2408}
2409
2410/// Check if the candidates could be combined with a shift instruction, which
2411/// includes:
2412/// 1. Truncate instruction
2413/// 2. And instruction and the imm is a mask of the low bits:
2414/// imm & (imm+1) == 0
2416 if (!isa<TruncInst>(User)) {
2417 if (User->getOpcode() != Instruction::And ||
2419 return false;
2420
2421 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
2422
2423 if ((Cimm & (Cimm + 1)).getBoolValue())
2424 return false;
2425 }
2426 return true;
2427}
2428
2429/// Sink both shift and truncate instruction to the use of truncate's BB.
2430static bool
2433 const TargetLowering &TLI, const DataLayout &DL) {
2434 BasicBlock *UserBB = User->getParent();
2436 auto *TruncI = cast<TruncInst>(User);
2437 bool MadeChange = false;
2438
2439 for (Instruction::user_iterator TruncUI = TruncI->user_begin(),
2440 TruncE = TruncI->user_end();
2441 TruncUI != TruncE;) {
2442
2443 Use &TruncTheUse = TruncUI.getUse();
2444 Instruction *TruncUser = cast<Instruction>(*TruncUI);
2445 // Preincrement use iterator so we don't invalidate it.
2446
2447 ++TruncUI;
2448
2449 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
2450 if (!ISDOpcode)
2451 continue;
2452
2453 // If the use is actually a legal node, there will not be an
2454 // implicit truncate.
2455 // FIXME: always querying the result type is just an
2456 // approximation; some nodes' legality is determined by the
2457 // operand or other means. There's no good way to find out though.
2459 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
2460 continue;
2461
2462 // Don't bother for PHI nodes.
2463 if (isa<PHINode>(TruncUser))
2464 continue;
2465
2466 BasicBlock *TruncUserBB = TruncUser->getParent();
2467
2468 if (UserBB == TruncUserBB)
2469 continue;
2470
2471 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
2472 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
2473
2474 if (!InsertedShift && !InsertedTrunc) {
2475 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
2476 assert(InsertPt != TruncUserBB->end());
2477 // Sink the shift
2478 if (ShiftI->getOpcode() == Instruction::AShr)
2479 InsertedShift =
2480 BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "");
2481 else
2482 InsertedShift =
2483 BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "");
2484 InsertedShift->setDebugLoc(ShiftI->getDebugLoc());
2485 InsertedShift->insertBefore(*TruncUserBB, InsertPt);
2486
2487 // Sink the trunc
2488 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
2489 TruncInsertPt++;
2490 // It will go ahead of any debug-info.
2491 TruncInsertPt.setHeadBit(true);
2492 assert(TruncInsertPt != TruncUserBB->end());
2493
2494 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
2495 TruncI->getType(), "");
2496 InsertedTrunc->insertBefore(*TruncUserBB, TruncInsertPt);
2497 InsertedTrunc->setDebugLoc(TruncI->getDebugLoc());
2498
2499 MadeChange = true;
2500
2501 TruncTheUse = InsertedTrunc;
2502 }
2503 }
2504 return MadeChange;
2505}
2506
2507/// Sink the shift *right* instruction into user blocks if the uses could
2508/// potentially be combined with this shift instruction and generate BitExtract
2509/// instruction. It will only be applied if the architecture supports BitExtract
2510/// instruction. Here is an example:
2511/// BB1:
2512/// %x.extract.shift = lshr i64 %arg1, 32
2513/// BB2:
2514/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
2515/// ==>
2516///
2517/// BB2:
2518/// %x.extract.shift.1 = lshr i64 %arg1, 32
2519/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
2520///
2521/// CodeGen will recognize the pattern in BB2 and generate BitExtract
2522/// instruction.
2523/// Return true if any changes are made.
2525 const TargetLowering &TLI,
2526 const DataLayout &DL) {
2527 BasicBlock *DefBB = ShiftI->getParent();
2528
2529 /// Only insert instructions in each block once.
2531
2532 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
2533
2534 bool MadeChange = false;
2535 for (Instruction::user_iterator UI = ShiftI->user_begin(),
2536 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(StartBlock->getTerminator());
2674 Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
2675
2676 // Replace the unconditional branch that was created by the first split with
2677 // a compare against zero and a conditional branch.
2678 Value *Zero = Constant::getNullValue(Ty);
2679 // Avoid introducing branch on poison. This also replaces the ctz operand.
2681 Op = Builder.CreateFreeze(Op, Op->getName() + ".fr");
2682 Value *Cmp = Builder.CreateICmpEQ(Op, Zero, "cmpz");
2683 Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
2684 StartBlock->getTerminator()->eraseFromParent();
2685 DTU->applyUpdates({{DominatorTree::Insert, StartBlock, EndBlock}});
2686
2687 // Create a PHI in the end block to select either the output of the intrinsic
2688 // or the bit width of the operand.
2689 Builder.SetInsertPoint(EndBlock, EndBlock->begin());
2690 PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
2691 replaceAllUsesWith(CountZeros, PN, FreshBBs, IsHugeFunc);
2692 Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
2693 PN->addIncoming(BitWidth, StartBlock);
2694 PN->addIncoming(CountZeros, CallBlock);
2695
2696 // We are explicitly handling the zero case, so we can set the intrinsic's
2697 // undefined zero argument to 'true'. This will also prevent reprocessing the
2698 // intrinsic; we only despeculate when a zero input is defined.
2699 CountZeros->setArgOperand(1, Builder.getTrue());
2700 ModifiedDT = ModifyDT::ModifyBBDT;
2701 return true;
2702}
2703
2704bool CodeGenPrepare::optimizeCallInst(CallInst *CI, ModifyDT &ModifiedDT) {
2705 BasicBlock *BB = CI->getParent();
2706
2707 // Sink address computing for memory operands into the block.
2708 if (CI->isInlineAsm() && optimizeInlineAsmInst(CI))
2709 return true;
2710
2711 // Align the pointer arguments to this call if the target thinks it's a good
2712 // idea
2713 unsigned MinSize;
2714 Align PrefAlign;
2715 if (TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
2716 for (auto &Arg : CI->args()) {
2717 // We want to align both objects whose address is used directly and
2718 // objects whose address is used in casts and GEPs, though it only makes
2719 // sense for GEPs if the offset is a multiple of the desired alignment and
2720 // if size - offset meets the size threshold.
2721 if (!Arg->getType()->isPointerTy())
2722 continue;
2723 APInt Offset(DL->getIndexSizeInBits(
2724 cast<PointerType>(Arg->getType())->getAddressSpace()),
2725 0);
2726 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
2727 uint64_t Offset2 = Offset.getLimitedValue();
2728 if (!isAligned(PrefAlign, Offset2))
2729 continue;
2730 AllocaInst *AI;
2731 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlign() < PrefAlign) {
2732 std::optional<TypeSize> AllocaSize = AI->getAllocationSize(*DL);
2733 if (AllocaSize && AllocaSize->getKnownMinValue() >= MinSize + Offset2)
2734 AI->setAlignment(PrefAlign);
2735 }
2736 // Global variables can only be aligned if they are defined in this
2737 // object (i.e. they are uniquely initialized in this object), and
2738 // over-aligning global variables that have an explicit section is
2739 // forbidden.
2740 GlobalVariable *GV;
2741 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
2742 GV->getPointerAlignment(*DL) < PrefAlign &&
2743 GV->getGlobalSize(*DL) >= MinSize + Offset2)
2744 GV->setAlignment(PrefAlign);
2745 }
2746 }
2747 // If this is a memcpy (or similar) then we may be able to improve the
2748 // alignment.
2749 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
2750 Align DestAlign = getKnownAlignment(MI->getDest(), *DL);
2751 MaybeAlign MIDestAlign = MI->getDestAlign();
2752 if (!MIDestAlign || DestAlign > *MIDestAlign)
2753 MI->setDestAlignment(DestAlign);
2754 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
2755 MaybeAlign MTISrcAlign = MTI->getSourceAlign();
2756 Align SrcAlign = getKnownAlignment(MTI->getSource(), *DL);
2757 if (!MTISrcAlign || SrcAlign > *MTISrcAlign)
2758 MTI->setSourceAlignment(SrcAlign);
2759 }
2760 }
2761
2762 // If we have a cold call site, try to sink addressing computation into the
2763 // cold block. This interacts with our handling for loads and stores to
2764 // ensure that we can fold all uses of a potential addressing computation
2765 // into their uses. TODO: generalize this to work over profiling data
2766 if (CI->hasFnAttr(Attribute::Cold) &&
2767 !llvm::shouldOptimizeForSize(BB, PSI, BFI))
2768 for (auto &Arg : CI->args()) {
2769 if (!Arg->getType()->isPointerTy())
2770 continue;
2771 unsigned AS = Arg->getType()->getPointerAddressSpace();
2772 if (optimizeMemoryInst(CI, Arg, Arg->getType(), AS))
2773 return true;
2774 }
2775
2776 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
2777 if (II) {
2778 switch (II->getIntrinsicID()) {
2779 default:
2780 break;
2781 case Intrinsic::assume:
2782 llvm_unreachable("llvm.assume should have been removed already");
2783 case Intrinsic::allow_runtime_check:
2784 case Intrinsic::allow_ubsan_check:
2785 case Intrinsic::experimental_widenable_condition: {
2786 // Give up on future widening opportunities so that we can fold away dead
2787 // paths and merge blocks before going into block-local instruction
2788 // selection.
2789 if (II->use_empty()) {
2790 II->eraseFromParent();
2791 return true;
2792 }
2793 Constant *RetVal = ConstantInt::getTrue(II->getContext());
2794 resetIteratorIfInvalidatedWhileCalling(BB, [&]() {
2795 replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
2796 });
2797 return true;
2798 }
2799 case Intrinsic::objectsize:
2800 llvm_unreachable("llvm.objectsize.* should have been lowered already");
2801 case Intrinsic::is_constant:
2802 llvm_unreachable("llvm.is.constant.* should have been lowered already");
2803 case Intrinsic::aarch64_stlxr:
2804 case Intrinsic::aarch64_stxr: {
2805 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
2806 if (!ExtVal || !ExtVal->hasOneUse() ||
2807 ExtVal->getParent() == CI->getParent())
2808 return false;
2809 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
2810 ExtVal->moveBefore(CI->getIterator());
2811 // Mark this instruction as "inserted by CGP", so that other
2812 // optimizations don't touch it.
2813 InsertedInsts.insert(ExtVal);
2814 return true;
2815 }
2816
2817 case Intrinsic::launder_invariant_group: {
2818 Value *ArgVal = II->getArgOperand(0);
2819 auto it = LargeOffsetGEPMap.find(II);
2820 if (it != LargeOffsetGEPMap.end()) {
2821 // Merge entries in LargeOffsetGEPMap to reflect the RAUW.
2822 // Make sure not to have to deal with iterator invalidation
2823 // after possibly adding ArgVal to LargeOffsetGEPMap.
2824 auto GEPs = std::move(it->second);
2825 LargeOffsetGEPMap[ArgVal].append(GEPs.begin(), GEPs.end());
2826 LargeOffsetGEPMap.erase(II);
2827 }
2828
2829 replaceAllUsesWith(II, ArgVal, FreshBBs, IsHugeFunc);
2830 II->eraseFromParent();
2831 return true;
2832 }
2833 case Intrinsic::cttz:
2834 case Intrinsic::ctlz:
2835 // If counting zeros is expensive, try to avoid it.
2836 return despeculateCountZeros(II, DTU, LI, TLI, DL, ModifiedDT, FreshBBs,
2837 IsHugeFunc);
2838 case Intrinsic::fshl:
2839 case Intrinsic::fshr:
2840 return optimizeFunnelShift(II);
2841 case Intrinsic::masked_gather:
2842 return optimizeGatherScatterInst(II, II->getArgOperand(0));
2843 case Intrinsic::masked_scatter:
2844 return optimizeGatherScatterInst(II, II->getArgOperand(1));
2845 case Intrinsic::masked_load:
2846 // Treat v1X masked load as load X type.
2847 if (auto *VT = dyn_cast<FixedVectorType>(II->getType())) {
2848 if (VT->getNumElements() == 1) {
2849 Value *PtrVal = II->getArgOperand(0);
2850 unsigned AS = PtrVal->getType()->getPointerAddressSpace();
2851 if (optimizeMemoryInst(II, PtrVal, VT->getElementType(), AS))
2852 return true;
2853 }
2854 }
2855 return false;
2856 case Intrinsic::masked_store:
2857 // Treat v1X masked store as store X type.
2858 if (auto *VT =
2859 dyn_cast<FixedVectorType>(II->getArgOperand(0)->getType())) {
2860 if (VT->getNumElements() == 1) {
2861 Value *PtrVal = II->getArgOperand(1);
2862 unsigned AS = PtrVal->getType()->getPointerAddressSpace();
2863 if (optimizeMemoryInst(II, PtrVal, VT->getElementType(), AS))
2864 return true;
2865 }
2866 }
2867 return false;
2868 case Intrinsic::umul_with_overflow:
2869 return optimizeMulWithOverflow(II, /*IsSigned=*/false, ModifiedDT);
2870 case Intrinsic::smul_with_overflow:
2871 return optimizeMulWithOverflow(II, /*IsSigned=*/true, ModifiedDT);
2872 }
2873
2874 SmallVector<Value *, 2> PtrOps;
2875 Type *AccessTy;
2876 if (TLI->getAddrModeArguments(II, PtrOps, AccessTy))
2877 while (!PtrOps.empty()) {
2878 Value *PtrVal = PtrOps.pop_back_val();
2879 unsigned AS = PtrVal->getType()->getPointerAddressSpace();
2880 if (optimizeMemoryInst(II, PtrVal, AccessTy, AS))
2881 return true;
2882 }
2883 }
2884
2885 // From here on out we're working with named functions.
2886 auto *Callee = CI->getCalledFunction();
2887 if (!Callee)
2888 return false;
2889
2890 // Lower all default uses of _chk calls. This is very similar
2891 // to what InstCombineCalls does, but here we are only lowering calls
2892 // to fortified library functions (e.g. __memcpy_chk) that have the default
2893 // "don't know" as the objectsize. Anything else should be left alone.
2894 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
2895 IRBuilder<> Builder(CI);
2896 if (Value *V = Simplifier.optimizeCall(CI, Builder)) {
2897 replaceAllUsesWith(CI, V, FreshBBs, IsHugeFunc);
2898 CI->eraseFromParent();
2899 return true;
2900 }
2901
2902 // SCCP may have propagated, among other things, C++ static variables across
2903 // calls. If this happens to be the case, we may want to undo it in order to
2904 // avoid redundant pointer computation of the constant, as the function method
2905 // returning the constant needs to be executed anyways.
2906 auto GetUniformReturnValue = [](const Function *F) -> GlobalVariable * {
2907 if (!F->getReturnType()->isPointerTy())
2908 return nullptr;
2909
2910 GlobalVariable *UniformValue = nullptr;
2911 for (auto &BB : *F) {
2912 if (auto *RI = dyn_cast<ReturnInst>(BB.getTerminator())) {
2913 if (auto *V = dyn_cast<GlobalVariable>(RI->getReturnValue())) {
2914 if (!UniformValue)
2915 UniformValue = V;
2916 else if (V != UniformValue)
2917 return nullptr;
2918 } else {
2919 return nullptr;
2920 }
2921 }
2922 }
2923
2924 return UniformValue;
2925 };
2926
2927 if (Callee->hasExactDefinition()) {
2928 if (GlobalVariable *RV = GetUniformReturnValue(Callee)) {
2929 bool MadeChange = false;
2930 for (Use &U : make_early_inc_range(RV->uses())) {
2931 auto *I = dyn_cast<Instruction>(U.getUser());
2932 if (!I || I->getParent() != CI->getParent()) {
2933 // Limit to the same basic block to avoid extending the call-site live
2934 // range, which otherwise could increase register pressure.
2935 continue;
2936 }
2937 if (CI->comesBefore(I)) {
2938 U.set(CI);
2939 MadeChange = true;
2940 }
2941 }
2942
2943 return MadeChange;
2944 }
2945 }
2946
2947 return false;
2948}
2949
2951 const CallInst *CI) {
2952 assert(CI && CI->use_empty());
2953
2954 if (const auto *II = dyn_cast<IntrinsicInst>(CI))
2955 switch (II->getIntrinsicID()) {
2956 case Intrinsic::memset:
2957 case Intrinsic::memcpy:
2958 case Intrinsic::memmove:
2959 return true;
2960 default:
2961 return false;
2962 }
2963
2964 Function *Callee = CI->getCalledFunction();
2965 if (Callee && TLInfo)
2966 switch (TLInfo->getLibFunc(*Callee)) {
2967 case LibFunc_strcpy:
2968 case LibFunc_strncpy:
2969 case LibFunc_strcat:
2970 case LibFunc_strncat:
2971 return true;
2972 default:
2973 return false;
2974 }
2975
2976 return false;
2977}
2978
2979/// Look for opportunities to duplicate return instructions to the predecessor
2980/// to enable tail call optimizations. The case it is currently looking for is
2981/// the following one. Known intrinsics or library function that may be tail
2982/// called are taken into account as well.
2983/// @code
2984/// bb0:
2985/// %tmp0 = tail call i32 @f0()
2986/// br label %return
2987/// bb1:
2988/// %tmp1 = tail call i32 @f1()
2989/// br label %return
2990/// bb2:
2991/// %tmp2 = tail call i32 @f2()
2992/// br label %return
2993/// return:
2994/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
2995/// ret i32 %retval
2996/// @endcode
2997///
2998/// =>
2999///
3000/// @code
3001/// bb0:
3002/// %tmp0 = tail call i32 @f0()
3003/// ret i32 %tmp0
3004/// bb1:
3005/// %tmp1 = tail call i32 @f1()
3006/// ret i32 %tmp1
3007/// bb2:
3008/// %tmp2 = tail call i32 @f2()
3009/// ret i32 %tmp2
3010/// @endcode
3011bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB,
3012 ModifyDT &ModifiedDT) {
3013 if (!BB->getTerminator())
3014 return false;
3015
3016 ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator());
3017 if (!RetI)
3018 return false;
3019
3020 assert(LI->getLoopFor(BB) == nullptr && "A return block cannot be in a loop");
3021
3022 PHINode *PN = nullptr;
3023 ExtractValueInst *EVI = nullptr;
3024 BitCastInst *BCI = nullptr;
3025 Value *V = RetI->getReturnValue();
3026 if (V) {
3027 BCI = dyn_cast<BitCastInst>(V);
3028 if (BCI)
3029 V = BCI->getOperand(0);
3030
3032 if (EVI) {
3033 V = EVI->getOperand(0);
3034 if (!llvm::all_of(EVI->indices(), equal_to(0)))
3035 return false;
3036 }
3037
3038 PN = dyn_cast<PHINode>(V);
3039 }
3040
3041 if (PN && PN->getParent() != BB)
3042 return false;
3043
3044 auto isLifetimeEndOrBitCastFor = [](const Instruction *Inst) {
3045 const BitCastInst *BC = dyn_cast<BitCastInst>(Inst);
3046 if (BC && BC->hasOneUse())
3047 Inst = BC->user_back();
3048
3049 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst))
3050 return II->getIntrinsicID() == Intrinsic::lifetime_end;
3051 return false;
3052 };
3053
3055
3056 auto isFakeUse = [&FakeUses](const Instruction *Inst) {
3057 if (auto *II = dyn_cast<IntrinsicInst>(Inst);
3058 II && II->getIntrinsicID() == Intrinsic::fake_use) {
3059 // Record the instruction so it can be preserved when the exit block is
3060 // removed. Do not preserve the fake use that uses the result of the
3061 // PHI instruction.
3062 // Do not copy fake uses that use the result of a PHI node.
3063 // FIXME: If we do want to copy the fake use into the return blocks, we
3064 // have to figure out which of the PHI node operands to use for each
3065 // copy.
3066 if (!isa<PHINode>(II->getOperand(0))) {
3067 FakeUses.push_back(II);
3068 }
3069 return true;
3070 }
3071
3072 return false;
3073 };
3074
3075 // Make sure there are no instructions between the first instruction
3076 // and return.
3078 // Skip over pseudo-probes and the bitcast.
3079 while (&*BI == BCI || &*BI == EVI || isa<PseudoProbeInst>(BI) ||
3080 isLifetimeEndOrBitCastFor(&*BI) || isFakeUse(&*BI))
3081 BI = std::next(BI);
3082 if (&*BI != RetI)
3083 return false;
3084
3085 // Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
3086 // call.
3087 auto MayBePermittedAsTailCall = [&](const auto *CI) {
3088 return TLI->mayBeEmittedAsTailCall(CI) &&
3089 attributesPermitTailCall(BB->getParent(), CI, RetI, *TLI);
3090 };
3091
3092 SmallVector<BasicBlock *, 4> TailCallBBs;
3093 // Record the call instructions so we can insert any fake uses
3094 // that need to be preserved before them.
3096 if (PN) {
3097 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
3098 // Look through bitcasts.
3099 Value *IncomingVal = PN->getIncomingValue(I)->stripPointerCasts();
3100 CallInst *CI = dyn_cast<CallInst>(IncomingVal);
3101 BasicBlock *PredBB = PN->getIncomingBlock(I);
3102 // Make sure the phi value is indeed produced by the tail call.
3103 if (CI && CI->hasOneUse() && CI->getParent() == PredBB &&
3104 MayBePermittedAsTailCall(CI)) {
3105 TailCallBBs.push_back(PredBB);
3106 CallInsts.push_back(CI);
3107 } else {
3108 // Consider the cases in which the phi value is indirectly produced by
3109 // the tail call, for example when encountering memset(), memmove(),
3110 // strcpy(), whose return value may have been optimized out. In such
3111 // cases, the value needs to be the first function argument.
3112 //
3113 // bb0:
3114 // tail call void @llvm.memset.p0.i64(ptr %0, i8 0, i64 %1)
3115 // br label %return
3116 // return:
3117 // %phi = phi ptr [ %0, %bb0 ], [ %2, %entry ]
3118 if (PredBB && PredBB->getSingleSuccessor() == BB)
3120 PredBB->getTerminator()->getPrevNode());
3121
3122 if (CI && CI->use_empty() &&
3123 isIntrinsicOrLFToBeTailCalled(TLInfo, CI) &&
3124 IncomingVal == CI->getArgOperand(0) &&
3125 MayBePermittedAsTailCall(CI)) {
3126 TailCallBBs.push_back(PredBB);
3127 CallInsts.push_back(CI);
3128 }
3129 }
3130 }
3131 } else {
3132 SmallPtrSet<BasicBlock *, 4> VisitedBBs;
3133 for (BasicBlock *Pred : predecessors(BB)) {
3134 if (!VisitedBBs.insert(Pred).second)
3135 continue;
3136 if (Instruction *I = Pred->rbegin()->getPrevNode()) {
3137 CallInst *CI = dyn_cast<CallInst>(I);
3138 if (CI && CI->use_empty() && MayBePermittedAsTailCall(CI)) {
3139 // Either we return void or the return value must be the first
3140 // argument of a known intrinsic or library function.
3141 if (!V || isa<UndefValue>(V) ||
3142 (isIntrinsicOrLFToBeTailCalled(TLInfo, CI) &&
3143 V == CI->getArgOperand(0))) {
3144 TailCallBBs.push_back(Pred);
3145 CallInsts.push_back(CI);
3146 }
3147 }
3148 }
3149 }
3150 }
3151
3152 bool Changed = false;
3153 for (auto const &TailCallBB : TailCallBBs) {
3154 // Make sure the call instruction is followed by an unconditional branch to
3155 // the return block.
3156 UncondBrInst *BI = dyn_cast<UncondBrInst>(TailCallBB->getTerminator());
3157 if (!BI || BI->getSuccessor() != BB)
3158 continue;
3159
3160 // Duplicate the return into TailCallBB.
3161 (void)FoldReturnIntoUncondBranch(RetI, BB, TailCallBB, DTU);
3163 BFI->getBlockFreq(BB) >= BFI->getBlockFreq(TailCallBB));
3164 BFI->setBlockFreq(BB,
3165 (BFI->getBlockFreq(BB) - BFI->getBlockFreq(TailCallBB)));
3166 ModifiedDT = ModifyDT::ModifyBBDT;
3167 Changed = true;
3168 ++NumRetsDup;
3169 }
3170
3171 // If we eliminated all predecessors of the block, delete the block now.
3172 if (Changed && !BB->hasAddressTaken() && pred_empty(BB)) {
3173 // Copy the fake uses found in the original return block to all blocks
3174 // that contain tail calls.
3175 for (auto *CI : CallInsts) {
3176 for (auto const *FakeUse : FakeUses) {
3177 auto *ClonedInst = FakeUse->clone();
3178 ClonedInst->insertBefore(CI->getIterator());
3179 }
3180 }
3181 DTU->deleteBB(BB);
3182 }
3183
3184 return Changed;
3185}
3186
3187//===----------------------------------------------------------------------===//
3188// Memory Optimization
3189//===----------------------------------------------------------------------===//
3190
3191namespace {
3192
3193/// This is an extended version of TargetLowering::AddrMode
3194/// which holds actual Value*'s for register values.
3195struct ExtAddrMode : public TargetLowering::AddrMode {
3196 Value *BaseReg = nullptr;
3197 Value *ScaledReg = nullptr;
3198 Value *OriginalValue = nullptr;
3199 bool InBounds = true;
3200
3201 enum FieldName {
3202 NoField = 0x00,
3203 BaseRegField = 0x01,
3204 BaseGVField = 0x02,
3205 BaseOffsField = 0x04,
3206 ScaledRegField = 0x08,
3207 ScaleField = 0x10,
3208 MultipleFields = 0xff
3209 };
3210
3211 ExtAddrMode() = default;
3212
3213 void print(raw_ostream &OS) const;
3214 void dump() const;
3215
3216 // Replace From in ExtAddrMode with To.
3217 // E.g., SExt insts may be promoted and deleted. We should replace them with
3218 // the promoted values.
3219 void replaceWith(Value *From, Value *To) {
3220 if (ScaledReg == From)
3221 ScaledReg = To;
3222 }
3223
3224 FieldName compare(const ExtAddrMode &other) {
3225 // First check that the types are the same on each field, as differing types
3226 // is something we can't cope with later on.
3227 if (BaseReg && other.BaseReg &&
3228 BaseReg->getType() != other.BaseReg->getType())
3229 return MultipleFields;
3230 if (BaseGV && other.BaseGV && BaseGV->getType() != other.BaseGV->getType())
3231 return MultipleFields;
3232 if (ScaledReg && other.ScaledReg &&
3233 ScaledReg->getType() != other.ScaledReg->getType())
3234 return MultipleFields;
3235
3236 // Conservatively reject 'inbounds' mismatches.
3237 if (InBounds != other.InBounds)
3238 return MultipleFields;
3239
3240 // Check each field to see if it differs.
3241 unsigned Result = NoField;
3242 if (BaseReg != other.BaseReg)
3243 Result |= BaseRegField;
3244 if (BaseGV != other.BaseGV)
3245 Result |= BaseGVField;
3246 if (BaseOffs != other.BaseOffs)
3247 Result |= BaseOffsField;
3248 if (ScaledReg != other.ScaledReg)
3249 Result |= ScaledRegField;
3250 // Don't count 0 as being a different scale, because that actually means
3251 // unscaled (which will already be counted by having no ScaledReg).
3252 if (Scale && other.Scale && Scale != other.Scale)
3253 Result |= ScaleField;
3254
3255 if (llvm::popcount(Result) > 1)
3256 return MultipleFields;
3257 else
3258 return static_cast<FieldName>(Result);
3259 }
3260
3261 // An AddrMode is trivial if it involves no calculation i.e. it is just a base
3262 // with no offset.
3263 bool isTrivial() {
3264 // An AddrMode is (BaseGV + BaseReg + BaseOffs + ScaleReg * Scale) so it is
3265 // trivial if at most one of these terms is nonzero, except that BaseGV and
3266 // BaseReg both being zero actually means a null pointer value, which we
3267 // consider to be 'non-zero' here.
3268 return !BaseOffs && !Scale && !(BaseGV && BaseReg);
3269 }
3270
3271 Value *GetFieldAsValue(FieldName Field, Type *IntPtrTy) {
3272 switch (Field) {
3273 default:
3274 return nullptr;
3275 case BaseRegField:
3276 return BaseReg;
3277 case BaseGVField:
3278 return BaseGV;
3279 case ScaledRegField:
3280 return ScaledReg;
3281 case BaseOffsField:
3282 return ConstantInt::getSigned(IntPtrTy, BaseOffs);
3283 }
3284 }
3285
3286 void SetCombinedField(FieldName Field, Value *V,
3287 const SmallVectorImpl<ExtAddrMode> &AddrModes) {
3288 switch (Field) {
3289 default:
3290 llvm_unreachable("Unhandled fields are expected to be rejected earlier");
3291 break;
3292 case ExtAddrMode::BaseRegField:
3293 BaseReg = V;
3294 break;
3295 case ExtAddrMode::BaseGVField:
3296 // A combined BaseGV is an Instruction, not a GlobalValue, so it goes
3297 // in the BaseReg field.
3298 assert(BaseReg == nullptr);
3299 BaseReg = V;
3300 BaseGV = nullptr;
3301 break;
3302 case ExtAddrMode::ScaledRegField:
3303 ScaledReg = V;
3304 // If we have a mix of scaled and unscaled addrmodes then we want scale
3305 // to be the scale and not zero.
3306 if (!Scale)
3307 for (const ExtAddrMode &AM : AddrModes)
3308 if (AM.Scale) {
3309 Scale = AM.Scale;
3310 break;
3311 }
3312 break;
3313 case ExtAddrMode::BaseOffsField:
3314 // The offset is no longer a constant, so it goes in ScaledReg with a
3315 // scale of 1.
3316 assert(ScaledReg == nullptr);
3317 ScaledReg = V;
3318 Scale = 1;
3319 BaseOffs = 0;
3320 break;
3321 }
3322 }
3323};
3324
3325#ifndef NDEBUG
3326static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
3327 AM.print(OS);
3328 return OS;
3329}
3330#endif
3331
3332#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3333void ExtAddrMode::print(raw_ostream &OS) const {
3334 bool NeedPlus = false;
3335 OS << "[";
3336 if (InBounds)
3337 OS << "inbounds ";
3338 if (BaseGV) {
3339 OS << "GV:";
3340 BaseGV->printAsOperand(OS, /*PrintType=*/false);
3341 NeedPlus = true;
3342 }
3343
3344 if (BaseOffs) {
3345 OS << (NeedPlus ? " + " : "") << BaseOffs;
3346 NeedPlus = true;
3347 }
3348
3349 if (BaseReg) {
3350 OS << (NeedPlus ? " + " : "") << "Base:";
3351 BaseReg->printAsOperand(OS, /*PrintType=*/false);
3352 NeedPlus = true;
3353 }
3354 if (Scale) {
3355 OS << (NeedPlus ? " + " : "") << Scale << "*";
3356 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
3357 }
3358
3359 OS << ']';
3360}
3361
3362LLVM_DUMP_METHOD void ExtAddrMode::dump() const {
3363 print(dbgs());
3364 dbgs() << '\n';
3365}
3366#endif
3367
3368} // end anonymous namespace
3369
3370namespace {
3371
3372/// This class provides transaction based operation on the IR.
3373/// Every change made through this class is recorded in the internal state and
3374/// can be undone (rollback) until commit is called.
3375/// CGP does not check if instructions could be speculatively executed when
3376/// moved. Preserving the original location would pessimize the debugging
3377/// experience, as well as negatively impact the quality of sample PGO.
3378class TypePromotionTransaction {
3379 /// This represents the common interface of the individual transaction.
3380 /// Each class implements the logic for doing one specific modification on
3381 /// the IR via the TypePromotionTransaction.
3382 class TypePromotionAction {
3383 protected:
3384 /// The Instruction modified.
3385 Instruction *Inst;
3386
3387 public:
3388 /// Constructor of the action.
3389 /// The constructor performs the related action on the IR.
3390 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
3391
3392 virtual ~TypePromotionAction() = default;
3393
3394 /// Undo the modification done by this action.
3395 /// When this method is called, the IR must be in the same state as it was
3396 /// before this action was applied.
3397 /// \pre Undoing the action works if and only if the IR is in the exact same
3398 /// state as it was directly after this action was applied.
3399 virtual void undo() = 0;
3400
3401 /// Advocate every change made by this action.
3402 /// When the results on the IR of the action are to be kept, it is important
3403 /// to call this function, otherwise hidden information may be kept forever.
3404 virtual void commit() {
3405 // Nothing to be done, this action is not doing anything.
3406 }
3407 };
3408
3409 /// Utility to remember the position of an instruction.
3410 class InsertionHandler {
3411 /// Position of an instruction.
3412 /// Either an instruction:
3413 /// - Is the first in a basic block: BB is used.
3414 /// - Has a previous instruction: PrevInst is used.
3415 struct {
3416 BasicBlock::iterator PrevInst;
3417 BasicBlock *BB;
3418 } Point;
3419 std::optional<DbgRecord::self_iterator> BeforeDbgRecord = std::nullopt;
3420
3421 /// Remember whether or not the instruction had a previous instruction.
3422 bool HasPrevInstruction;
3423
3424 public:
3425 /// Record the position of \p Inst.
3426 InsertionHandler(Instruction *Inst) {
3427 HasPrevInstruction = (Inst != &*(Inst->getParent()->begin()));
3428 BasicBlock *BB = Inst->getParent();
3429
3430 // Record where we would have to re-insert the instruction in the sequence
3431 // of DbgRecords, if we ended up reinserting.
3432 BeforeDbgRecord = Inst->getDbgReinsertionPosition();
3433
3434 if (HasPrevInstruction) {
3435 Point.PrevInst = std::prev(Inst->getIterator());
3436 } else {
3437 Point.BB = BB;
3438 }
3439 }
3440
3441 /// Insert \p Inst at the recorded position.
3442 void insert(Instruction *Inst) {
3443 if (HasPrevInstruction) {
3444 if (Inst->getParent())
3445 Inst->removeFromParent();
3446 Inst->insertAfter(Point.PrevInst);
3447 } else {
3448 BasicBlock::iterator Position = Point.BB->getFirstInsertionPt();
3449 if (Inst->getParent())
3450 Inst->moveBefore(*Point.BB, Position);
3451 else
3452 Inst->insertBefore(*Point.BB, Position);
3453 }
3454
3455 Inst->getParent()->reinsertInstInDbgRecords(Inst, BeforeDbgRecord);
3456 }
3457 };
3458
3459 /// Set the operand of an instruction with a new value.
3460 class OperandSetter : public TypePromotionAction {
3461 /// Original operand of the instruction.
3462 Value *Origin;
3463
3464 /// Index of the modified instruction.
3465 unsigned Idx;
3466
3467 public:
3468 /// Set \p Idx operand of \p Inst with \p NewVal.
3469 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
3470 : TypePromotionAction(Inst), Idx(Idx) {
3471 LLVM_DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
3472 << "for:" << *Inst << "\n"
3473 << "with:" << *NewVal << "\n");
3474 Origin = Inst->getOperand(Idx);
3475 Inst->setOperand(Idx, NewVal);
3476 }
3477
3478 /// Restore the original value of the instruction.
3479 void undo() override {
3480 LLVM_DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
3481 << "for: " << *Inst << "\n"
3482 << "with: " << *Origin << "\n");
3483 Inst->setOperand(Idx, Origin);
3484 }
3485 };
3486
3487 /// Hide the operands of an instruction.
3488 /// Do as if this instruction was not using any of its operands.
3489 class OperandsHider : public TypePromotionAction {
3490 /// The list of original operands.
3491 SmallVector<Value *, 4> OriginalValues;
3492
3493 public:
3494 /// Remove \p Inst from the uses of the operands of \p Inst.
3495 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
3496 LLVM_DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
3497 unsigned NumOpnds = Inst->getNumOperands();
3498 OriginalValues.reserve(NumOpnds);
3499 for (unsigned It = 0; It < NumOpnds; ++It) {
3500 // Save the current operand.
3501 Value *Val = Inst->getOperand(It);
3502 OriginalValues.push_back(Val);
3503 // Set a dummy one.
3504 // We could use OperandSetter here, but that would imply an overhead
3505 // that we are not willing to pay.
3506 Inst->setOperand(It, PoisonValue::get(Val->getType()));
3507 }
3508 }
3509
3510 /// Restore the original list of uses.
3511 void undo() override {
3512 LLVM_DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
3513 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
3514 Inst->setOperand(It, OriginalValues[It]);
3515 }
3516 };
3517
3518 /// Build a truncate instruction.
3519 class TruncBuilder : public TypePromotionAction {
3520 Value *Val;
3521
3522 public:
3523 /// Build a truncate instruction of \p Opnd producing a \p Ty
3524 /// result.
3525 /// trunc Opnd to Ty.
3526 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
3527 IRBuilder<> Builder(Opnd);
3528 Builder.SetCurrentDebugLocation(DebugLoc());
3529 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
3530 LLVM_DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
3531 }
3532
3533 /// Get the built value.
3534 Value *getBuiltValue() { return Val; }
3535
3536 /// Remove the built instruction.
3537 void undo() override {
3538 LLVM_DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
3539 if (Instruction *IVal = dyn_cast<Instruction>(Val))
3540 IVal->eraseFromParent();
3541 }
3542 };
3543
3544 /// Build a sign extension instruction.
3545 class SExtBuilder : public TypePromotionAction {
3546 Value *Val;
3547
3548 public:
3549 /// Build a sign extension instruction of \p Opnd producing a \p Ty
3550 /// result.
3551 /// sext Opnd to Ty.
3552 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
3553 : TypePromotionAction(InsertPt) {
3554 IRBuilder<> Builder(InsertPt);
3555 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
3556 LLVM_DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
3557 }
3558
3559 /// Get the built value.
3560 Value *getBuiltValue() { return Val; }
3561
3562 /// Remove the built instruction.
3563 void undo() override {
3564 LLVM_DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
3565 if (Instruction *IVal = dyn_cast<Instruction>(Val))
3566 IVal->eraseFromParent();
3567 }
3568 };
3569
3570 /// Build a zero extension instruction.
3571 class ZExtBuilder : public TypePromotionAction {
3572 Value *Val;
3573
3574 public:
3575 /// Build a zero extension instruction of \p Opnd producing a \p Ty
3576 /// result.
3577 /// zext Opnd to Ty.
3578 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
3579 : TypePromotionAction(InsertPt) {
3580 IRBuilder<> Builder(InsertPt);
3581 Builder.SetCurrentDebugLocation(DebugLoc());
3582 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
3583 LLVM_DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
3584 }
3585
3586 /// Get the built value.
3587 Value *getBuiltValue() { return Val; }
3588
3589 /// Remove the built instruction.
3590 void undo() override {
3591 LLVM_DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
3592 if (Instruction *IVal = dyn_cast<Instruction>(Val))
3593 IVal->eraseFromParent();
3594 }
3595 };
3596
3597 /// Mutate an instruction to another type.
3598 class TypeMutator : public TypePromotionAction {
3599 /// Record the original type.
3600 Type *OrigTy;
3601
3602 public:
3603 /// Mutate the type of \p Inst into \p NewTy.
3604 TypeMutator(Instruction *Inst, Type *NewTy)
3605 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
3606 LLVM_DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
3607 << "\n");
3608 Inst->mutateType(NewTy);
3609 }
3610
3611 /// Mutate the instruction back to its original type.
3612 void undo() override {
3613 LLVM_DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
3614 << "\n");
3615 Inst->mutateType(OrigTy);
3616 }
3617 };
3618
3619 /// Replace the uses of an instruction by another instruction.
3620 class UsesReplacer : public TypePromotionAction {
3621 /// Helper structure to keep track of the replaced uses.
3622 struct InstructionAndIdx {
3623 /// The instruction using the instruction.
3624 Instruction *Inst;
3625
3626 /// The index where this instruction is used for Inst.
3627 unsigned Idx;
3628
3629 InstructionAndIdx(Instruction *Inst, unsigned Idx)
3630 : Inst(Inst), Idx(Idx) {}
3631 };
3632
3633 /// Keep track of the original uses (pair Instruction, Index).
3635 /// Keep track of the debug users.
3636 SmallVector<DbgVariableRecord *, 1> DbgVariableRecords;
3637
3638 /// Keep track of the new value so that we can undo it by replacing
3639 /// instances of the new value with the original value.
3640 Value *New;
3641
3643
3644 public:
3645 /// Replace all the use of \p Inst by \p New.
3646 UsesReplacer(Instruction *Inst, Value *New)
3647 : TypePromotionAction(Inst), New(New) {
3648 LLVM_DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
3649 << "\n");
3650 // Record the original uses.
3651 for (Use &U : Inst->uses()) {
3652 Instruction *UserI = cast<Instruction>(U.getUser());
3653 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
3654 }
3655 // Record the debug uses separately. They are not in the instruction's
3656 // use list, but they are replaced by RAUW.
3657 findDbgValues(Inst, DbgVariableRecords);
3658
3659 // Now, we can replace the uses.
3660 Inst->replaceAllUsesWith(New);
3661 }
3662
3663 /// Reassign the original uses of Inst to Inst.
3664 void undo() override {
3665 LLVM_DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
3666 for (InstructionAndIdx &Use : OriginalUses)
3667 Use.Inst->setOperand(Use.Idx, Inst);
3668 // RAUW has replaced all original uses with references to the new value,
3669 // including the debug uses. Since we are undoing the replacements,
3670 // the original debug uses must also be reinstated to maintain the
3671 // correctness and utility of debug value records.
3672 for (DbgVariableRecord *DVR : DbgVariableRecords)
3673 DVR->replaceVariableLocationOp(New, Inst);
3674 }
3675 };
3676
3677 /// Remove an instruction from the IR.
3678 class InstructionRemover : public TypePromotionAction {
3679 /// Original position of the instruction.
3680 InsertionHandler Inserter;
3681
3682 /// Helper structure to hide all the link to the instruction. In other
3683 /// words, this helps to do as if the instruction was removed.
3684 OperandsHider Hider;
3685
3686 /// Keep track of the uses replaced, if any.
3687 UsesReplacer *Replacer = nullptr;
3688
3689 /// Keep track of instructions removed.
3690 SetOfInstrs &RemovedInsts;
3691
3692 public:
3693 /// Remove all reference of \p Inst and optionally replace all its
3694 /// uses with New.
3695 /// \p RemovedInsts Keep track of the instructions removed by this Action.
3696 /// \pre If !Inst->use_empty(), then New != nullptr
3697 InstructionRemover(Instruction *Inst, SetOfInstrs &RemovedInsts,
3698 Value *New = nullptr)
3699 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
3700 RemovedInsts(RemovedInsts) {
3701 if (New)
3702 Replacer = new UsesReplacer(Inst, New);
3703 LLVM_DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
3704 RemovedInsts.insert(Inst);
3705 /// The instructions removed here will be freed after completing
3706 /// optimizeBlock() for all blocks as we need to keep track of the
3707 /// removed instructions during promotion.
3708 Inst->removeFromParent();
3709 }
3710
3711 ~InstructionRemover() override { delete Replacer; }
3712
3713 InstructionRemover &operator=(const InstructionRemover &other) = delete;
3714 InstructionRemover(const InstructionRemover &other) = delete;
3715
3716 /// Resurrect the instruction and reassign it to the proper uses if
3717 /// new value was provided when build this action.
3718 void undo() override {
3719 LLVM_DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
3720 Inserter.insert(Inst);
3721 if (Replacer)
3722 Replacer->undo();
3723 Hider.undo();
3724 RemovedInsts.erase(Inst);
3725 }
3726 };
3727
3728public:
3729 /// Restoration point.
3730 /// The restoration point is a pointer to an action instead of an iterator
3731 /// because the iterator may be invalidated but not the pointer.
3732 using ConstRestorationPt = const TypePromotionAction *;
3733
3734 TypePromotionTransaction(SetOfInstrs &RemovedInsts)
3735 : RemovedInsts(RemovedInsts) {}
3736
3737 /// Advocate every changes made in that transaction. Return true if any change
3738 /// happen.
3739 bool commit();
3740
3741 /// Undo all the changes made after the given point.
3742 void rollback(ConstRestorationPt Point);
3743
3744 /// Get the current restoration point.
3745 ConstRestorationPt getRestorationPoint() const;
3746
3747 /// \name API for IR modification with state keeping to support rollback.
3748 /// @{
3749 /// Same as Instruction::setOperand.
3750 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
3751
3752 /// Same as Instruction::eraseFromParent.
3753 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
3754
3755 /// Same as Value::replaceAllUsesWith.
3756 void replaceAllUsesWith(Instruction *Inst, Value *New);
3757
3758 /// Same as Value::mutateType.
3759 void mutateType(Instruction *Inst, Type *NewTy);
3760
3761 /// Same as IRBuilder::createTrunc.
3762 Value *createTrunc(Instruction *Opnd, Type *Ty);
3763
3764 /// Same as IRBuilder::createSExt.
3765 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
3766
3767 /// Same as IRBuilder::createZExt.
3768 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
3769
3770private:
3771 /// The ordered list of actions made so far.
3773
3774 using CommitPt =
3775 SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator;
3776
3777 SetOfInstrs &RemovedInsts;
3778};
3779
3780} // end anonymous namespace
3781
3782void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
3783 Value *NewVal) {
3784 Actions.push_back(std::make_unique<TypePromotionTransaction::OperandSetter>(
3785 Inst, Idx, NewVal));
3786}
3787
3788void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
3789 Value *NewVal) {
3790 Actions.push_back(
3791 std::make_unique<TypePromotionTransaction::InstructionRemover>(
3792 Inst, RemovedInsts, NewVal));
3793}
3794
3795void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
3796 Value *New) {
3797 Actions.push_back(
3798 std::make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
3799}
3800
3801void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
3802 Actions.push_back(
3803 std::make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
3804}
3805
3806Value *TypePromotionTransaction::createTrunc(Instruction *Opnd, Type *Ty) {
3807 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
3808 Value *Val = Ptr->getBuiltValue();
3809 Actions.push_back(std::move(Ptr));
3810 return Val;
3811}
3812
3813Value *TypePromotionTransaction::createSExt(Instruction *Inst, Value *Opnd,
3814 Type *Ty) {
3815 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
3816 Value *Val = Ptr->getBuiltValue();
3817 Actions.push_back(std::move(Ptr));
3818 return Val;
3819}
3820
3821Value *TypePromotionTransaction::createZExt(Instruction *Inst, Value *Opnd,
3822 Type *Ty) {
3823 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
3824 Value *Val = Ptr->getBuiltValue();
3825 Actions.push_back(std::move(Ptr));
3826 return Val;
3827}
3828
3829TypePromotionTransaction::ConstRestorationPt
3830TypePromotionTransaction::getRestorationPoint() const {
3831 return !Actions.empty() ? Actions.back().get() : nullptr;
3832}
3833
3834bool TypePromotionTransaction::commit() {
3835 for (std::unique_ptr<TypePromotionAction> &Action : Actions)
3836 Action->commit();
3837 bool Modified = !Actions.empty();
3838 Actions.clear();
3839 return Modified;
3840}
3841
3842void TypePromotionTransaction::rollback(
3843 TypePromotionTransaction::ConstRestorationPt Point) {
3844 while (!Actions.empty() && Point != Actions.back().get()) {
3845 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
3846 Curr->undo();
3847 }
3848}
3849
3850namespace {
3851
3852/// A helper class for matching addressing modes.
3853///
3854/// This encapsulates the logic for matching the target-legal addressing modes.
3855class AddressingModeMatcher {
3856 SmallVectorImpl<Instruction *> &AddrModeInsts;
3857 const TargetLowering &TLI;
3858 const TargetRegisterInfo &TRI;
3859 const DataLayout &DL;
3860 const LoopInfo &LI;
3861 const std::function<const DominatorTree &()> getDTFn;
3862
3863 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
3864 /// the memory instruction that we're computing this address for.
3865 Type *AccessTy;
3866 unsigned AddrSpace;
3867 Instruction *MemoryInst;
3868
3869 /// This is the addressing mode that we're building up. This is
3870 /// part of the return value of this addressing mode matching stuff.
3871 ExtAddrMode &AddrMode;
3872
3873 /// The instructions inserted by other CodeGenPrepare optimizations.
3874 const SetOfInstrs &InsertedInsts;
3875
3876 /// A map from the instructions to their type before promotion.
3877 InstrToOrigTy &PromotedInsts;
3878
3879 /// The ongoing transaction where every action should be registered.
3880 TypePromotionTransaction &TPT;
3881
3882 // A GEP which has too large offset to be folded into the addressing mode.
3883 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP;
3884
3885 /// This is set to true when we should not do profitability checks.
3886 /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
3887 bool IgnoreProfitability;
3888
3889 /// True if we are optimizing for size.
3890 bool OptSize = false;
3891
3892 ProfileSummaryInfo *PSI;
3893 BlockFrequencyInfo *BFI;
3894
3895 AddressingModeMatcher(
3896 SmallVectorImpl<Instruction *> &AMI, const TargetLowering &TLI,
3897 const TargetRegisterInfo &TRI, const LoopInfo &LI,
3898 const std::function<const DominatorTree &()> getDTFn, Type *AT,
3899 unsigned AS, Instruction *MI, ExtAddrMode &AM,
3900 const SetOfInstrs &InsertedInsts, InstrToOrigTy &PromotedInsts,
3901 TypePromotionTransaction &TPT,
3902 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP,
3903 bool OptSize, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI)
3904 : AddrModeInsts(AMI), TLI(TLI), TRI(TRI),
3905 DL(MI->getDataLayout()), LI(LI), getDTFn(getDTFn),
3906 AccessTy(AT), AddrSpace(AS), MemoryInst(MI), AddrMode(AM),
3907 InsertedInsts(InsertedInsts), PromotedInsts(PromotedInsts), TPT(TPT),
3908 LargeOffsetGEP(LargeOffsetGEP), OptSize(OptSize), PSI(PSI), BFI(BFI) {
3909 IgnoreProfitability = false;
3910 }
3911
3912public:
3913 /// Find the maximal addressing mode that a load/store of V can fold,
3914 /// give an access type of AccessTy. This returns a list of involved
3915 /// instructions in AddrModeInsts.
3916 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
3917 /// optimizations.
3918 /// \p PromotedInsts maps the instructions to their type before promotion.
3919 /// \p The ongoing transaction where every action should be registered.
3920 static ExtAddrMode
3921 Match(Value *V, Type *AccessTy, unsigned AS, Instruction *MemoryInst,
3922 SmallVectorImpl<Instruction *> &AddrModeInsts,
3923 const TargetLowering &TLI, const LoopInfo &LI,
3924 const std::function<const DominatorTree &()> getDTFn,
3925 const TargetRegisterInfo &TRI, const SetOfInstrs &InsertedInsts,
3926 InstrToOrigTy &PromotedInsts, TypePromotionTransaction &TPT,
3927 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP,
3928 bool OptSize, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI) {
3929 ExtAddrMode Result;
3930
3931 bool Success = AddressingModeMatcher(AddrModeInsts, TLI, TRI, LI, getDTFn,
3932 AccessTy, AS, MemoryInst, Result,
3933 InsertedInsts, PromotedInsts, TPT,
3934 LargeOffsetGEP, OptSize, PSI, BFI)
3935 .matchAddr(V, 0);
3936 (void)Success;
3937 assert(Success && "Couldn't select *anything*?");
3938 return Result;
3939 }
3940
3941private:
3942 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
3943 bool matchAddr(Value *Addr, unsigned Depth);
3944 bool matchOperationAddr(User *AddrInst, unsigned Opcode, unsigned Depth,
3945 bool *MovedAway = nullptr);
3946 bool isProfitableToFoldIntoAddressingMode(Instruction *I,
3947 ExtAddrMode &AMBefore,
3948 ExtAddrMode &AMAfter);
3949 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
3950 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
3951 Value *PromotedOperand) const;
3952};
3953
3954class PhiNodeSet;
3955
3956/// An iterator for PhiNodeSet.
3957class PhiNodeSetIterator {
3958 PhiNodeSet *const Set;
3959 size_t CurrentIndex = 0;
3960
3961public:
3962 /// The constructor. Start should point to either a valid element, or be equal
3963 /// to the size of the underlying SmallVector of the PhiNodeSet.
3964 PhiNodeSetIterator(PhiNodeSet *const Set, size_t Start);
3965 PHINode *operator*() const;
3966 PhiNodeSetIterator &operator++();
3967 bool operator==(const PhiNodeSetIterator &RHS) const;
3968 bool operator!=(const PhiNodeSetIterator &RHS) const;
3969};
3970
3971/// Keeps a set of PHINodes.
3972///
3973/// This is a minimal set implementation for a specific use case:
3974/// It is very fast when there are very few elements, but also provides good
3975/// performance when there are many. It is similar to SmallPtrSet, but also
3976/// provides iteration by insertion order, which is deterministic and stable
3977/// across runs. It is also similar to SmallSetVector, but provides removing
3978/// elements in O(1) time. This is achieved by not actually removing the element
3979/// from the underlying vector, so comes at the cost of using more memory, but
3980/// that is fine, since PhiNodeSets are used as short lived objects.
3981class PhiNodeSet {
3982 friend class PhiNodeSetIterator;
3983
3984 using MapType = SmallDenseMap<PHINode *, size_t, 32>;
3985 using iterator = PhiNodeSetIterator;
3986
3987 /// Keeps the elements in the order of their insertion in the underlying
3988 /// vector. To achieve constant time removal, it never deletes any element.
3990
3991 /// Keeps the elements in the underlying set implementation. This (and not the
3992 /// NodeList defined above) is the source of truth on whether an element
3993 /// is actually in the collection.
3994 MapType NodeMap;
3995
3996 /// Points to the first valid (not deleted) element when the set is not empty
3997 /// and the value is not zero. Equals to the size of the underlying vector
3998 /// when the set is empty. When the value is 0, as in the beginning, the
3999 /// first element may or may not be valid.
4000 size_t FirstValidElement = 0;
4001
4002public:
4003 /// Inserts a new element to the collection.
4004 /// \returns true if the element is actually added, i.e. was not in the
4005 /// collection before the operation.
4006 bool insert(PHINode *Ptr) {
4007 if (NodeMap.insert(std::make_pair(Ptr, NodeList.size())).second) {
4008 NodeList.push_back(Ptr);
4009 return true;
4010 }
4011 return false;
4012 }
4013
4014 /// Removes the element from the collection.
4015 /// \returns whether the element is actually removed, i.e. was in the
4016 /// collection before the operation.
4017 bool erase(PHINode *Ptr) {
4018 if (NodeMap.erase(Ptr)) {
4019 SkipRemovedElements(FirstValidElement);
4020 return true;
4021 }
4022 return false;
4023 }
4024
4025 /// Removes all elements and clears the collection.
4026 void clear() {
4027 NodeMap.clear();
4028 NodeList.clear();
4029 FirstValidElement = 0;
4030 }
4031
4032 /// \returns an iterator that will iterate the elements in the order of
4033 /// insertion.
4034 iterator begin() {
4035 if (FirstValidElement == 0)
4036 SkipRemovedElements(FirstValidElement);
4037 return PhiNodeSetIterator(this, FirstValidElement);
4038 }
4039
4040 /// \returns an iterator that points to the end of the collection.
4041 iterator end() { return PhiNodeSetIterator(this, NodeList.size()); }
4042
4043 /// Returns the number of elements in the collection.
4044 size_t size() const { return NodeMap.size(); }
4045
4046 /// \returns 1 if the given element is in the collection, and 0 if otherwise.
4047 size_t count(PHINode *Ptr) const { return NodeMap.count(Ptr); }
4048
4049private:
4050 /// Updates the CurrentIndex so that it will point to a valid element.
4051 ///
4052 /// If the element of NodeList at CurrentIndex is valid, it does not
4053 /// change it. If there are no more valid elements, it updates CurrentIndex
4054 /// to point to the end of the NodeList.
4055 void SkipRemovedElements(size_t &CurrentIndex) {
4056 while (CurrentIndex < NodeList.size()) {
4057 auto it = NodeMap.find(NodeList[CurrentIndex]);
4058 // If the element has been deleted and added again later, NodeMap will
4059 // point to a different index, so CurrentIndex will still be invalid.
4060 if (it != NodeMap.end() && it->second == CurrentIndex)
4061 break;
4062 ++CurrentIndex;
4063 }
4064 }
4065};
4066
4067PhiNodeSetIterator::PhiNodeSetIterator(PhiNodeSet *const Set, size_t Start)
4068 : Set(Set), CurrentIndex(Start) {}
4069
4070PHINode *PhiNodeSetIterator::operator*() const {
4071 assert(CurrentIndex < Set->NodeList.size() &&
4072 "PhiNodeSet access out of range");
4073 return Set->NodeList[CurrentIndex];
4074}
4075
4076PhiNodeSetIterator &PhiNodeSetIterator::operator++() {
4077 assert(CurrentIndex < Set->NodeList.size() &&
4078 "PhiNodeSet access out of range");
4079 ++CurrentIndex;
4080 Set->SkipRemovedElements(CurrentIndex);
4081 return *this;
4082}
4083
4084bool PhiNodeSetIterator::operator==(const PhiNodeSetIterator &RHS) const {
4085 return CurrentIndex == RHS.CurrentIndex;
4086}
4087
4088bool PhiNodeSetIterator::operator!=(const PhiNodeSetIterator &RHS) const {
4089 return !((*this) == RHS);
4090}
4091
4092/// Keep track of simplification of Phi nodes.
4093/// Accept the set of all phi nodes and erase phi node from this set
4094/// if it is simplified.
4095class SimplificationTracker {
4096 DenseMap<Value *, Value *> Storage;
4097 // Tracks newly created Phi nodes. The elements are iterated by insertion
4098 // order.
4099 PhiNodeSet AllPhiNodes;
4100 // Tracks newly created Select nodes.
4101 SmallPtrSet<SelectInst *, 32> AllSelectNodes;
4102
4103public:
4104 Value *Get(Value *V) {
4105 do {
4106 auto SV = Storage.find(V);
4107 if (SV == Storage.end())
4108 return V;
4109 V = SV->second;
4110 } while (true);
4111 }
4112
4113 void Put(Value *From, Value *To) { Storage.insert({From, To}); }
4114
4115 void ReplacePhi(PHINode *From, PHINode *To) {
4116 Value *OldReplacement = Get(From);
4117 while (OldReplacement != From) {
4118 From = To;
4119 To = dyn_cast<PHINode>(OldReplacement);
4120 OldReplacement = Get(From);
4121 }
4122 assert(To && Get(To) == To && "Replacement PHI node is already replaced.");
4123 Put(From, To);
4124 From->replaceAllUsesWith(To);
4125 AllPhiNodes.erase(From);
4126 From->eraseFromParent();
4127 }
4128
4129 PhiNodeSet &newPhiNodes() { return AllPhiNodes; }
4130
4131 void insertNewPhi(PHINode *PN) { AllPhiNodes.insert(PN); }
4132
4133 void insertNewSelect(SelectInst *SI) { AllSelectNodes.insert(SI); }
4134
4135 unsigned countNewPhiNodes() const { return AllPhiNodes.size(); }
4136
4137 unsigned countNewSelectNodes() const { return AllSelectNodes.size(); }
4138
4139 void destroyNewNodes(Type *CommonType) {
4140 // For safe erasing, replace the uses with dummy value first.
4141 auto *Dummy = PoisonValue::get(CommonType);
4142 for (auto *I : AllPhiNodes) {
4143 I->replaceAllUsesWith(Dummy);
4144 I->eraseFromParent();
4145 }
4146 AllPhiNodes.clear();
4147 for (auto *I : AllSelectNodes) {
4148 I->replaceAllUsesWith(Dummy);
4149 I->eraseFromParent();
4150 }
4151 AllSelectNodes.clear();
4152 }
4153};
4154
4155/// A helper class for combining addressing modes.
4156class AddressingModeCombiner {
4157 typedef DenseMap<Value *, Value *> FoldAddrToValueMapping;
4158 typedef std::pair<PHINode *, PHINode *> PHIPair;
4159
4160private:
4161 /// The addressing modes we've collected.
4163
4164 /// The field in which the AddrModes differ, when we have more than one.
4165 ExtAddrMode::FieldName DifferentField = ExtAddrMode::NoField;
4166
4167 /// Are the AddrModes that we have all just equal to their original values?
4168 bool AllAddrModesTrivial = true;
4169
4170 /// Common Type for all different fields in addressing modes.
4171 Type *CommonType = nullptr;
4172
4173 const DataLayout &DL;
4174
4175 /// Original Address.
4176 Value *Original;
4177
4178 /// Common value among addresses
4179 Value *CommonValue = nullptr;
4180
4181public:
4182 AddressingModeCombiner(const DataLayout &DL, Value *OriginalValue)
4183 : DL(DL), Original(OriginalValue) {}
4184
4185 ~AddressingModeCombiner() { eraseCommonValueIfDead(); }
4186
4187 /// Get the combined AddrMode
4188 const ExtAddrMode &getAddrMode() const { return AddrModes[0]; }
4189
4190 /// Add a new AddrMode if it's compatible with the AddrModes we already
4191 /// have.
4192 /// \return True iff we succeeded in doing so.
4193 bool addNewAddrMode(ExtAddrMode &NewAddrMode) {
4194 // Take note of if we have any non-trivial AddrModes, as we need to detect
4195 // when all AddrModes are trivial as then we would introduce a phi or select
4196 // which just duplicates what's already there.
4197 AllAddrModesTrivial = AllAddrModesTrivial && NewAddrMode.isTrivial();
4198
4199 // If this is the first addrmode then everything is fine.
4200 if (AddrModes.empty()) {
4201 AddrModes.emplace_back(NewAddrMode);
4202 return true;
4203 }
4204
4205 // Figure out how different this is from the other address modes, which we
4206 // can do just by comparing against the first one given that we only care
4207 // about the cumulative difference.
4208 ExtAddrMode::FieldName ThisDifferentField =
4209 AddrModes[0].compare(NewAddrMode);
4210 if (DifferentField == ExtAddrMode::NoField)
4211 DifferentField = ThisDifferentField;
4212 else if (DifferentField != ThisDifferentField)
4213 DifferentField = ExtAddrMode::MultipleFields;
4214
4215 // If NewAddrMode differs in more than one dimension we cannot handle it.
4216 bool CanHandle = DifferentField != ExtAddrMode::MultipleFields;
4217
4218 // If Scale Field is different then we reject.
4219 CanHandle = CanHandle && DifferentField != ExtAddrMode::ScaleField;
4220
4221 // We also must reject the case when base offset is different and
4222 // scale reg is not null, we cannot handle this case due to merge of
4223 // different offsets will be used as ScaleReg.
4224 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseOffsField ||
4225 !NewAddrMode.ScaledReg);
4226
4227 // We also must reject the case when GV is different and BaseReg installed
4228 // due to we want to use base reg as a merge of GV values.
4229 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseGVField ||
4230 !NewAddrMode.HasBaseReg);
4231
4232 // Even if NewAddMode is the same we still need to collect it due to
4233 // original value is different. And later we will need all original values
4234 // as anchors during finding the common Phi node.
4235 if (CanHandle)
4236 AddrModes.emplace_back(NewAddrMode);
4237 else
4238 AddrModes.clear();
4239
4240 return CanHandle;
4241 }
4242
4243 /// Combine the addressing modes we've collected into a single
4244 /// addressing mode.
4245 /// \return True iff we successfully combined them or we only had one so
4246 /// didn't need to combine them anyway.
4247 bool combineAddrModes() {
4248 // If we have no AddrModes then they can't be combined.
4249 if (AddrModes.size() == 0)
4250 return false;
4251
4252 // A single AddrMode can trivially be combined.
4253 if (AddrModes.size() == 1 || DifferentField == ExtAddrMode::NoField)
4254 return true;
4255
4256 // If the AddrModes we collected are all just equal to the value they are
4257 // derived from then combining them wouldn't do anything useful.
4258 if (AllAddrModesTrivial)
4259 return false;
4260
4261 if (!addrModeCombiningAllowed())
4262 return false;
4263
4264 // Build a map between <original value, basic block where we saw it> to
4265 // value of base register.
4266 // Bail out if there is no common type.
4267 FoldAddrToValueMapping Map;
4268 if (!initializeMap(Map))
4269 return false;
4270
4271 CommonValue = findCommon(Map);
4272 if (CommonValue)
4273 AddrModes[0].SetCombinedField(DifferentField, CommonValue, AddrModes);
4274 return CommonValue != nullptr;
4275 }
4276
4277private:
4278 /// `CommonValue` may be a placeholder inserted by us.
4279 /// If the placeholder is not used, we should remove this dead instruction.
4280 void eraseCommonValueIfDead() {
4281 if (CommonValue && CommonValue->use_empty())
4282 if (Instruction *CommonInst = dyn_cast<Instruction>(CommonValue))
4283 CommonInst->eraseFromParent();
4284 }
4285
4286 /// Initialize Map with anchor values. For address seen
4287 /// we set the value of different field saw in this address.
4288 /// At the same time we find a common type for different field we will
4289 /// use to create new Phi/Select nodes. Keep it in CommonType field.
4290 /// Return false if there is no common type found.
4291 bool initializeMap(FoldAddrToValueMapping &Map) {
4292 // Keep track of keys where the value is null. We will need to replace it
4293 // with constant null when we know the common type.
4294 SmallVector<Value *, 2> NullValue;
4295 Type *IntPtrTy = DL.getIntPtrType(AddrModes[0].OriginalValue->getType());
4296 for (auto &AM : AddrModes) {
4297 Value *DV = AM.GetFieldAsValue(DifferentField, IntPtrTy);
4298 if (DV) {
4299 auto *Type = DV->getType();
4300 if (CommonType && CommonType != Type)
4301 return false;
4302 CommonType = Type;
4303 Map[AM.OriginalValue] = DV;
4304 } else {
4305 NullValue.push_back(AM.OriginalValue);
4306 }
4307 }
4308 assert(CommonType && "At least one non-null value must be!");
4309 for (auto *V : NullValue)
4310 Map[V] = Constant::getNullValue(CommonType);
4311 return true;
4312 }
4313
4314 /// We have mapping between value A and other value B where B was a field in
4315 /// addressing mode represented by A. Also we have an original value C
4316 /// representing an address we start with. Traversing from C through phi and
4317 /// selects we ended up with A's in a map. This utility function tries to find
4318 /// a value V which is a field in addressing mode C and traversing through phi
4319 /// nodes and selects we will end up in corresponded values B in a map.
4320 /// The utility will create a new Phi/Selects if needed.
4321 // The simple example looks as follows:
4322 // BB1:
4323 // p1 = b1 + 40
4324 // br cond BB2, BB3
4325 // BB2:
4326 // p2 = b2 + 40
4327 // br BB3
4328 // BB3:
4329 // p = phi [p1, BB1], [p2, BB2]
4330 // v = load p
4331 // Map is
4332 // p1 -> b1
4333 // p2 -> b2
4334 // Request is
4335 // p -> ?
4336 // The function tries to find or build phi [b1, BB1], [b2, BB2] in BB3.
4337 Value *findCommon(FoldAddrToValueMapping &Map) {
4338 // Tracks the simplification of newly created phi nodes. The reason we use
4339 // this mapping is because we will add new created Phi nodes in AddrToBase.
4340 // Simplification of Phi nodes is recursive, so some Phi node may
4341 // be simplified after we added it to AddrToBase. In reality this
4342 // simplification is possible only if original phi/selects were not
4343 // simplified yet.
4344 // Using this mapping we can find the current value in AddrToBase.
4345 SimplificationTracker ST;
4346
4347 // First step, DFS to create PHI nodes for all intermediate blocks.
4348 // Also fill traverse order for the second step.
4349 SmallVector<Value *, 32> TraverseOrder;
4350 InsertPlaceholders(Map, TraverseOrder, ST);
4351
4352 // Second Step, fill new nodes by merged values and simplify if possible.
4353 FillPlaceholders(Map, TraverseOrder, ST);
4354
4355 if (!AddrSinkNewSelects && ST.countNewSelectNodes() > 0) {
4356 ST.destroyNewNodes(CommonType);
4357 return nullptr;
4358 }
4359
4360 // Now we'd like to match New Phi nodes to existed ones.
4361 unsigned PhiNotMatchedCount = 0;
4362 if (!MatchPhiSet(ST, AddrSinkNewPhis, PhiNotMatchedCount)) {
4363 ST.destroyNewNodes(CommonType);
4364 return nullptr;
4365 }
4366
4367 auto *Result = ST.Get(Map.find(Original)->second);
4368 if (Result) {
4369 NumMemoryInstsPhiCreated += ST.countNewPhiNodes() + PhiNotMatchedCount;
4370 NumMemoryInstsSelectCreated += ST.countNewSelectNodes();
4371 }
4372 return Result;
4373 }
4374
4375 /// Try to match PHI node to Candidate.
4376 /// Matcher tracks the matched Phi nodes.
4377 bool MatchPhiNode(PHINode *PHI, PHINode *Candidate,
4378 SmallSetVector<PHIPair, 8> &Matcher,
4379 PhiNodeSet &PhiNodesToMatch) {
4380 SmallVector<PHIPair, 8> WorkList;
4381 Matcher.insert({PHI, Candidate});
4382 SmallPtrSet<PHINode *, 8> MatchedPHIs;
4383 MatchedPHIs.insert(PHI);
4384 WorkList.push_back({PHI, Candidate});
4385 SmallSet<PHIPair, 8> Visited;
4386 while (!WorkList.empty()) {
4387 auto Item = WorkList.pop_back_val();
4388 if (!Visited.insert(Item).second)
4389 continue;
4390 // We iterate over all incoming values to Phi to compare them.
4391 // If values are different and both of them Phi and the first one is a
4392 // Phi we added (subject to match) and both of them is in the same basic
4393 // block then we can match our pair if values match. So we state that
4394 // these values match and add it to work list to verify that.
4395 for (auto *B : Item.first->blocks()) {
4396 Value *FirstValue = Item.first->getIncomingValueForBlock(B);
4397 Value *SecondValue = Item.second->getIncomingValueForBlock(B);
4398 if (FirstValue == SecondValue)
4399 continue;
4400
4401 PHINode *FirstPhi = dyn_cast<PHINode>(FirstValue);
4402 PHINode *SecondPhi = dyn_cast<PHINode>(SecondValue);
4403
4404 // One of them is not Phi or
4405 // The first one is not Phi node from the set we'd like to match or
4406 // Phi nodes from different basic blocks then
4407 // we will not be able to match.
4408 if (!FirstPhi || !SecondPhi || !PhiNodesToMatch.count(FirstPhi) ||
4409 FirstPhi->getParent() != SecondPhi->getParent())
4410 return false;
4411
4412 // If we already matched them then continue.
4413 if (Matcher.count({FirstPhi, SecondPhi}))
4414 continue;
4415 // So the values are different and does not match. So we need them to
4416 // match. (But we register no more than one match per PHI node, so that
4417 // we won't later try to replace them twice.)
4418 if (MatchedPHIs.insert(FirstPhi).second)
4419 Matcher.insert({FirstPhi, SecondPhi});
4420 // But me must check it.
4421 WorkList.push_back({FirstPhi, SecondPhi});
4422 }
4423 }
4424 return true;
4425 }
4426
4427 /// For the given set of PHI nodes (in the SimplificationTracker) try
4428 /// to find their equivalents.
4429 /// Returns false if this matching fails and creation of new Phi is disabled.
4430 bool MatchPhiSet(SimplificationTracker &ST, bool AllowNewPhiNodes,
4431 unsigned &PhiNotMatchedCount) {
4432 // Matched and PhiNodesToMatch iterate their elements in a deterministic
4433 // order, so the replacements (ReplacePhi) are also done in a deterministic
4434 // order.
4435 SmallSetVector<PHIPair, 8> Matched;
4436 SmallPtrSet<PHINode *, 8> WillNotMatch;
4437 PhiNodeSet &PhiNodesToMatch = ST.newPhiNodes();
4438 while (PhiNodesToMatch.size()) {
4439 PHINode *PHI = *PhiNodesToMatch.begin();
4440
4441 // Add us, if no Phi nodes in the basic block we do not match.
4442 WillNotMatch.clear();
4443 WillNotMatch.insert(PHI);
4444
4445 // Traverse all Phis until we found equivalent or fail to do that.
4446 bool IsMatched = false;
4447 for (auto &P : PHI->getParent()->phis()) {
4448 // Skip new Phi nodes.
4449 if (PhiNodesToMatch.count(&P))
4450 continue;
4451 if ((IsMatched = MatchPhiNode(PHI, &P, Matched, PhiNodesToMatch)))
4452 break;
4453 // If it does not match, collect all Phi nodes from matcher.
4454 // if we end up with no match, them all these Phi nodes will not match
4455 // later.
4456 WillNotMatch.insert_range(llvm::make_first_range(Matched));
4457 Matched.clear();
4458 }
4459 if (IsMatched) {
4460 // Replace all matched values and erase them.
4461 for (auto MV : Matched)
4462 ST.ReplacePhi(MV.first, MV.second);
4463 Matched.clear();
4464 continue;
4465 }
4466 // If we are not allowed to create new nodes then bail out.
4467 if (!AllowNewPhiNodes)
4468 return false;
4469 // Just remove all seen values in matcher. They will not match anything.
4470 PhiNotMatchedCount += WillNotMatch.size();
4471 for (auto *P : WillNotMatch)
4472 PhiNodesToMatch.erase(P);
4473 }
4474 return true;
4475 }
4476 /// Fill the placeholders with values from predecessors and simplify them.
4477 void FillPlaceholders(FoldAddrToValueMapping &Map,
4478 SmallVectorImpl<Value *> &TraverseOrder,
4479 SimplificationTracker &ST) {
4480 while (!TraverseOrder.empty()) {
4481 Value *Current = TraverseOrder.pop_back_val();
4482 assert(Map.contains(Current) && "No node to fill!!!");
4483 Value *V = Map[Current];
4484
4485 if (SelectInst *Select = dyn_cast<SelectInst>(V)) {
4486 // CurrentValue also must be Select.
4487 auto *CurrentSelect = cast<SelectInst>(Current);
4488 auto *TrueValue = CurrentSelect->getTrueValue();
4489 assert(Map.contains(TrueValue) && "No True Value!");
4490 Select->setTrueValue(ST.Get(Map[TrueValue]));
4491 auto *FalseValue = CurrentSelect->getFalseValue();
4492 assert(Map.contains(FalseValue) && "No False Value!");
4493 Select->setFalseValue(ST.Get(Map[FalseValue]));
4494 } else {
4495 // Must be a Phi node then.
4496 auto *PHI = cast<PHINode>(V);
4497 // Fill the Phi node with values from predecessors.
4498 for (auto *B : predecessors(PHI->getParent())) {
4499 Value *PV = cast<PHINode>(Current)->getIncomingValueForBlock(B);
4500 assert(Map.contains(PV) && "No predecessor Value!");
4501 PHI->addIncoming(ST.Get(Map[PV]), B);
4502 }
4503 }
4504 }
4505 }
4506
4507 /// Starting from original value recursively iterates over def-use chain up to
4508 /// known ending values represented in a map. For each traversed phi/select
4509 /// inserts a placeholder Phi or Select.
4510 /// Reports all new created Phi/Select nodes by adding them to set.
4511 /// Also reports and order in what values have been traversed.
4512 void InsertPlaceholders(FoldAddrToValueMapping &Map,
4513 SmallVectorImpl<Value *> &TraverseOrder,
4514 SimplificationTracker &ST) {
4515 SmallVector<Value *, 32> Worklist;
4516 assert((isa<PHINode>(Original) || isa<SelectInst>(Original)) &&
4517 "Address must be a Phi or Select node");
4518 auto *Dummy = PoisonValue::get(CommonType);
4519 Worklist.push_back(Original);
4520 while (!Worklist.empty()) {
4521 Value *Current = Worklist.pop_back_val();
4522 // if it is already visited or it is an ending value then skip it.
4523 if (Map.contains(Current))
4524 continue;
4525 TraverseOrder.push_back(Current);
4526
4527 // CurrentValue must be a Phi node or select. All others must be covered
4528 // by anchors.
4529 if (SelectInst *CurrentSelect = dyn_cast<SelectInst>(Current)) {
4530 // Is it OK to get metadata from OrigSelect?!
4531 // Create a Select placeholder with dummy value.
4532 SelectInst *Select =
4533 SelectInst::Create(CurrentSelect->getCondition(), Dummy, Dummy,
4534 CurrentSelect->getName(),
4535 CurrentSelect->getIterator(), CurrentSelect);
4536 Map[Current] = Select;
4537 ST.insertNewSelect(Select);
4538 // We are interested in True and False values.
4539 Worklist.push_back(CurrentSelect->getTrueValue());
4540 Worklist.push_back(CurrentSelect->getFalseValue());
4541 } else {
4542 // It must be a Phi node then.
4543 PHINode *CurrentPhi = cast<PHINode>(Current);
4544 unsigned PredCount = CurrentPhi->getNumIncomingValues();
4545 PHINode *PHI =
4546 PHINode::Create(CommonType, PredCount, "sunk_phi", CurrentPhi->getIterator());
4547 Map[Current] = PHI;
4548 ST.insertNewPhi(PHI);
4549 append_range(Worklist, CurrentPhi->incoming_values());
4550 }
4551 }
4552 }
4553
4554 bool addrModeCombiningAllowed() {
4556 return false;
4557 switch (DifferentField) {
4558 default:
4559 return false;
4560 case ExtAddrMode::BaseRegField:
4562 case ExtAddrMode::BaseGVField:
4563 return AddrSinkCombineBaseGV;
4564 case ExtAddrMode::BaseOffsField:
4566 case ExtAddrMode::ScaledRegField:
4568 }
4569 }
4570};
4571} // end anonymous namespace
4572
4573/// Try adding ScaleReg*Scale to the current addressing mode.
4574/// Return true and update AddrMode if this addr mode is legal for the target,
4575/// false if not.
4576bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
4577 unsigned Depth) {
4578 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
4579 // mode. Just process that directly.
4580 if (Scale == 1)
4581 return matchAddr(ScaleReg, Depth);
4582
4583 // If the scale is 0, it takes nothing to add this.
4584 if (Scale == 0)
4585 return true;
4586
4587 // If we already have a scale of this value, we can add to it, otherwise, we
4588 // need an available scale field.
4589 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
4590 return false;
4591
4592 ExtAddrMode TestAddrMode = AddrMode;
4593
4594 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
4595 // [A+B + A*7] -> [B+A*8].
4596 TestAddrMode.Scale += Scale;
4597 TestAddrMode.ScaledReg = ScaleReg;
4598
4599 // If the new address isn't legal, bail out.
4600 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
4601 return false;
4602
4603 // It was legal, so commit it.
4604 AddrMode = TestAddrMode;
4605
4606 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
4607 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
4608 // X*Scale + C*Scale to addr mode. If we found available IV increment, do not
4609 // go any further: we can reuse it and cannot eliminate it.
4610 ConstantInt *CI = nullptr;
4611 Value *AddLHS = nullptr;
4612 if (isa<Instruction>(ScaleReg) && // not a constant expr.
4613 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI))) &&
4614 !isIVIncrement(ScaleReg, &LI) && CI->getValue().isSignedIntN(64)) {
4615 TestAddrMode.InBounds = false;
4616 TestAddrMode.ScaledReg = AddLHS;
4617 TestAddrMode.BaseOffs += CI->getSExtValue() * TestAddrMode.Scale;
4618
4619 // If this addressing mode is legal, commit it and remember that we folded
4620 // this instruction.
4621 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
4622 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
4623 AddrMode = TestAddrMode;
4624 return true;
4625 }
4626 // Restore status quo.
4627 TestAddrMode = AddrMode;
4628 }
4629
4630 // If this is an add recurrence with a constant step, return the increment
4631 // instruction and the canonicalized step.
4632 auto GetConstantStep =
4633 [this](const Value *V) -> std::optional<std::pair<Instruction *, APInt>> {
4634 auto *PN = dyn_cast<PHINode>(V);
4635 if (!PN)
4636 return std::nullopt;
4637 auto IVInc = getIVIncrement(PN, &LI);
4638 if (!IVInc)
4639 return std::nullopt;
4640 // TODO: The result of the intrinsics above is two-complement. However when
4641 // IV inc is expressed as add or sub, iv.next is potentially a poison value.
4642 // If it has nuw or nsw flags, we need to make sure that these flags are
4643 // inferrable at the point of memory instruction. Otherwise we are replacing
4644 // well-defined two-complement computation with poison. Currently, to avoid
4645 // potentially complex analysis needed to prove this, we reject such cases.
4646 if (auto *OIVInc = dyn_cast<OverflowingBinaryOperator>(IVInc->first))
4647 if (OIVInc->hasNoSignedWrap() || OIVInc->hasNoUnsignedWrap())
4648 return std::nullopt;
4649 if (auto *ConstantStep = dyn_cast<ConstantInt>(IVInc->second))
4650 return std::make_pair(IVInc->first, ConstantStep->getValue());
4651 return std::nullopt;
4652 };
4653
4654 // Try to account for the following special case:
4655 // 1. ScaleReg is an inductive variable;
4656 // 2. We use it with non-zero offset;
4657 // 3. IV's increment is available at the point of memory instruction.
4658 //
4659 // In this case, we may reuse the IV increment instead of the IV Phi to
4660 // achieve the following advantages:
4661 // 1. If IV step matches the offset, we will have no need in the offset;
4662 // 2. Even if they don't match, we will reduce the overlap of living IV
4663 // and IV increment, that will potentially lead to better register
4664 // assignment.
4665 if (AddrMode.BaseOffs) {
4666 if (auto IVStep = GetConstantStep(ScaleReg)) {
4667 Instruction *IVInc = IVStep->first;
4668 // The following assert is important to ensure a lack of infinite loops.
4669 // This transforms is (intentionally) the inverse of the one just above.
4670 // If they don't agree on the definition of an increment, we'd alternate
4671 // back and forth indefinitely.
4672 assert(isIVIncrement(IVInc, &LI) && "implied by GetConstantStep");
4673 APInt Step = IVStep->second;
4674 APInt Offset = Step * AddrMode.Scale;
4675 if (Offset.isSignedIntN(64)) {
4676 TestAddrMode.InBounds = false;
4677 TestAddrMode.ScaledReg = IVInc;
4678 TestAddrMode.BaseOffs -= Offset.getLimitedValue();
4679 // If this addressing mode is legal, commit it..
4680 // (Note that we defer the (expensive) domtree base legality check
4681 // to the very last possible point.)
4682 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace) &&
4683 getDTFn().dominates(IVInc, MemoryInst)) {
4684 AddrModeInsts.push_back(cast<Instruction>(IVInc));
4685 AddrMode = TestAddrMode;
4686 return true;
4687 }
4688 // Restore status quo.
4689 TestAddrMode = AddrMode;
4690 }
4691 }
4692 }
4693
4694 // Otherwise, just return what we have.
4695 return true;
4696}
4697
4698/// This is a little filter, which returns true if an addressing computation
4699/// involving I might be folded into a load/store accessing it.
4700/// This doesn't need to be perfect, but needs to accept at least
4701/// the set of instructions that MatchOperationAddr can.
4703 switch (I->getOpcode()) {
4704 case Instruction::BitCast:
4705 case Instruction::AddrSpaceCast:
4706 // Don't touch identity bitcasts.
4707 if (I->getType() == I->getOperand(0)->getType())
4708 return false;
4709 return I->getType()->isIntOrPtrTy();
4710 case Instruction::PtrToInt:
4711 // PtrToInt is always a noop, as we know that the int type is pointer sized.
4712 return true;
4713 case Instruction::IntToPtr:
4714 // We know the input is intptr_t, so this is foldable.
4715 return true;
4716 case Instruction::Add:
4717 return true;
4718 case Instruction::Mul:
4719 case Instruction::Shl:
4720 // Can only handle X*C and X << C.
4721 return isa<ConstantInt>(I->getOperand(1));
4722 case Instruction::GetElementPtr:
4723 return true;
4724 default:
4725 return false;
4726 }
4727}
4728
4729/// Check whether or not \p Val is a legal instruction for \p TLI.
4730/// \note \p Val is assumed to be the product of some type promotion.
4731/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
4732/// to be legal, as the non-promoted value would have had the same state.
4734 const DataLayout &DL, Value *Val) {
4735 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
4736 if (!PromotedInst)
4737 return false;
4738 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
4739 // If the ISDOpcode is undefined, it was undefined before the promotion.
4740 if (!ISDOpcode)
4741 return true;
4742 // Otherwise, check if the promoted instruction is legal or not.
4743 return TLI.isOperationLegalOrCustom(
4744 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
4745}
4746
4747namespace {
4748
4749/// Hepler class to perform type promotion.
4750class TypePromotionHelper {
4751 /// Utility function to add a promoted instruction \p ExtOpnd to
4752 /// \p PromotedInsts and record the type of extension we have seen.
4753 static void addPromotedInst(InstrToOrigTy &PromotedInsts,
4754 Instruction *ExtOpnd, bool IsSExt) {
4755 ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension;
4756 auto [It, Inserted] = PromotedInsts.try_emplace(ExtOpnd);
4757 if (!Inserted) {
4758 // If the new extension is same as original, the information in
4759 // PromotedInsts[ExtOpnd] is still correct.
4760 if (It->second.getInt() == ExtTy)
4761 return;
4762
4763 // Now the new extension is different from old extension, we make
4764 // the type information invalid by setting extension type to
4765 // BothExtension.
4766 ExtTy = BothExtension;
4767 }
4768 It->second = TypeIsSExt(ExtOpnd->getType(), ExtTy);
4769 }
4770
4771 /// Utility function to query the original type of instruction \p Opnd
4772 /// with a matched extension type. If the extension doesn't match, we
4773 /// cannot use the information we had on the original type.
4774 /// BothExtension doesn't match any extension type.
4775 static const Type *getOrigType(const InstrToOrigTy &PromotedInsts,
4776 Instruction *Opnd, bool IsSExt) {
4777 ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension;
4778 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
4779 if (It != PromotedInsts.end() && It->second.getInt() == ExtTy)
4780 return It->second.getPointer();
4781 return nullptr;
4782 }
4783
4784 /// Utility function to check whether or not a sign or zero extension
4785 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
4786 /// either using the operands of \p Inst or promoting \p Inst.
4787 /// The type of the extension is defined by \p IsSExt.
4788 /// In other words, check if:
4789 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
4790 /// #1 Promotion applies:
4791 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
4792 /// #2 Operand reuses:
4793 /// ext opnd1 to ConsideredExtType.
4794 /// \p PromotedInsts maps the instructions to their type before promotion.
4795 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
4796 const InstrToOrigTy &PromotedInsts, bool IsSExt);
4797
4798 /// Utility function to determine if \p OpIdx should be promoted when
4799 /// promoting \p Inst.
4800 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
4801 return !(isa<SelectInst>(Inst) && OpIdx == 0);
4802 }
4803
4804 /// Utility function to promote the operand of \p Ext when this
4805 /// operand is a promotable trunc or sext or zext.
4806 /// \p PromotedInsts maps the instructions to their type before promotion.
4807 /// \p CreatedInstsCost[out] contains the cost of all instructions
4808 /// created to promote the operand of Ext.
4809 /// Newly added extensions are inserted in \p Exts.
4810 /// Newly added truncates are inserted in \p Truncs.
4811 /// Should never be called directly.
4812 /// \return The promoted value which is used instead of Ext.
4813 static Value *promoteOperandForTruncAndAnyExt(
4814 Instruction *Ext, TypePromotionTransaction &TPT,
4815 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4816 SmallVectorImpl<Instruction *> *Exts,
4817 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
4818
4819 /// Utility function to promote the operand of \p Ext when this
4820 /// operand is promotable and is not a supported trunc or sext.
4821 /// \p PromotedInsts maps the instructions to their type before promotion.
4822 /// \p CreatedInstsCost[out] contains the cost of all the instructions
4823 /// created to promote the operand of Ext.
4824 /// Newly added extensions are inserted in \p Exts.
4825 /// Newly added truncates are inserted in \p Truncs.
4826 /// Should never be called directly.
4827 /// \return The promoted value which is used instead of Ext.
4828 static Value *promoteOperandForOther(Instruction *Ext,
4829 TypePromotionTransaction &TPT,
4830 InstrToOrigTy &PromotedInsts,
4831 unsigned &CreatedInstsCost,
4832 SmallVectorImpl<Instruction *> *Exts,
4833 SmallVectorImpl<Instruction *> *Truncs,
4834 const TargetLowering &TLI, bool IsSExt);
4835
4836 /// \see promoteOperandForOther.
4837 static Value *signExtendOperandForOther(
4838 Instruction *Ext, TypePromotionTransaction &TPT,
4839 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4840 SmallVectorImpl<Instruction *> *Exts,
4841 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
4842 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
4843 Exts, Truncs, TLI, true);
4844 }
4845
4846 /// \see promoteOperandForOther.
4847 static Value *zeroExtendOperandForOther(
4848 Instruction *Ext, TypePromotionTransaction &TPT,
4849 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4850 SmallVectorImpl<Instruction *> *Exts,
4851 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
4852 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
4853 Exts, Truncs, TLI, false);
4854 }
4855
4856public:
4857 /// Type for the utility function that promotes the operand of Ext.
4858 using Action = Value *(*)(Instruction *Ext, TypePromotionTransaction &TPT,
4859 InstrToOrigTy &PromotedInsts,
4860 unsigned &CreatedInstsCost,
4861 SmallVectorImpl<Instruction *> *Exts,
4862 SmallVectorImpl<Instruction *> *Truncs,
4863 const TargetLowering &TLI);
4864
4865 /// Given a sign/zero extend instruction \p Ext, return the appropriate
4866 /// action to promote the operand of \p Ext instead of using Ext.
4867 /// \return NULL if no promotable action is possible with the current
4868 /// sign extension.
4869 /// \p InsertedInsts keeps track of all the instructions inserted by the
4870 /// other CodeGenPrepare optimizations. This information is important
4871 /// because we do not want to promote these instructions as CodeGenPrepare
4872 /// will reinsert them later. Thus creating an infinite loop: create/remove.
4873 /// \p PromotedInsts maps the instructions to their type before promotion.
4874 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
4875 const TargetLowering &TLI,
4876 const InstrToOrigTy &PromotedInsts);
4877};
4878
4879} // end anonymous namespace
4880
4881bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
4882 Type *ConsideredExtType,
4883 const InstrToOrigTy &PromotedInsts,
4884 bool IsSExt) {
4885 // The promotion helper does not know how to deal with vector types yet.
4886 // To be able to fix that, we would need to fix the places where we
4887 // statically extend, e.g., constants and such.
4888 if (Inst->getType()->isVectorTy())
4889 return false;
4890
4891 // We can always get through zext.
4892 if (isa<ZExtInst>(Inst))
4893 return true;
4894
4895 // sext(sext) is ok too.
4896 if (IsSExt && isa<SExtInst>(Inst))
4897 return true;
4898
4899 // We can get through binary operator, if it is legal. In other words, the
4900 // binary operator must have a nuw or nsw flag.
4901 if (const auto *BinOp = dyn_cast<BinaryOperator>(Inst))
4902 if (isa<OverflowingBinaryOperator>(BinOp) &&
4903 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
4904 (IsSExt && BinOp->hasNoSignedWrap())))
4905 return true;
4906
4907 // ext(and(opnd, cst)) --> and(ext(opnd), ext(cst))
4908 if ((Inst->getOpcode() == Instruction::And ||
4909 Inst->getOpcode() == Instruction::Or))
4910 return true;
4911
4912 // ext(xor(opnd, cst)) --> xor(ext(opnd), ext(cst))
4913 if (Inst->getOpcode() == Instruction::Xor) {
4914 // Make sure it is not a NOT.
4915 if (const auto *Cst = dyn_cast<ConstantInt>(Inst->getOperand(1)))
4916 if (!Cst->getValue().isAllOnes())
4917 return true;
4918 }
4919
4920 // zext(shrl(opnd, cst)) --> shrl(zext(opnd), zext(cst))
4921 // It may change a poisoned value into a regular value, like
4922 // zext i32 (shrl i8 %val, 12) --> shrl i32 (zext i8 %val), 12
4923 // poisoned value regular value
4924 // It should be OK since undef covers valid value.
4925 if (Inst->getOpcode() == Instruction::LShr && !IsSExt)
4926 return true;
4927
4928 // and(ext(shl(opnd, cst)), cst) --> and(shl(ext(opnd), ext(cst)), cst)
4929 // It may change a poisoned value into a regular value, like
4930 // zext i32 (shl i8 %val, 12) --> shl i32 (zext i8 %val), 12
4931 // poisoned value regular value
4932 // It should be OK since undef covers valid value.
4933 if (Inst->getOpcode() == Instruction::Shl && Inst->hasOneUse()) {
4934 const auto *ExtInst = cast<const Instruction>(*Inst->user_begin());
4935 if (ExtInst->hasOneUse()) {
4936 const auto *AndInst = dyn_cast<const Instruction>(*ExtInst->user_begin());
4937 if (AndInst && AndInst->getOpcode() == Instruction::And) {
4938 const auto *Cst = dyn_cast<ConstantInt>(AndInst->getOperand(1));
4939 if (Cst &&
4940 Cst->getValue().isIntN(Inst->getType()->getIntegerBitWidth()))
4941 return true;
4942 }
4943 }
4944 }
4945
4946 // Check if we can do the following simplification.
4947 // ext(trunc(opnd)) --> ext(opnd)
4948 if (!isa<TruncInst>(Inst))
4949 return false;
4950
4951 Value *OpndVal = Inst->getOperand(0);
4952 // Check if we can use this operand in the extension.
4953 // If the type is larger than the result type of the extension, we cannot.
4954 if (!OpndVal->getType()->isIntegerTy() ||
4955 OpndVal->getType()->getIntegerBitWidth() >
4956 ConsideredExtType->getIntegerBitWidth())
4957 return false;
4958
4959 // If the operand of the truncate is not an instruction, we will not have
4960 // any information on the dropped bits.
4961 // (Actually we could for constant but it is not worth the extra logic).
4962 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
4963 if (!Opnd)
4964 return false;
4965
4966 // Check if the source of the type is narrow enough.
4967 // I.e., check that trunc just drops extended bits of the same kind of
4968 // the extension.
4969 // #1 get the type of the operand and check the kind of the extended bits.
4970 const Type *OpndType = getOrigType(PromotedInsts, Opnd, IsSExt);
4971 if (OpndType)
4972 ;
4973 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
4974 OpndType = Opnd->getOperand(0)->getType();
4975 else
4976 return false;
4977
4978 // #2 check that the truncate just drops extended bits.
4979 return Inst->getType()->getIntegerBitWidth() >=
4980 OpndType->getIntegerBitWidth();
4981}
4982
4983TypePromotionHelper::Action TypePromotionHelper::getAction(
4984 Instruction *Ext, const SetOfInstrs &InsertedInsts,
4985 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
4986 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
4987 "Unexpected instruction type");
4988 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
4989 Type *ExtTy = Ext->getType();
4990 bool IsSExt = isa<SExtInst>(Ext);
4991 // If the operand of the extension is not an instruction, we cannot
4992 // get through.
4993 // If it, check we can get through.
4994 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
4995 return nullptr;
4996
4997 // Do not promote if the operand has been added by codegenprepare.
4998 // Otherwise, it means we are undoing an optimization that is likely to be
4999 // redone, thus causing potential infinite loop.
5000 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
5001 return nullptr;
5002
5003 // SExt or Trunc instructions.
5004 // Return the related handler.
5005 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
5006 isa<ZExtInst>(ExtOpnd))
5007 return promoteOperandForTruncAndAnyExt;
5008
5009 // Regular instruction.
5010 // Abort early if we will have to insert non-free instructions.
5011 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
5012 return nullptr;
5013 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
5014}
5015
5016Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
5017 Instruction *SExt, TypePromotionTransaction &TPT,
5018 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
5019 SmallVectorImpl<Instruction *> *Exts,
5020 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
5021 // By construction, the operand of SExt is an instruction. Otherwise we cannot
5022 // get through it and this method should not be called.
5023 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
5024 Value *ExtVal = SExt;
5025 bool HasMergedNonFreeExt = false;
5026 if (isa<ZExtInst>(SExtOpnd)) {
5027 // Replace s|zext(zext(opnd))
5028 // => zext(opnd).
5029 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
5030 Value *ZExt =
5031 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
5032 TPT.replaceAllUsesWith(SExt, ZExt);
5033 TPT.eraseInstruction(SExt);
5034 ExtVal = ZExt;
5035 } else {
5036 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
5037 // => z|sext(opnd).
5038 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
5039 }
5040 CreatedInstsCost = 0;
5041
5042 // Remove dead code.
5043 if (SExtOpnd->use_empty())
5044 TPT.eraseInstruction(SExtOpnd);
5045
5046 // Check if the extension is still needed.
5047 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
5048 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
5049 if (ExtInst) {
5050 if (Exts)
5051 Exts->push_back(ExtInst);
5052 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
5053 }
5054 return ExtVal;
5055 }
5056
5057 // At this point we have: ext ty opnd to ty.
5058 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
5059 Value *NextVal = ExtInst->getOperand(0);
5060 TPT.eraseInstruction(ExtInst, NextVal);
5061 return NextVal;
5062}
5063
5064Value *TypePromotionHelper::promoteOperandForOther(
5065 Instruction *Ext, TypePromotionTransaction &TPT,
5066 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
5067 SmallVectorImpl<Instruction *> *Exts,
5068 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
5069 bool IsSExt) {
5070 // By construction, the operand of Ext is an instruction. Otherwise we cannot
5071 // get through it and this method should not be called.
5072 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
5073 CreatedInstsCost = 0;
5074 if (!ExtOpnd->hasOneUse()) {
5075 // ExtOpnd will be promoted.
5076 // All its uses, but Ext, will need to use a truncated value of the
5077 // promoted version.
5078 // Create the truncate now.
5079 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
5080 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
5081 // Insert it just after the definition.
5082 ITrunc->moveAfter(ExtOpnd);
5083 if (Truncs)
5084 Truncs->push_back(ITrunc);
5085 }
5086
5087 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
5088 // Restore the operand of Ext (which has been replaced by the previous call
5089 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
5090 TPT.setOperand(Ext, 0, ExtOpnd);
5091 }
5092
5093 // Get through the Instruction:
5094 // 1. Update its type.
5095 // 2. Replace the uses of Ext by Inst.
5096 // 3. Extend each operand that needs to be extended.
5097
5098 // Remember the original type of the instruction before promotion.
5099 // This is useful to know that the high bits are sign extended bits.
5100 addPromotedInst(PromotedInsts, ExtOpnd, IsSExt);
5101 // Step #1.
5102 TPT.mutateType(ExtOpnd, Ext->getType());
5103 // Step #2.
5104 TPT.replaceAllUsesWith(Ext, ExtOpnd);
5105 // Step #3.
5106 LLVM_DEBUG(dbgs() << "Propagate Ext to operands\n");
5107 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
5108 ++OpIdx) {
5109 LLVM_DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
5110 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
5111 !shouldExtOperand(ExtOpnd, OpIdx)) {
5112 LLVM_DEBUG(dbgs() << "No need to propagate\n");
5113 continue;
5114 }
5115 // Check if we can statically extend the operand.
5116 Value *Opnd = ExtOpnd->getOperand(OpIdx);
5117 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
5118 LLVM_DEBUG(dbgs() << "Statically extend\n");
5119 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
5120 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
5121 : Cst->getValue().zext(BitWidth);
5122 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
5123 continue;
5124 }
5125 // UndefValue are typed, so we have to statically sign extend them.
5126 if (isa<UndefValue>(Opnd)) {
5127 LLVM_DEBUG(dbgs() << "Statically extend\n");
5128 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
5129 continue;
5130 }
5131
5132 // Otherwise we have to explicitly sign extend the operand.
5133 Value *ValForExtOpnd = IsSExt
5134 ? TPT.createSExt(ExtOpnd, Opnd, Ext->getType())
5135 : TPT.createZExt(ExtOpnd, Opnd, Ext->getType());
5136 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
5137 Instruction *InstForExtOpnd = dyn_cast<Instruction>(ValForExtOpnd);
5138 if (!InstForExtOpnd)
5139 continue;
5140
5141 if (Exts)
5142 Exts->push_back(InstForExtOpnd);
5143
5144 CreatedInstsCost += !TLI.isExtFree(InstForExtOpnd);
5145 }
5146 LLVM_DEBUG(dbgs() << "Extension is useless now\n");
5147 TPT.eraseInstruction(Ext);
5148 return ExtOpnd;
5149}
5150
5151/// Check whether or not promoting an instruction to a wider type is profitable.
5152/// \p NewCost gives the cost of extension instructions created by the
5153/// promotion.
5154/// \p OldCost gives the cost of extension instructions before the promotion
5155/// plus the number of instructions that have been
5156/// matched in the addressing mode the promotion.
5157/// \p PromotedOperand is the value that has been promoted.
5158/// \return True if the promotion is profitable, false otherwise.
5159bool AddressingModeMatcher::isPromotionProfitable(
5160 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
5161 LLVM_DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost
5162 << '\n');
5163 // The cost of the new extensions is greater than the cost of the
5164 // old extension plus what we folded.
5165 // This is not profitable.
5166 if (NewCost > OldCost)
5167 return false;
5168 if (NewCost < OldCost)
5169 return true;
5170 // The promotion is neutral but it may help folding the sign extension in
5171 // loads for instance.
5172 // Check that we did not create an illegal instruction.
5173 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
5174}
5175
5176/// Given an instruction or constant expr, see if we can fold the operation
5177/// into the addressing mode. If so, update the addressing mode and return
5178/// true, otherwise return false without modifying AddrMode.
5179/// If \p MovedAway is not NULL, it contains the information of whether or
5180/// not AddrInst has to be folded into the addressing mode on success.
5181/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
5182/// because it has been moved away.
5183/// Thus AddrInst must not be added in the matched instructions.
5184/// This state can happen when AddrInst is a sext, since it may be moved away.
5185/// Therefore, AddrInst may not be valid when MovedAway is true and it must
5186/// not be referenced anymore.
5187bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
5188 unsigned Depth,
5189 bool *MovedAway) {
5190 // Avoid exponential behavior on extremely deep expression trees.
5191 if (Depth >= 5)
5192 return false;
5193
5194 // By default, all matched instructions stay in place.
5195 if (MovedAway)
5196 *MovedAway = false;
5197
5198 switch (Opcode) {
5199 case Instruction::PtrToInt:
5200 // PtrToInt is always a noop, as we know that the int type is pointer sized.
5201 return matchAddr(AddrInst->getOperand(0), Depth);
5202 case Instruction::IntToPtr: {
5203 auto AS = AddrInst->getType()->getPointerAddressSpace();
5204 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
5205 // This inttoptr is a no-op if the integer type is pointer sized.
5206 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
5207 return matchAddr(AddrInst->getOperand(0), Depth);
5208 return false;
5209 }
5210 case Instruction::BitCast:
5211 // BitCast is always a noop, and we can handle it as long as it is
5212 // int->int or pointer->pointer (we don't want int<->fp or something).
5213 if (AddrInst->getOperand(0)->getType()->isIntOrPtrTy() &&
5214 // Don't touch identity bitcasts. These were probably put here by LSR,
5215 // and we don't want to mess around with them. Assume it knows what it
5216 // is doing.
5217 AddrInst->getOperand(0)->getType() != AddrInst->getType())
5218 return matchAddr(AddrInst->getOperand(0), Depth);
5219 return false;
5220 case Instruction::AddrSpaceCast: {
5221 unsigned SrcAS =
5222 AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
5223 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
5224 if (TLI.getTargetMachine().isNoopAddrSpaceCast(DL, SrcAS, DestAS))
5225 return matchAddr(AddrInst->getOperand(0), Depth);
5226 return false;
5227 }
5228 case Instruction::Add: {
5229 // Check to see if we can merge in one operand, then the other. If so, we
5230 // win.
5231 ExtAddrMode BackupAddrMode = AddrMode;
5232 unsigned OldSize = AddrModeInsts.size();
5233 // Start a transaction at this point.
5234 // The LHS may match but not the RHS.
5235 // Therefore, we need a higher level restoration point to undo partially
5236 // matched operation.
5237 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5238 TPT.getRestorationPoint();
5239
5240 // Try to match an integer constant second to increase its chance of ending
5241 // up in `BaseOffs`, resp. decrease its chance of ending up in `BaseReg`.
5242 int First = 0, Second = 1;
5243 if (isa<ConstantInt>(AddrInst->getOperand(First))
5244 && !isa<ConstantInt>(AddrInst->getOperand(Second)))
5245 std::swap(First, Second);
5246 AddrMode.InBounds = false;
5247 if (matchAddr(AddrInst->getOperand(First), Depth + 1) &&
5248 matchAddr(AddrInst->getOperand(Second), Depth + 1))
5249 return true;
5250
5251 // Restore the old addr mode info.
5252 AddrMode = BackupAddrMode;
5253 AddrModeInsts.resize(OldSize);
5254 TPT.rollback(LastKnownGood);
5255
5256 // Otherwise this was over-aggressive. Try merging operands in the opposite
5257 // order.
5258 if (matchAddr(AddrInst->getOperand(Second), Depth + 1) &&
5259 matchAddr(AddrInst->getOperand(First), Depth + 1))
5260 return true;
5261
5262 // Otherwise we definitely can't merge the ADD in.
5263 AddrMode = BackupAddrMode;
5264 AddrModeInsts.resize(OldSize);
5265 TPT.rollback(LastKnownGood);
5266 break;
5267 }
5268 // case Instruction::Or:
5269 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
5270 // break;
5271 case Instruction::Mul:
5272 case Instruction::Shl: {
5273 // Can only handle X*C and X << C.
5274 AddrMode.InBounds = false;
5275 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
5276 if (!RHS || RHS->getBitWidth() > 64)
5277 return false;
5278 int64_t Scale = Opcode == Instruction::Shl
5279 ? 1LL << RHS->getLimitedValue(RHS->getBitWidth() - 1)
5280 : RHS->getSExtValue();
5281
5282 return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
5283 }
5284 case Instruction::GetElementPtr: {
5285 // Scan the GEP. We check it if it contains constant offsets and at most
5286 // one variable offset.
5287 int VariableOperand = -1;
5288 unsigned VariableScale = 0;
5289
5290 int64_t ConstantOffset = 0;
5291 gep_type_iterator GTI = gep_type_begin(AddrInst);
5292 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
5293 if (StructType *STy = GTI.getStructTypeOrNull()) {
5294 const StructLayout *SL = DL.getStructLayout(STy);
5295 unsigned Idx =
5296 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
5297 ConstantOffset += SL->getElementOffset(Idx);
5298 } else {
5299 TypeSize TS = GTI.getSequentialElementStride(DL);
5300 if (TS.isNonZero()) {
5301 // The optimisations below currently only work for fixed offsets.
5302 if (TS.isScalable())
5303 return false;
5304 int64_t TypeSize = TS.getFixedValue();
5305 if (ConstantInt *CI =
5306 dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
5307 const APInt &CVal = CI->getValue();
5308 if (CVal.getSignificantBits() <= 64) {
5309 ConstantOffset += CVal.getSExtValue() * TypeSize;
5310 continue;
5311 }
5312 }
5313 // We only allow one variable index at the moment.
5314 if (VariableOperand != -1)
5315 return false;
5316
5317 // Remember the variable index.
5318 VariableOperand = i;
5319 VariableScale = TypeSize;
5320 }
5321 }
5322 }
5323
5324 // A common case is for the GEP to only do a constant offset. In this case,
5325 // just add it to the disp field and check validity.
5326 if (VariableOperand == -1) {
5327 AddrMode.BaseOffs += ConstantOffset;
5328 if (matchAddr(AddrInst->getOperand(0), Depth + 1)) {
5329 if (!cast<GEPOperator>(AddrInst)->isInBounds())
5330 AddrMode.InBounds = false;
5331 return true;
5332 }
5333 AddrMode.BaseOffs -= ConstantOffset;
5334
5336 TLI.shouldConsiderGEPOffsetSplit() && Depth == 0 &&
5337 ConstantOffset > 0) {
5338 // Record GEPs with non-zero offsets as candidates for splitting in
5339 // the event that the offset cannot fit into the r+i addressing mode.
5340 // Simple and common case that only one GEP is used in calculating the
5341 // address for the memory access.
5342 Value *Base = AddrInst->getOperand(0);
5343 auto *BaseI = dyn_cast<Instruction>(Base);
5344 auto *GEP = cast<GetElementPtrInst>(AddrInst);
5346 (BaseI && !isa<CastInst>(BaseI) &&
5347 !isa<GetElementPtrInst>(BaseI))) {
5348 // Make sure the parent block allows inserting non-PHI instructions
5349 // before the terminator.
5350 BasicBlock *Parent = BaseI ? BaseI->getParent()
5351 : &GEP->getFunction()->getEntryBlock();
5352 if (!Parent->getTerminator()->isEHPad())
5353 LargeOffsetGEP = std::make_pair(GEP, ConstantOffset);
5354 }
5355 }
5356
5357 return false;
5358 }
5359
5360 // Save the valid addressing mode in case we can't match.
5361 ExtAddrMode BackupAddrMode = AddrMode;
5362 unsigned OldSize = AddrModeInsts.size();
5363
5364 // See if the scale and offset amount is valid for this target.
5365 AddrMode.BaseOffs += ConstantOffset;
5366 if (!cast<GEPOperator>(AddrInst)->isInBounds())
5367 AddrMode.InBounds = false;
5368
5369 // Match the base operand of the GEP.
5370 if (!matchAddr(AddrInst->getOperand(0), Depth + 1)) {
5371 // If it couldn't be matched, just stuff the value in a register.
5372 if (AddrMode.HasBaseReg) {
5373 AddrMode = BackupAddrMode;
5374 AddrModeInsts.resize(OldSize);
5375 return false;
5376 }
5377 AddrMode.HasBaseReg = true;
5378 AddrMode.BaseReg = AddrInst->getOperand(0);
5379 }
5380
5381 // Match the remaining variable portion of the GEP.
5382 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
5383 Depth)) {
5384 // If it couldn't be matched, try stuffing the base into a register
5385 // instead of matching it, and retrying the match of the scale.
5386 AddrMode = BackupAddrMode;
5387 AddrModeInsts.resize(OldSize);
5388 if (AddrMode.HasBaseReg)
5389 return false;
5390 AddrMode.HasBaseReg = true;
5391 AddrMode.BaseReg = AddrInst->getOperand(0);
5392 AddrMode.BaseOffs += ConstantOffset;
5393 if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
5394 VariableScale, Depth)) {
5395 // If even that didn't work, bail.
5396 AddrMode = BackupAddrMode;
5397 AddrModeInsts.resize(OldSize);
5398 return false;
5399 }
5400 }
5401
5402 return true;
5403 }
5404 case Instruction::SExt:
5405 case Instruction::ZExt: {
5406 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
5407 if (!Ext)
5408 return false;
5409
5410 // Try to move this ext out of the way of the addressing mode.
5411 // Ask for a method for doing so.
5412 TypePromotionHelper::Action TPH =
5413 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
5414 if (!TPH)
5415 return false;
5416
5417 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5418 TPT.getRestorationPoint();
5419 unsigned CreatedInstsCost = 0;
5420 unsigned ExtCost = !TLI.isExtFree(Ext);
5421 Value *PromotedOperand =
5422 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
5423 // SExt has been moved away.
5424 // Thus either it will be rematched later in the recursive calls or it is
5425 // gone. Anyway, we must not fold it into the addressing mode at this point.
5426 // E.g.,
5427 // op = add opnd, 1
5428 // idx = ext op
5429 // addr = gep base, idx
5430 // is now:
5431 // promotedOpnd = ext opnd <- no match here
5432 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
5433 // addr = gep base, op <- match
5434 if (MovedAway)
5435 *MovedAway = true;
5436
5437 assert(PromotedOperand &&
5438 "TypePromotionHelper should have filtered out those cases");
5439
5440 ExtAddrMode BackupAddrMode = AddrMode;
5441 unsigned OldSize = AddrModeInsts.size();
5442
5443 if (!matchAddr(PromotedOperand, Depth) ||
5444 // The total of the new cost is equal to the cost of the created
5445 // instructions.
5446 // The total of the old cost is equal to the cost of the extension plus
5447 // what we have saved in the addressing mode.
5448 !isPromotionProfitable(CreatedInstsCost,
5449 ExtCost + (AddrModeInsts.size() - OldSize),
5450 PromotedOperand)) {
5451 AddrMode = BackupAddrMode;
5452 AddrModeInsts.resize(OldSize);
5453 LLVM_DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
5454 TPT.rollback(LastKnownGood);
5455 return false;
5456 }
5457
5458 // SExt has been deleted. Make sure it is not referenced by the AddrMode.
5459 AddrMode.replaceWith(Ext, PromotedOperand);
5460 return true;
5461 }
5462 case Instruction::Call:
5463 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(AddrInst)) {
5464 if (II->getIntrinsicID() == Intrinsic::threadlocal_address) {
5465 GlobalValue &GV = cast<GlobalValue>(*II->getArgOperand(0));
5466 if (TLI.addressingModeSupportsTLS(GV))
5467 return matchAddr(AddrInst->getOperand(0), Depth);
5468 }
5469 }
5470 break;
5471 }
5472 return false;
5473}
5474
5475/// If we can, try to add the value of 'Addr' into the current addressing mode.
5476/// If Addr can't be added to AddrMode this returns false and leaves AddrMode
5477/// unmodified. This assumes that Addr is either a pointer type or intptr_t
5478/// for the target.
5479///
5480bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
5481 // Start a transaction at this point that we will rollback if the matching
5482 // fails.
5483 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5484 TPT.getRestorationPoint();
5485 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
5486 if (CI->getValue().isSignedIntN(64)) {
5487 // Check if the addition would result in a signed overflow.
5488 int64_t Result;
5489 bool Overflow =
5490 AddOverflow(AddrMode.BaseOffs, CI->getSExtValue(), Result);
5491 if (!Overflow) {
5492 // Fold in immediates if legal for the target.
5493 AddrMode.BaseOffs = Result;
5494 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
5495 return true;
5496 AddrMode.BaseOffs -= CI->getSExtValue();
5497 }
5498 }
5499 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
5500 // If this is a global variable, try to fold it into the addressing mode.
5501 if (!AddrMode.BaseGV) {
5502 AddrMode.BaseGV = GV;
5503 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
5504 return true;
5505 AddrMode.BaseGV = nullptr;
5506 }
5507 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
5508 ExtAddrMode BackupAddrMode = AddrMode;
5509 unsigned OldSize = AddrModeInsts.size();
5510
5511 // Check to see if it is possible to fold this operation.
5512 bool MovedAway = false;
5513 if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
5514 // This instruction may have been moved away. If so, there is nothing
5515 // to check here.
5516 if (MovedAway)
5517 return true;
5518 // Okay, it's possible to fold this. Check to see if it is actually
5519 // *profitable* to do so. We use a simple cost model to avoid increasing
5520 // register pressure too much.
5521 if (I->hasOneUse() ||
5522 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
5523 AddrModeInsts.push_back(I);
5524 return true;
5525 }
5526
5527 // It isn't profitable to do this, roll back.
5528 AddrMode = BackupAddrMode;
5529 AddrModeInsts.resize(OldSize);
5530 TPT.rollback(LastKnownGood);
5531 }
5532 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
5533 if (matchOperationAddr(CE, CE->getOpcode(), Depth))
5534 return true;
5535 TPT.rollback(LastKnownGood);
5536 } else if (isa<ConstantPointerNull>(Addr)) {
5537 // Null pointer gets folded without affecting the addressing mode.
5538 return true;
5539 }
5540
5541 // Worse case, the target should support [reg] addressing modes. :)
5542 if (!AddrMode.HasBaseReg) {
5543 AddrMode.HasBaseReg = true;
5544 AddrMode.BaseReg = Addr;
5545 // Still check for legality in case the target supports [imm] but not [i+r].
5546 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
5547 return true;
5548 AddrMode.HasBaseReg = false;
5549 AddrMode.BaseReg = nullptr;
5550 }
5551
5552 // If the base register is already taken, see if we can do [r+r].
5553 if (AddrMode.Scale == 0) {
5554 AddrMode.Scale = 1;
5555 AddrMode.ScaledReg = Addr;
5556 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
5557 return true;
5558 AddrMode.Scale = 0;
5559 AddrMode.ScaledReg = nullptr;
5560 }
5561 // Couldn't match.
5562 TPT.rollback(LastKnownGood);
5563 return false;
5564}
5565
5566/// Check to see if all uses of OpVal by the specified inline asm call are due
5567/// to memory operands. If so, return true, otherwise return false.
5569 const TargetLowering &TLI,
5570 const TargetRegisterInfo &TRI) {
5571 const Function *F = CI->getFunction();
5572 TargetLowering::AsmOperandInfoVector TargetConstraints =
5573 TLI.ParseConstraints(F->getDataLayout(), &TRI, *CI);
5574
5575 for (TargetLowering::AsmOperandInfo &OpInfo : TargetConstraints) {
5576 // Compute the constraint code and ConstraintType to use.
5577 TLI.ComputeConstraintToUse(OpInfo, SDValue());
5578
5579 // If this asm operand is our Value*, and if it isn't an indirect memory
5580 // operand, we can't fold it! TODO: Also handle C_Address?
5581 if (OpInfo.CallOperandVal == OpVal &&
5582 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
5583 !OpInfo.isIndirect))
5584 return false;
5585 }
5586
5587 return true;
5588}
5589
5590/// Recursively walk all the uses of I until we find a memory use.
5591/// If we find an obviously non-foldable instruction, return true.
5592/// Add accessed addresses and types to MemoryUses.
5594 Instruction *I, SmallVectorImpl<std::pair<Use *, Type *>> &MemoryUses,
5595 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetLowering &TLI,
5596 const TargetRegisterInfo &TRI, bool OptSize, ProfileSummaryInfo *PSI,
5597 BlockFrequencyInfo *BFI, unsigned &SeenInsts) {
5598 // If we already considered this instruction, we're done.
5599 if (!ConsideredInsts.insert(I).second)
5600 return false;
5601
5602 // If this is an obviously unfoldable instruction, bail out.
5603 if (!MightBeFoldableInst(I))
5604 return true;
5605
5606 // Loop over all the uses, recursively processing them.
5607 for (Use &U : I->uses()) {
5608 // Conservatively return true if we're seeing a large number or a deep chain
5609 // of users. This avoids excessive compilation times in pathological cases.
5610 if (SeenInsts++ >= MaxAddressUsersToScan)
5611 return true;
5612
5613 Instruction *UserI = cast<Instruction>(U.getUser());
5614 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
5615 MemoryUses.push_back({&U, LI->getType()});
5616 continue;
5617 }
5618
5619 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
5620 if (U.getOperandNo() != StoreInst::getPointerOperandIndex())
5621 return true; // Storing addr, not into addr.
5622 MemoryUses.push_back({&U, SI->getValueOperand()->getType()});
5623 continue;
5624 }
5625
5626 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UserI)) {
5627 if (U.getOperandNo() != AtomicRMWInst::getPointerOperandIndex())
5628 return true; // Storing addr, not into addr.
5629 MemoryUses.push_back({&U, RMW->getValOperand()->getType()});
5630 continue;
5631 }
5632
5634 if (U.getOperandNo() != AtomicCmpXchgInst::getPointerOperandIndex())
5635 return true; // Storing addr, not into addr.
5636 MemoryUses.push_back({&U, CmpX->getCompareOperand()->getType()});
5637 continue;
5638 }
5639
5642 Type *AccessTy;
5643 if (!TLI.getAddrModeArguments(II, PtrOps, AccessTy))
5644 return true;
5645
5646 if (!find(PtrOps, U.get()))
5647 return true;
5648
5649 MemoryUses.push_back({&U, AccessTy});
5650 continue;
5651 }
5652
5653 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
5654 if (CI->hasFnAttr(Attribute::Cold)) {
5655 // If this is a cold call, we can sink the addressing calculation into
5656 // the cold path. See optimizeCallInst
5657 if (!llvm::shouldOptimizeForSize(CI->getParent(), PSI, BFI))
5658 continue;
5659 }
5660
5661 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledOperand());
5662 if (!IA)
5663 return true;
5664
5665 // If this is a memory operand, we're cool, otherwise bail out.
5666 if (!IsOperandAMemoryOperand(CI, IA, I, TLI, TRI))
5667 return true;
5668 continue;
5669 }
5670
5671 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI, TRI, OptSize,
5672 PSI, BFI, SeenInsts))
5673 return true;
5674 }
5675
5676 return false;
5677}
5678
5680 Instruction *I, SmallVectorImpl<std::pair<Use *, Type *>> &MemoryUses,
5681 const TargetLowering &TLI, const TargetRegisterInfo &TRI, bool OptSize,
5683 unsigned SeenInsts = 0;
5684 SmallPtrSet<Instruction *, 16> ConsideredInsts;
5685 return FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI, TRI, OptSize,
5686 PSI, BFI, SeenInsts);
5687}
5688
5689
5690/// Return true if Val is already known to be live at the use site that we're
5691/// folding it into. If so, there is no cost to include it in the addressing
5692/// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
5693/// instruction already.
5694bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,
5695 Value *KnownLive1,
5696 Value *KnownLive2) {
5697 // If Val is either of the known-live values, we know it is live!
5698 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
5699 return true;
5700
5701 // All values other than instructions and arguments (e.g. constants) are live.
5702 if (!isa<Instruction>(Val) && !isa<Argument>(Val))
5703 return true;
5704
5705 // If Val is a constant sized alloca in the entry block, it is live, this is
5706 // true because it is just a reference to the stack/frame pointer, which is
5707 // live for the whole function.
5708 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
5709 if (AI->isStaticAlloca())
5710 return true;
5711
5712 // Check to see if this value is already used in the memory instruction's
5713 // block. If so, it's already live into the block at the very least, so we
5714 // can reasonably fold it.
5715 return Val->isUsedInBasicBlock(MemoryInst->getParent());
5716}
5717
5718/// It is possible for the addressing mode of the machine to fold the specified
5719/// instruction into a load or store that ultimately uses it.
5720/// However, the specified instruction has multiple uses.
5721/// Given this, it may actually increase register pressure to fold it
5722/// into the load. For example, consider this code:
5723///
5724/// X = ...
5725/// Y = X+1
5726/// use(Y) -> nonload/store
5727/// Z = Y+1
5728/// load Z
5729///
5730/// In this case, Y has multiple uses, and can be folded into the load of Z
5731/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
5732/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
5733/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
5734/// number of computations either.
5735///
5736/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
5737/// X was live across 'load Z' for other reasons, we actually *would* want to
5738/// fold the addressing mode in the Z case. This would make Y die earlier.
5739bool AddressingModeMatcher::isProfitableToFoldIntoAddressingMode(
5740 Instruction *I, ExtAddrMode &AMBefore, ExtAddrMode &AMAfter) {
5741 if (IgnoreProfitability)
5742 return true;
5743
5744 // AMBefore is the addressing mode before this instruction was folded into it,
5745 // and AMAfter is the addressing mode after the instruction was folded. Get
5746 // the set of registers referenced by AMAfter and subtract out those
5747 // referenced by AMBefore: this is the set of values which folding in this
5748 // address extends the lifetime of.
5749 //
5750 // Note that there are only two potential values being referenced here,
5751 // BaseReg and ScaleReg (global addresses are always available, as are any
5752 // folded immediates).
5753 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
5754
5755 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
5756 // lifetime wasn't extended by adding this instruction.
5757 if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
5758 BaseReg = nullptr;
5759 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
5760 ScaledReg = nullptr;
5761
5762 // If folding this instruction (and it's subexprs) didn't extend any live
5763 // ranges, we're ok with it.
5764 if (!BaseReg && !ScaledReg)
5765 return true;
5766
5767 // If all uses of this instruction can have the address mode sunk into them,
5768 // we can remove the addressing mode and effectively trade one live register
5769 // for another (at worst.) In this context, folding an addressing mode into
5770 // the use is just a particularly nice way of sinking it.
5772 if (FindAllMemoryUses(I, MemoryUses, TLI, TRI, OptSize, PSI, BFI))
5773 return false; // Has a non-memory, non-foldable use!
5774
5775 // Now that we know that all uses of this instruction are part of a chain of
5776 // computation involving only operations that could theoretically be folded
5777 // into a memory use, loop over each of these memory operation uses and see
5778 // if they could *actually* fold the instruction. The assumption is that
5779 // addressing modes are cheap and that duplicating the computation involved
5780 // many times is worthwhile, even on a fastpath. For sinking candidates
5781 // (i.e. cold call sites), this serves as a way to prevent excessive code
5782 // growth since most architectures have some reasonable small and fast way to
5783 // compute an effective address. (i.e LEA on x86)
5784 SmallVector<Instruction *, 32> MatchedAddrModeInsts;
5785 for (const std::pair<Use *, Type *> &Pair : MemoryUses) {
5786 Value *Address = Pair.first->get();
5787 Instruction *UserI = cast<Instruction>(Pair.first->getUser());
5788 Type *AddressAccessTy = Pair.second;
5789 unsigned AS = Address->getType()->getPointerAddressSpace();
5790
5791 // Do a match against the root of this address, ignoring profitability. This
5792 // will tell us if the addressing mode for the memory operation will
5793 // *actually* cover the shared instruction.
5794 ExtAddrMode Result;
5795 std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr,
5796 0);
5797 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5798 TPT.getRestorationPoint();
5799 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, TRI, LI, getDTFn,
5800 AddressAccessTy, AS, UserI, Result,
5801 InsertedInsts, PromotedInsts, TPT,
5802 LargeOffsetGEP, OptSize, PSI, BFI);
5803 Matcher.IgnoreProfitability = true;
5804 bool Success = Matcher.matchAddr(Address, 0);
5805 (void)Success;
5806 assert(Success && "Couldn't select *anything*?");
5807
5808 // The match was to check the profitability, the changes made are not
5809 // part of the original matcher. Therefore, they should be dropped
5810 // otherwise the original matcher will not present the right state.
5811 TPT.rollback(LastKnownGood);
5812
5813 // If the match didn't cover I, then it won't be shared by it.
5814 if (!is_contained(MatchedAddrModeInsts, I))
5815 return false;
5816
5817 MatchedAddrModeInsts.clear();
5818 }
5819
5820 return true;
5821}
5822
5823/// Return true if the specified values are defined in a
5824/// different basic block than BB.
5825static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
5827 return I->getParent() != BB;
5828 return false;
5829}
5830
5831// Find an insert position of Addr for MemoryInst. We can't guarantee MemoryInst
5832// is the first instruction that will use Addr. So we need to find the first
5833// user of Addr in current BB.
5835 Value *SunkAddr) {
5836 if (Addr->hasOneUse())
5837 return MemoryInst->getIterator();
5838
5839 // We already have a SunkAddr in current BB, but we may need to insert cast
5840 // instruction after it.
5841 if (SunkAddr) {
5842 if (Instruction *AddrInst = dyn_cast<Instruction>(SunkAddr))
5843 return std::next(AddrInst->getIterator());
5844 }
5845
5846 // Find the first user of Addr in current BB.
5847 Instruction *Earliest = MemoryInst;
5848 for (User *U : Addr->users()) {
5849 Instruction *UserInst = dyn_cast<Instruction>(U);
5850 if (UserInst && UserInst->getParent() == MemoryInst->getParent()) {
5851 if (isa<PHINode>(UserInst) || UserInst->isDebugOrPseudoInst())
5852 continue;
5853 if (UserInst->comesBefore(Earliest))
5854 Earliest = UserInst;
5855 }
5856 }
5857 return Earliest->getIterator();
5858}
5859
5860/// Sink addressing mode computation immediate before MemoryInst if doing so
5861/// can be done without increasing register pressure. The need for the
5862/// register pressure constraint means this can end up being an all or nothing
5863/// decision for all uses of the same addressing computation.
5864///
5865/// Load and Store Instructions often have addressing modes that can do
5866/// significant amounts of computation. As such, instruction selection will try
5867/// to get the load or store to do as much computation as possible for the
5868/// program. The problem is that isel can only see within a single block. As
5869/// such, we sink as much legal addressing mode work into the block as possible.
5870///
5871/// This method is used to optimize both load/store and inline asms with memory
5872/// operands. It's also used to sink addressing computations feeding into cold
5873/// call sites into their (cold) basic block.
5874///
5875/// The motivation for handling sinking into cold blocks is that doing so can
5876/// both enable other address mode sinking (by satisfying the register pressure
5877/// constraint above), and reduce register pressure globally (by removing the
5878/// addressing mode computation from the fast path entirely.).
5879bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
5880 Type *AccessTy, unsigned AddrSpace) {
5881 Value *Repl = Addr;
5882
5883 // Try to collapse single-value PHI nodes. This is necessary to undo
5884 // unprofitable PRE transformations.
5885 SmallVector<Value *, 8> worklist;
5886 SmallPtrSet<Value *, 16> Visited;
5887 worklist.push_back(Addr);
5888
5889 // Use a worklist to iteratively look through PHI and select nodes, and
5890 // ensure that the addressing mode obtained from the non-PHI/select roots of
5891 // the graph are compatible.
5892 bool PhiOrSelectSeen = false;
5893 SmallVector<Instruction *, 16> AddrModeInsts;
5894 AddressingModeCombiner AddrModes(*DL, Addr);
5895 TypePromotionTransaction TPT(RemovedInsts);
5896 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5897 TPT.getRestorationPoint();
5898 while (!worklist.empty()) {
5899 Value *V = worklist.pop_back_val();
5900
5901 // We allow traversing cyclic Phi nodes.
5902 // In case of success after this loop we ensure that traversing through
5903 // Phi nodes ends up with all cases to compute address of the form
5904 // BaseGV + Base + Scale * Index + Offset
5905 // where Scale and Offset are constans and BaseGV, Base and Index
5906 // are exactly the same Values in all cases.
5907 // It means that BaseGV, Scale and Offset dominate our memory instruction
5908 // and have the same value as they had in address computation represented
5909 // as Phi. So we can safely sink address computation to memory instruction.
5910 if (!Visited.insert(V).second)
5911 continue;
5912
5913 // For a PHI node, push all of its incoming values.
5914 if (PHINode *P = dyn_cast<PHINode>(V)) {
5915 append_range(worklist, P->incoming_values());
5916 PhiOrSelectSeen = true;
5917 continue;
5918 }
5919 // Similar for select.
5920 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
5921 worklist.push_back(SI->getFalseValue());
5922 worklist.push_back(SI->getTrueValue());
5923 PhiOrSelectSeen = true;
5924 continue;
5925 }
5926
5927 // For non-PHIs, determine the addressing mode being computed. Note that
5928 // the result may differ depending on what other uses our candidate
5929 // addressing instructions might have.
5930 AddrModeInsts.clear();
5931 std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr,
5932 0);
5933 // Defer the query (and possible computation of) the dom tree to point of
5934 // actual use. It's expected that most address matches don't actually need
5935 // the domtree.
5936 auto getDTFn = [this]() -> const DominatorTree & { return getDT(); };
5937 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
5938 V, AccessTy, AddrSpace, MemoryInst, AddrModeInsts, *TLI, *LI, getDTFn,
5939 *TRI, InsertedInsts, PromotedInsts, TPT, LargeOffsetGEP, OptSize, PSI,
5940 BFI);
5941
5942 GetElementPtrInst *GEP = LargeOffsetGEP.first;
5943 if (GEP && !NewGEPBases.count(GEP)) {
5944 // If splitting the underlying data structure can reduce the offset of a
5945 // GEP, collect the GEP. Skip the GEPs that are the new bases of
5946 // previously split data structures.
5947 LargeOffsetGEPMap[GEP->getPointerOperand()].push_back(LargeOffsetGEP);
5948 LargeOffsetGEPID.insert(std::make_pair(GEP, LargeOffsetGEPID.size()));
5949 }
5950
5951 NewAddrMode.OriginalValue = V;
5952 if (!AddrModes.addNewAddrMode(NewAddrMode))
5953 break;
5954 }
5955
5956 // Try to combine the AddrModes we've collected. If we couldn't collect any,
5957 // or we have multiple but either couldn't combine them or combining them
5958 // wouldn't do anything useful, bail out now.
5959 if (!AddrModes.combineAddrModes()) {
5960 TPT.rollback(LastKnownGood);
5961 return false;
5962 }
5963 bool Modified = TPT.commit();
5964
5965 // Get the combined AddrMode (or the only AddrMode, if we only had one).
5966 ExtAddrMode AddrMode = AddrModes.getAddrMode();
5967
5968 // If all the instructions matched are already in this BB, don't do anything.
5969 // If we saw a Phi node then it is not local definitely, and if we saw a
5970 // select then we want to push the address calculation past it even if it's
5971 // already in this BB.
5972 if (!PhiOrSelectSeen && none_of(AddrModeInsts, [&](Value *V) {
5973 return IsNonLocalValue(V, MemoryInst->getParent());
5974 })) {
5975 LLVM_DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode
5976 << "\n");
5977 return Modified;
5978 }
5979
5980 // Now that we determined the addressing expression we want to use and know
5981 // that we have to sink it into this block. Check to see if we have already
5982 // done this for some other load/store instr in this block. If so, reuse
5983 // the computation. Before attempting reuse, check if the address is valid
5984 // as it may have been erased.
5985
5986 WeakTrackingVH SunkAddrVH = SunkAddrs[Addr];
5987
5988 Value *SunkAddr = SunkAddrVH.pointsToAliveValue() ? SunkAddrVH : nullptr;
5989 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
5990
5991 // The current BB may be optimized multiple times, we can't guarantee the
5992 // reuse of Addr happens later, call findInsertPos to find an appropriate
5993 // insert position.
5994 auto InsertPos = findInsertPos(Addr, MemoryInst, SunkAddr);
5995
5996 // TODO: Adjust insert point considering (Base|Scaled)Reg if possible.
5997 if (!SunkAddr) {
5998 auto &DT = getDT();
5999 if ((AddrMode.BaseReg && !DT.dominates(AddrMode.BaseReg, &*InsertPos)) ||
6000 (AddrMode.ScaledReg && !DT.dominates(AddrMode.ScaledReg, &*InsertPos)))
6001 return Modified;
6002 }
6003
6004 IRBuilder<> Builder(MemoryInst->getParent(), InsertPos);
6005
6006 if (SunkAddr) {
6007 LLVM_DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode
6008 << " for " << *MemoryInst << "\n");
6009 if (SunkAddr->getType() != Addr->getType()) {
6010 if (SunkAddr->getType()->getPointerAddressSpace() !=
6011 Addr->getType()->getPointerAddressSpace() &&
6012 !DL->isNonIntegralPointerType(Addr->getType())) {
6013 // There are two reasons the address spaces might not match: a no-op
6014 // addrspacecast, or a ptrtoint/inttoptr pair. Either way, we emit a
6015 // ptrtoint/inttoptr pair to ensure we match the original semantics.
6016 // TODO: allow bitcast between different address space pointers with the
6017 // same size.
6018 SunkAddr = Builder.CreatePtrToInt(SunkAddr, IntPtrTy, "sunkaddr");
6019 SunkAddr =
6020 Builder.CreateIntToPtr(SunkAddr, Addr->getType(), "sunkaddr");
6021 } else
6022 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
6023 }
6025 SubtargetInfo->addrSinkUsingGEPs())) {
6026 // By default, we use the GEP-based method when AA is used later. This
6027 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
6028 LLVM_DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode
6029 << " for " << *MemoryInst << "\n");
6030 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
6031
6032 // First, find the pointer.
6033 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
6034 ResultPtr = AddrMode.BaseReg;
6035 AddrMode.BaseReg = nullptr;
6036 }
6037
6038 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
6039 // We can't add more than one pointer together, nor can we scale a
6040 // pointer (both of which seem meaningless).
6041 if (ResultPtr || AddrMode.Scale != 1)
6042 return Modified;
6043
6044 ResultPtr = AddrMode.ScaledReg;
6045 AddrMode.Scale = 0;
6046 }
6047
6048 // It is only safe to sign extend the BaseReg if we know that the math
6049 // required to create it did not overflow before we extend it. Since
6050 // the original IR value was tossed in favor of a constant back when
6051 // the AddrMode was created we need to bail out gracefully if widths
6052 // do not match instead of extending it.
6053 //
6054 // (See below for code to add the scale.)
6055 if (AddrMode.Scale) {
6056 Type *ScaledRegTy = AddrMode.ScaledReg->getType();
6058 cast<IntegerType>(ScaledRegTy)->getBitWidth())
6059 return Modified;
6060 }
6061
6062 GlobalValue *BaseGV = AddrMode.BaseGV;
6063 if (BaseGV != nullptr) {
6064 if (ResultPtr)
6065 return Modified;
6066
6067 if (BaseGV->isThreadLocal()) {
6068 ResultPtr = Builder.CreateThreadLocalAddress(BaseGV);
6069 } else {
6070 ResultPtr = BaseGV;
6071 }
6072 }
6073
6074 // If the real base value actually came from an inttoptr, then the matcher
6075 // will look through it and provide only the integer value. In that case,
6076 // use it here.
6077 if (!DL->isNonIntegralPointerType(Addr->getType())) {
6078 if (!ResultPtr && AddrMode.BaseReg) {
6079 ResultPtr = Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(),
6080 "sunkaddr");
6081 AddrMode.BaseReg = nullptr;
6082 } else if (!ResultPtr && AddrMode.Scale == 1) {
6083 ResultPtr = Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(),
6084 "sunkaddr");
6085 AddrMode.Scale = 0;
6086 }
6087 }
6088
6089 if (!ResultPtr && !AddrMode.BaseReg && !AddrMode.Scale &&
6090 !AddrMode.BaseOffs) {
6091 SunkAddr = Constant::getNullValue(Addr->getType());
6092 } else if (!ResultPtr) {
6093 return Modified;
6094 } else {
6095 Type *I8PtrTy =
6096 Builder.getPtrTy(Addr->getType()->getPointerAddressSpace());
6097
6098 // Start with the base register. Do this first so that subsequent address
6099 // matching finds it last, which will prevent it from trying to match it
6100 // as the scaled value in case it happens to be a mul. That would be
6101 // problematic if we've sunk a different mul for the scale, because then
6102 // we'd end up sinking both muls.
6103 if (AddrMode.BaseReg) {
6104 Value *V = AddrMode.BaseReg;
6105 if (V->getType() != IntPtrTy)
6106 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
6107
6108 ResultIndex = V;
6109 }
6110
6111 // Add the scale value.
6112 if (AddrMode.Scale) {
6113 Value *V = AddrMode.ScaledReg;
6114 if (V->getType() == IntPtrTy) {
6115 // done.
6116 } else {
6118 cast<IntegerType>(V->getType())->getBitWidth() &&
6119 "We can't transform if ScaledReg is too narrow");
6120 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
6121 }
6122
6123 if (AddrMode.Scale != 1)
6124 V = Builder.CreateMul(
6125 V, ConstantInt::getSigned(IntPtrTy, AddrMode.Scale), "sunkaddr");
6126 if (ResultIndex)
6127 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
6128 else
6129 ResultIndex = V;
6130 }
6131
6132 // Add in the Base Offset if present.
6133 if (AddrMode.BaseOffs) {
6135 if (ResultIndex) {
6136 // We need to add this separately from the scale above to help with
6137 // SDAG consecutive load/store merging.
6138 if (ResultPtr->getType() != I8PtrTy)
6139 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
6140 ResultPtr = Builder.CreatePtrAdd(ResultPtr, ResultIndex, "sunkaddr",
6141 AddrMode.InBounds);
6142 }
6143
6144 ResultIndex = V;
6145 }
6146
6147 if (!ResultIndex) {
6148 auto PtrInst = dyn_cast<Instruction>(ResultPtr);
6149 // We know that we have a pointer without any offsets. If this pointer
6150 // originates from a different basic block than the current one, we
6151 // must be able to recreate it in the current basic block.
6152 // We do not support the recreation of any instructions yet.
6153 if (PtrInst && PtrInst->getParent() != MemoryInst->getParent())
6154 return Modified;
6155 SunkAddr = ResultPtr;
6156 } else {
6157 if (ResultPtr->getType() != I8PtrTy)
6158 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
6159 SunkAddr = Builder.CreatePtrAdd(ResultPtr, ResultIndex, "sunkaddr",
6160 AddrMode.InBounds);
6161 }
6162
6163 if (SunkAddr->getType() != Addr->getType()) {
6164 if (SunkAddr->getType()->getPointerAddressSpace() !=
6165 Addr->getType()->getPointerAddressSpace() &&
6166 !DL->isNonIntegralPointerType(Addr->getType())) {
6167 // There are two reasons the address spaces might not match: a no-op
6168 // addrspacecast, or a ptrtoint/inttoptr pair. Either way, we emit a
6169 // ptrtoint/inttoptr pair to ensure we match the original semantics.
6170 // TODO: allow bitcast between different address space pointers with
6171 // the same size.
6172 SunkAddr = Builder.CreatePtrToInt(SunkAddr, IntPtrTy, "sunkaddr");
6173 SunkAddr =
6174 Builder.CreateIntToPtr(SunkAddr, Addr->getType(), "sunkaddr");
6175 } else
6176 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
6177 }
6178 }
6179 } else {
6180 // We'd require a ptrtoint/inttoptr down the line, which we can't do for
6181 // non-integral pointers, so in that case bail out now.
6182 Type *BaseTy = AddrMode.BaseReg ? AddrMode.BaseReg->getType() : nullptr;
6183 Type *ScaleTy = AddrMode.Scale ? AddrMode.ScaledReg->getType() : nullptr;
6184 PointerType *BasePtrTy = dyn_cast_or_null<PointerType>(BaseTy);
6185 PointerType *ScalePtrTy = dyn_cast_or_null<PointerType>(ScaleTy);
6186 if (DL->isNonIntegralPointerType(Addr->getType()) ||
6187 (BasePtrTy && DL->isNonIntegralPointerType(BasePtrTy)) ||
6188 (ScalePtrTy && DL->isNonIntegralPointerType(ScalePtrTy)) ||
6189 (AddrMode.BaseGV &&
6190 DL->isNonIntegralPointerType(AddrMode.BaseGV->getType())))
6191 return Modified;
6192
6193 LLVM_DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode
6194 << " for " << *MemoryInst << "\n");
6195 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
6196 Value *Result = nullptr;
6197
6198 // Start with the base register. Do this first so that subsequent address
6199 // matching finds it last, which will prevent it from trying to match it
6200 // as the scaled value in case it happens to be a mul. That would be
6201 // problematic if we've sunk a different mul for the scale, because then
6202 // we'd end up sinking both muls.
6203 if (AddrMode.BaseReg) {
6204 Value *V = AddrMode.BaseReg;
6205 if (V->getType()->isPointerTy())
6206 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
6207 if (V->getType() != IntPtrTy)
6208 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
6209 Result = V;
6210 }
6211
6212 // Add the scale value.
6213 if (AddrMode.Scale) {
6214 Value *V = AddrMode.ScaledReg;
6215 if (V->getType() == IntPtrTy) {
6216 // done.
6217 } else if (V->getType()->isPointerTy()) {
6218 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
6219 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
6220 cast<IntegerType>(V->getType())->getBitWidth()) {
6221 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
6222 } else {
6223 // It is only safe to sign extend the BaseReg if we know that the math
6224 // required to create it did not overflow before we extend it. Since
6225 // the original IR value was tossed in favor of a constant back when
6226 // the AddrMode was created we need to bail out gracefully if widths
6227 // do not match instead of extending it.
6229 if (I && (Result != AddrMode.BaseReg))
6230 I->eraseFromParent();
6231 return Modified;
6232 }
6233 if (AddrMode.Scale != 1)
6234 V = Builder.CreateMul(
6235 V, ConstantInt::getSigned(IntPtrTy, AddrMode.Scale), "sunkaddr");
6236 if (Result)
6237 Result = Builder.CreateAdd(Result, V, "sunkaddr");
6238 else
6239 Result = V;
6240 }
6241
6242 // Add in the BaseGV if present.
6243 GlobalValue *BaseGV = AddrMode.BaseGV;
6244 if (BaseGV != nullptr) {
6245 Value *BaseGVPtr;
6246 if (BaseGV->isThreadLocal()) {
6247 BaseGVPtr = Builder.CreateThreadLocalAddress(BaseGV);
6248 } else {
6249 BaseGVPtr = BaseGV;
6250 }
6251 Value *V = Builder.CreatePtrToInt(BaseGVPtr, IntPtrTy, "sunkaddr");
6252 if (Result)
6253 Result = Builder.CreateAdd(Result, V, "sunkaddr");
6254 else
6255 Result = V;
6256 }
6257
6258 // Add in the Base Offset if present.
6259 if (AddrMode.BaseOffs) {
6261 if (Result)
6262 Result = Builder.CreateAdd(Result, V, "sunkaddr");
6263 else
6264 Result = V;
6265 }
6266
6267 if (!Result)
6268 SunkAddr = Constant::getNullValue(Addr->getType());
6269 else
6270 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
6271 }
6272
6273 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
6274 // Store the newly computed address into the cache. In the case we reused a
6275 // value, this should be idempotent.
6276 SunkAddrs[Addr] = WeakTrackingVH(SunkAddr);
6277
6278 // If we have no uses, recursively delete the value and all dead instructions
6279 // using it.
6280 if (Repl->use_empty()) {
6281 resetIteratorIfInvalidatedWhileCalling(CurInstIterator->getParent(), [&]() {
6282 RecursivelyDeleteTriviallyDeadInstructions(
6283 Repl, TLInfo, nullptr,
6284 [&](Value *V) { removeAllAssertingVHReferences(V); });
6285 });
6286 }
6287 ++NumMemoryInsts;
6288 return true;
6289}
6290
6291/// Rewrite GEP input to gather/scatter to enable SelectionDAGBuilder to find
6292/// a uniform base to use for ISD::MGATHER/MSCATTER. SelectionDAGBuilder can
6293/// only handle a 2 operand GEP in the same basic block or a splat constant
6294/// vector. The 2 operands to the GEP must have a scalar pointer and a vector
6295/// index.
6296///
6297/// If the existing GEP has a vector base pointer that is splat, we can look
6298/// through the splat to find the scalar pointer. If we can't find a scalar
6299/// pointer there's nothing we can do.
6300///
6301/// If we have a GEP with more than 2 indices where the middle indices are all
6302/// zeroes, we can replace it with 2 GEPs where the second has 2 operands.
6303///
6304/// If the final index isn't a vector or is a splat, we can emit a scalar GEP
6305/// followed by a GEP with an all zeroes vector index. This will enable
6306/// SelectionDAGBuilder to use the scalar GEP as the uniform base and have a
6307/// zero index.
6308bool CodeGenPrepare::optimizeGatherScatterInst(Instruction *MemoryInst,
6309 Value *Ptr) {
6310 Value *NewAddr;
6311
6312 if (const auto *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
6313 // Don't optimize GEPs that don't have indices.
6314 if (!GEP->hasIndices())
6315 return false;
6316
6317 // If the GEP and the gather/scatter aren't in the same BB, don't optimize.
6318 // FIXME: We should support this by sinking the GEP.
6319 if (MemoryInst->getParent() != GEP->getParent())
6320 return false;
6321
6322 SmallVector<Value *, 2> Ops(GEP->operands());
6323
6324 bool RewriteGEP = false;
6325
6326 if (Ops[0]->getType()->isVectorTy()) {
6327 Ops[0] = getSplatValue(Ops[0]);
6328 if (!Ops[0])
6329 return false;
6330 RewriteGEP = true;
6331 }
6332
6333 unsigned FinalIndex = Ops.size() - 1;
6334
6335 // Ensure all but the last index is 0.
6336 // FIXME: This isn't strictly required. All that's required is that they are
6337 // all scalars or splats.
6338 for (unsigned i = 1; i < FinalIndex; ++i) {
6339 auto *C = dyn_cast<Constant>(Ops[i]);
6340 if (!C)
6341 return false;
6342 if (isa<VectorType>(C->getType()))
6343 C = C->getSplatValue();
6344 auto *CI = dyn_cast_or_null<ConstantInt>(C);
6345 if (!CI || !CI->isZero())
6346 return false;
6347 // Scalarize the index if needed.
6348 Ops[i] = CI;
6349 }
6350
6351 // Try to scalarize the final index.
6352 if (Ops[FinalIndex]->getType()->isVectorTy()) {
6353 if (Value *V = getSplatValue(Ops[FinalIndex])) {
6354 auto *C = dyn_cast<ConstantInt>(V);
6355 // Don't scalarize all zeros vector.
6356 if (!C || !C->isZero()) {
6357 Ops[FinalIndex] = V;
6358 RewriteGEP = true;
6359 }
6360 }
6361 }
6362
6363 // If we made any changes or the we have extra operands, we need to generate
6364 // new instructions.
6365 if (!RewriteGEP && Ops.size() == 2)
6366 return false;
6367
6368 auto NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
6369
6370 IRBuilder<> Builder(MemoryInst);
6371
6372 Type *SourceTy = GEP->getSourceElementType();
6373 Type *ScalarIndexTy = DL->getIndexType(Ops[0]->getType()->getScalarType());
6374
6375 // If the final index isn't a vector, emit a scalar GEP containing all ops
6376 // and a vector GEP with all zeroes final index.
6377 if (!Ops[FinalIndex]->getType()->isVectorTy()) {
6378 NewAddr = Builder.CreateGEP(SourceTy, Ops[0], ArrayRef(Ops).drop_front());
6379 auto *IndexTy = VectorType::get(ScalarIndexTy, NumElts);
6380 auto *SecondTy = GetElementPtrInst::getIndexedType(
6381 SourceTy, ArrayRef(Ops).drop_front());
6382 NewAddr =
6383 Builder.CreateGEP(SecondTy, NewAddr, Constant::getNullValue(IndexTy));
6384 } else {
6385 Value *Base = Ops[0];
6386 Value *Index = Ops[FinalIndex];
6387
6388 // Create a scalar GEP if there are more than 2 operands.
6389 if (Ops.size() != 2) {
6390 // Replace the last index with 0.
6391 Ops[FinalIndex] =
6392 Constant::getNullValue(Ops[FinalIndex]->getType()->getScalarType());
6393 Base = Builder.CreateGEP(SourceTy, Base, ArrayRef(Ops).drop_front());
6395 SourceTy, ArrayRef(Ops).drop_front());
6396 }
6397
6398 // Now create the GEP with scalar pointer and vector index.
6399 NewAddr = Builder.CreateGEP(SourceTy, Base, Index);
6400 }
6401 } else if (!isa<Constant>(Ptr)) {
6402 // Not a GEP, maybe its a splat and we can create a GEP to enable
6403 // SelectionDAGBuilder to use it as a uniform base.
6404 Value *V = getSplatValue(Ptr);
6405 if (!V)
6406 return false;
6407
6408 auto NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
6409
6410 IRBuilder<> Builder(MemoryInst);
6411
6412 // Emit a vector GEP with a scalar pointer and all 0s vector index.
6413 Type *ScalarIndexTy = DL->getIndexType(V->getType()->getScalarType());
6414 auto *IndexTy = VectorType::get(ScalarIndexTy, NumElts);
6415 Type *ScalarTy;
6416 if (cast<IntrinsicInst>(MemoryInst)->getIntrinsicID() ==
6417 Intrinsic::masked_gather) {
6418 ScalarTy = MemoryInst->getType()->getScalarType();
6419 } else {
6420 assert(cast<IntrinsicInst>(MemoryInst)->getIntrinsicID() ==
6421 Intrinsic::masked_scatter);
6422 ScalarTy = MemoryInst->getOperand(0)->getType()->getScalarType();
6423 }
6424 NewAddr = Builder.CreateGEP(ScalarTy, V, Constant::getNullValue(IndexTy));
6425 } else {
6426 // Constant, SelectionDAGBuilder knows to check if its a splat.
6427 return false;
6428 }
6429
6430 MemoryInst->replaceUsesOfWith(Ptr, NewAddr);
6431
6432 // If we have no uses, recursively delete the value and all dead instructions
6433 // using it.
6434 if (Ptr->use_empty())
6436 Ptr, TLInfo, nullptr,
6437 [&](Value *V) { removeAllAssertingVHReferences(V); });
6438
6439 return true;
6440}
6441
6442// This is a helper for CodeGenPrepare::optimizeMulWithOverflow.
6443// Check the pattern we are interested in where there are maximum 2 uses
6444// of the intrinsic which are the extract instructions.
6446 ExtractValueInst *&OverflowExtract) {
6447 // Bail out if it's more than 2 users:
6448 if (I->hasNUsesOrMore(3))
6449 return false;
6450
6451 for (User *U : I->users()) {
6452 auto *Extract = dyn_cast<ExtractValueInst>(U);
6453 if (!Extract || Extract->getNumIndices() != 1)
6454 return false;
6455
6456 unsigned Index = Extract->getIndices()[0];
6457 if (Index == 0)
6458 MulExtract = Extract;
6459 else if (Index == 1)
6460 OverflowExtract = Extract;
6461 else
6462 return false;
6463 }
6464 return true;
6465}
6466
6467// Rewrite the mul_with_overflow intrinsic by checking if both of the
6468// operands' value ranges are within the legal type. If so, we can optimize the
6469// multiplication algorithm. This code is supposed to be written during the step
6470// of type legalization, but given that we need to reconstruct the IR which is
6471// not doable there, we do it here.
6472// The IR after the optimization will look like:
6473// entry:
6474// if signed:
6475// ( (lhs_lo>>BW-1) ^ lhs_hi) || ( (rhs_lo>>BW-1) ^ rhs_hi) ? overflow,
6476// overflow_no
6477// else:
6478// (lhs_hi != 0) || (rhs_hi != 0) ? overflow, overflow_no
6479// overflow_no:
6480// overflow:
6481// overflow.res:
6482// \returns true if optimization was applied
6483// TODO: This optimization can be further improved to optimize branching on
6484// overflow where the 'overflow_no' BB can branch directly to the false
6485// successor of overflow, but that would add additional complexity so we leave
6486// it for future work.
6487bool CodeGenPrepare::optimizeMulWithOverflow(Instruction *I, bool IsSigned,
6488 ModifyDT &ModifiedDT) {
6489 // Check if target supports this optimization.
6491 I->getContext(),
6492 TLI->getValueType(*DL, I->getType()->getContainedType(0))))
6493 return false;
6494
6495 ExtractValueInst *MulExtract = nullptr, *OverflowExtract = nullptr;
6496 if (!matchOverflowPattern(I, MulExtract, OverflowExtract))
6497 return false;
6498
6499 // Keep track of the instruction to stop reoptimizing it again.
6500 InsertedInsts.insert(I);
6501
6502 Value *LHS = I->getOperand(0);
6503 Value *RHS = I->getOperand(1);
6504 Type *Ty = LHS->getType();
6505 unsigned VTHalfBitWidth = Ty->getScalarSizeInBits() / 2;
6506 Type *LegalTy = Ty->getWithNewBitWidth(VTHalfBitWidth);
6507
6508 // New BBs:
6509 BasicBlock *OverflowEntryBB =
6510 splitBlockBefore(I->getParent(), I, DTU, LI, nullptr, "");
6511 OverflowEntryBB->takeName(I->getParent());
6512 // Keep the 'br' instruction that is generated as a result of the split to be
6513 // erased/replaced later.
6514 Instruction *OldTerminator = OverflowEntryBB->getTerminator();
6515 BasicBlock *NoOverflowBB =
6516 BasicBlock::Create(I->getContext(), "overflow.no", I->getFunction());
6517 NoOverflowBB->moveAfter(OverflowEntryBB);
6518 BasicBlock *OverflowBB =
6519 BasicBlock::Create(I->getContext(), "overflow", I->getFunction());
6520 OverflowBB->moveAfter(NoOverflowBB);
6521
6522 // BB overflow.entry:
6523 IRBuilder<> Builder(OverflowEntryBB);
6524 // Extract low and high halves of LHS:
6525 Value *LoLHS = Builder.CreateTrunc(LHS, LegalTy, "lo.lhs");
6526 Value *HiLHS = Builder.CreateLShr(LHS, VTHalfBitWidth, "lhs.lsr");
6527 HiLHS = Builder.CreateTrunc(HiLHS, LegalTy, "hi.lhs");
6528
6529 // Extract low and high halves of RHS:
6530 Value *LoRHS = Builder.CreateTrunc(RHS, LegalTy, "lo.rhs");
6531 Value *HiRHS = Builder.CreateLShr(RHS, VTHalfBitWidth, "rhs.lsr");
6532 HiRHS = Builder.CreateTrunc(HiRHS, LegalTy, "hi.rhs");
6533
6534 Value *IsAnyBitTrue;
6535 if (IsSigned) {
6536 Value *SignLoLHS =
6537 Builder.CreateAShr(LoLHS, VTHalfBitWidth - 1, "sign.lo.lhs");
6538 Value *SignLoRHS =
6539 Builder.CreateAShr(LoRHS, VTHalfBitWidth - 1, "sign.lo.rhs");
6540 Value *XorLHS = Builder.CreateXor(HiLHS, SignLoLHS);
6541 Value *XorRHS = Builder.CreateXor(HiRHS, SignLoRHS);
6542 Value *Or = Builder.CreateOr(XorLHS, XorRHS, "or.lhs.rhs");
6543 IsAnyBitTrue = Builder.CreateCmp(ICmpInst::ICMP_NE, Or,
6544 ConstantInt::getNullValue(Or->getType()));
6545 } else {
6546 Value *CmpLHS = Builder.CreateCmp(ICmpInst::ICMP_NE, HiLHS,
6547 ConstantInt::getNullValue(LegalTy));
6548 Value *CmpRHS = Builder.CreateCmp(ICmpInst::ICMP_NE, HiRHS,
6549 ConstantInt::getNullValue(LegalTy));
6550 IsAnyBitTrue = Builder.CreateOr(CmpLHS, CmpRHS, "or.lhs.rhs");
6551 }
6552 Builder.CreateCondBr(IsAnyBitTrue, OverflowBB, NoOverflowBB);
6553
6554 // BB overflow.no:
6555 Builder.SetInsertPoint(NoOverflowBB);
6556 Value *ExtLoLHS, *ExtLoRHS;
6557 if (IsSigned) {
6558 ExtLoLHS = Builder.CreateSExt(LoLHS, Ty, "lo.lhs.ext");
6559 ExtLoRHS = Builder.CreateSExt(LoRHS, Ty, "lo.rhs.ext");
6560 } else {
6561 ExtLoLHS = Builder.CreateZExt(LoLHS, Ty, "lo.lhs.ext");
6562 ExtLoRHS = Builder.CreateZExt(LoRHS, Ty, "lo.rhs.ext");
6563 }
6564
6565 Value *Mul = Builder.CreateMul(ExtLoLHS, ExtLoRHS, "mul.overflow.no");
6566
6567 // Create the 'overflow.res' BB to merge the results of
6568 // the two paths:
6569 BasicBlock *OverflowResBB = I->getParent();
6570 OverflowResBB->setName("overflow.res");
6571
6572 // BB overflow.no: jump to overflow.res BB
6573 Builder.CreateBr(OverflowResBB);
6574 // No we don't need the old terminator in overflow.entry BB, erase it:
6575 OldTerminator->eraseFromParent();
6576
6577 // BB overflow.res:
6578 Builder.SetInsertPoint(OverflowResBB, OverflowResBB->getFirstInsertionPt());
6579 // Create PHI nodes to merge results from no.overflow BB and overflow BB to
6580 // replace the extract instructions.
6581 PHINode *OverflowResPHI = Builder.CreatePHI(Ty, 2),
6582 *OverflowFlagPHI =
6583 Builder.CreatePHI(IntegerType::getInt1Ty(I->getContext()), 2);
6584
6585 // Add the incoming values from no.overflow BB and later from overflow BB.
6586 OverflowResPHI->addIncoming(Mul, NoOverflowBB);
6587 OverflowFlagPHI->addIncoming(ConstantInt::getFalse(I->getContext()),
6588 NoOverflowBB);
6589
6590 // Replace all users of MulExtract and OverflowExtract to use the PHI nodes.
6591 if (MulExtract) {
6592 MulExtract->replaceAllUsesWith(OverflowResPHI);
6593 MulExtract->eraseFromParent();
6594 }
6595 if (OverflowExtract) {
6596 OverflowExtract->replaceAllUsesWith(OverflowFlagPHI);
6597 OverflowExtract->eraseFromParent();
6598 }
6599
6600 // Remove the intrinsic from parent (overflow.res BB) as it will be part of
6601 // overflow BB
6602 I->removeFromParent();
6603 // BB overflow:
6604 I->insertInto(OverflowBB, OverflowBB->end());
6605 Builder.SetInsertPoint(OverflowBB, OverflowBB->end());
6606 Value *MulOverflow = Builder.CreateExtractValue(I, {0}, "mul.overflow");
6607 Value *OverflowFlag = Builder.CreateExtractValue(I, {1}, "overflow.flag");
6608 Builder.CreateBr(OverflowResBB);
6609
6610 // Add The Extracted values to the PHINodes in the overflow.res BB.
6611 OverflowResPHI->addIncoming(MulOverflow, OverflowBB);
6612 OverflowFlagPHI->addIncoming(OverflowFlag, OverflowBB);
6613
6614 DTU->applyUpdates({{DominatorTree::Insert, OverflowEntryBB, OverflowBB},
6615 {DominatorTree::Insert, OverflowEntryBB, NoOverflowBB},
6616 {DominatorTree::Insert, NoOverflowBB, OverflowResBB},
6617 {DominatorTree::Delete, OverflowEntryBB, OverflowResBB},
6618 {DominatorTree::Insert, OverflowBB, OverflowResBB}});
6619
6620 ModifiedDT = ModifyDT::ModifyBBDT;
6621 return true;
6622}
6623
6624/// If there are any memory operands, use OptimizeMemoryInst to sink their
6625/// address computing into the block when possible / profitable.
6626bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
6627 bool MadeChange = false;
6628
6629 const TargetRegisterInfo *TRI =
6631 TargetLowering::AsmOperandInfoVector TargetConstraints =
6632 TLI->ParseConstraints(*DL, TRI, *CS);
6633 unsigned ArgNo = 0;
6634 for (TargetLowering::AsmOperandInfo &OpInfo : TargetConstraints) {
6635 // Compute the constraint code and ConstraintType to use.
6636 TLI->ComputeConstraintToUse(OpInfo, SDValue());
6637
6638 // TODO: Also handle C_Address?
6639 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
6640 OpInfo.isIndirect) {
6641 Value *OpVal = CS->getArgOperand(ArgNo++);
6642 MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
6643 } else if (OpInfo.Type == InlineAsm::isInput)
6644 ArgNo++;
6645 }
6646
6647 return MadeChange;
6648}
6649
6650/// Check if all the uses of \p Val are equivalent (or free) zero or
6651/// sign extensions.
6652static bool hasSameExtUse(Value *Val, const TargetLowering &TLI) {
6653 assert(!Val->use_empty() && "Input must have at least one use");
6654 const Instruction *FirstUser = cast<Instruction>(*Val->user_begin());
6655 bool IsSExt = isa<SExtInst>(FirstUser);
6656 Type *ExtTy = FirstUser->getType();
6657 for (const User *U : Val->users()) {
6658 const Instruction *UI = cast<Instruction>(U);
6659 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
6660 return false;
6661 Type *CurTy = UI->getType();
6662 // Same input and output types: Same instruction after CSE.
6663 if (CurTy == ExtTy)
6664 continue;
6665
6666 // If IsSExt is true, we are in this situation:
6667 // a = Val
6668 // b = sext ty1 a to ty2
6669 // c = sext ty1 a to ty3
6670 // Assuming ty2 is shorter than ty3, this could be turned into:
6671 // a = Val
6672 // b = sext ty1 a to ty2
6673 // c = sext ty2 b to ty3
6674 // However, the last sext is not free.
6675 if (IsSExt)
6676 return false;
6677
6678 // This is a ZExt, maybe this is free to extend from one type to another.
6679 // In that case, we would not account for a different use.
6680 Type *NarrowTy;
6681 Type *LargeTy;
6682 if (ExtTy->getScalarType()->getIntegerBitWidth() >
6683 CurTy->getScalarType()->getIntegerBitWidth()) {
6684 NarrowTy = CurTy;
6685 LargeTy = ExtTy;
6686 } else {
6687 NarrowTy = ExtTy;
6688 LargeTy = CurTy;
6689 }
6690
6691 if (!TLI.isZExtFree(NarrowTy, LargeTy))
6692 return false;
6693 }
6694 // All uses are the same or can be derived from one another for free.
6695 return true;
6696}
6697
6698/// Try to speculatively promote extensions in \p Exts and continue
6699/// promoting through newly promoted operands recursively as far as doing so is
6700/// profitable. Save extensions profitably moved up, in \p ProfitablyMovedExts.
6701/// When some promotion happened, \p TPT contains the proper state to revert
6702/// them.
6703///
6704/// \return true if some promotion happened, false otherwise.
6705bool CodeGenPrepare::tryToPromoteExts(
6706 TypePromotionTransaction &TPT, const SmallVectorImpl<Instruction *> &Exts,
6707 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
6708 unsigned CreatedInstsCost) {
6709 bool Promoted = false;
6710
6711 // Iterate over all the extensions to try to promote them.
6712 for (auto *I : Exts) {
6713 // Early check if we directly have ext(load).
6714 if (isa<LoadInst>(I->getOperand(0))) {
6715 ProfitablyMovedExts.push_back(I);
6716 continue;
6717 }
6718
6719 // Check whether or not we want to do any promotion. The reason we have
6720 // this check inside the for loop is to catch the case where an extension
6721 // is directly fed by a load because in such case the extension can be moved
6722 // up without any promotion on its operands.
6724 return false;
6725
6726 // Get the action to perform the promotion.
6727 TypePromotionHelper::Action TPH =
6728 TypePromotionHelper::getAction(I, InsertedInsts, *TLI, PromotedInsts);
6729 // Check if we can promote.
6730 if (!TPH) {
6731 // Save the current extension as we cannot move up through its operand.
6732 ProfitablyMovedExts.push_back(I);
6733 continue;
6734 }
6735
6736 // Save the current state.
6737 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
6738 TPT.getRestorationPoint();
6739 SmallVector<Instruction *, 4> NewExts;
6740 unsigned NewCreatedInstsCost = 0;
6741 unsigned ExtCost = !TLI->isExtFree(I);
6742 // Promote.
6743 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
6744 &NewExts, nullptr, *TLI);
6745 assert(PromotedVal &&
6746 "TypePromotionHelper should have filtered out those cases");
6747
6748 // We would be able to merge only one extension in a load.
6749 // Therefore, if we have more than 1 new extension we heuristically
6750 // cut this search path, because it means we degrade the code quality.
6751 // With exactly 2, the transformation is neutral, because we will merge
6752 // one extension but leave one. However, we optimistically keep going,
6753 // because the new extension may be removed too. Also avoid replacing a
6754 // single free extension with multiple extensions, as this increases the
6755 // number of IR instructions while not providing any savings.
6756 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
6757 // FIXME: It would be possible to propagate a negative value instead of
6758 // conservatively ceiling it to 0.
6759 TotalCreatedInstsCost =
6760 std::max((long long)0, (TotalCreatedInstsCost - ExtCost));
6761 if (!StressExtLdPromotion &&
6762 (TotalCreatedInstsCost > 1 ||
6763 !isPromotedInstructionLegal(*TLI, *DL, PromotedVal) ||
6764 (ExtCost == 0 && NewExts.size() > 1))) {
6765 // This promotion is not profitable, rollback to the previous state, and
6766 // save the current extension in ProfitablyMovedExts as the latest
6767 // speculative promotion turned out to be unprofitable.
6768 TPT.rollback(LastKnownGood);
6769 ProfitablyMovedExts.push_back(I);
6770 continue;
6771 }
6772 // Continue promoting NewExts as far as doing so is profitable.
6773 SmallVector<Instruction *, 2> NewlyMovedExts;
6774 (void)tryToPromoteExts(TPT, NewExts, NewlyMovedExts, TotalCreatedInstsCost);
6775 bool NewPromoted = false;
6776 for (auto *ExtInst : NewlyMovedExts) {
6777 Instruction *MovedExt = cast<Instruction>(ExtInst);
6778 Value *ExtOperand = MovedExt->getOperand(0);
6779 // If we have reached to a load, we need this extra profitability check
6780 // as it could potentially be merged into an ext(load).
6781 if (isa<LoadInst>(ExtOperand) &&
6782 !(StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
6783 (ExtOperand->hasOneUse() || hasSameExtUse(ExtOperand, *TLI))))
6784 continue;
6785
6786 ProfitablyMovedExts.push_back(MovedExt);
6787 NewPromoted = true;
6788 }
6789
6790 // If none of speculative promotions for NewExts is profitable, rollback
6791 // and save the current extension (I) as the last profitable extension.
6792 if (!NewPromoted) {
6793 TPT.rollback(LastKnownGood);
6794 ProfitablyMovedExts.push_back(I);
6795 continue;
6796 }
6797 // The promotion is profitable.
6798 Promoted = true;
6799 }
6800 return Promoted;
6801}
6802
6803/// Merging redundant sexts when one is dominating the other.
6804bool CodeGenPrepare::mergeSExts(Function &F) {
6805 bool Changed = false;
6806 for (auto &Entry : ValToSExtendedUses) {
6807 SExts &Insts = Entry.second;
6808 SExts CurPts;
6809 for (Instruction *Inst : Insts) {
6810 if (RemovedInsts.count(Inst) || !isa<SExtInst>(Inst) ||
6811 Inst->getOperand(0) != Entry.first)
6812 continue;
6813 bool inserted = false;
6814 for (auto &Pt : CurPts) {
6815 if (getDT().dominates(Inst, Pt)) {
6816 replaceAllUsesWith(Pt, Inst, FreshBBs, IsHugeFunc);
6817 RemovedInsts.insert(Pt);
6818 Pt->removeFromParent();
6819 Pt = Inst;
6820 inserted = true;
6821 Changed = true;
6822 break;
6823 }
6824 if (!getDT().dominates(Pt, Inst))
6825 // Give up if we need to merge in a common dominator as the
6826 // experiments show it is not profitable.
6827 continue;
6828 replaceAllUsesWith(Inst, Pt, FreshBBs, IsHugeFunc);
6829 RemovedInsts.insert(Inst);
6830 Inst->removeFromParent();
6831 inserted = true;
6832 Changed = true;
6833 break;
6834 }
6835 if (!inserted)
6836 CurPts.push_back(Inst);
6837 }
6838 }
6839 return Changed;
6840}
6841
6842// Splitting large data structures so that the GEPs accessing them can have
6843// smaller offsets so that they can be sunk to the same blocks as their users.
6844// For example, a large struct starting from %base is split into two parts
6845// where the second part starts from %new_base.
6846//
6847// Before:
6848// BB0:
6849// %base =
6850//
6851// BB1:
6852// %gep0 = gep %base, off0
6853// %gep1 = gep %base, off1
6854// %gep2 = gep %base, off2
6855//
6856// BB2:
6857// %load1 = load %gep0
6858// %load2 = load %gep1
6859// %load3 = load %gep2
6860//
6861// After:
6862// BB0:
6863// %base =
6864// %new_base = gep %base, off0
6865//
6866// BB1:
6867// %new_gep0 = %new_base
6868// %new_gep1 = gep %new_base, off1 - off0
6869// %new_gep2 = gep %new_base, off2 - off0
6870//
6871// BB2:
6872// %load1 = load i32, i32* %new_gep0
6873// %load2 = load i32, i32* %new_gep1
6874// %load3 = load i32, i32* %new_gep2
6875//
6876// %new_gep1 and %new_gep2 can be sunk to BB2 now after the splitting because
6877// their offsets are smaller enough to fit into the addressing mode.
6878bool CodeGenPrepare::splitLargeGEPOffsets() {
6879 bool Changed = false;
6880 for (auto &Entry : LargeOffsetGEPMap) {
6881 Value *OldBase = Entry.first;
6882 SmallVectorImpl<std::pair<AssertingVH<GetElementPtrInst>, int64_t>>
6883 &LargeOffsetGEPs = Entry.second;
6884 auto compareGEPOffset =
6885 [&](const std::pair<GetElementPtrInst *, int64_t> &LHS,
6886 const std::pair<GetElementPtrInst *, int64_t> &RHS) {
6887 if (LHS.first == RHS.first)
6888 return false;
6889 if (LHS.second != RHS.second)
6890 return LHS.second < RHS.second;
6891 return LargeOffsetGEPID[LHS.first] < LargeOffsetGEPID[RHS.first];
6892 };
6893 // Sorting all the GEPs of the same data structures based on the offsets.
6894 llvm::sort(LargeOffsetGEPs, compareGEPOffset);
6895 LargeOffsetGEPs.erase(llvm::unique(LargeOffsetGEPs), LargeOffsetGEPs.end());
6896 // Skip if all the GEPs have the same offsets.
6897 if (LargeOffsetGEPs.front().second == LargeOffsetGEPs.back().second)
6898 continue;
6899 GetElementPtrInst *BaseGEP = LargeOffsetGEPs.begin()->first;
6900 int64_t BaseOffset = LargeOffsetGEPs.begin()->second;
6901 Value *NewBaseGEP = nullptr;
6902
6903 auto createNewBase = [&](int64_t BaseOffset, Value *OldBase,
6904 GetElementPtrInst *GEP) {
6905 LLVMContext &Ctx = GEP->getContext();
6906 Type *PtrIdxTy = DL->getIndexType(GEP->getType());
6907 Type *I8PtrTy =
6908 PointerType::get(Ctx, GEP->getType()->getPointerAddressSpace());
6909
6910 BasicBlock::iterator NewBaseInsertPt;
6911 BasicBlock *NewBaseInsertBB;
6912 if (auto *BaseI = dyn_cast<Instruction>(OldBase)) {
6913 // If the base of the struct is an instruction, the new base will be
6914 // inserted close to it.
6915 NewBaseInsertBB = BaseI->getParent();
6916 if (isa<PHINode>(BaseI))
6917 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
6918 else if (InvokeInst *Invoke = dyn_cast<InvokeInst>(BaseI)) {
6919 NewBaseInsertBB =
6920 SplitEdge(NewBaseInsertBB, Invoke->getNormalDest(), &getDT(), LI);
6921 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
6922 } else
6923 NewBaseInsertPt = std::next(BaseI->getIterator());
6924 } else {
6925 // If the current base is an argument or global value, the new base
6926 // will be inserted to the entry block.
6927 NewBaseInsertBB = &BaseGEP->getFunction()->getEntryBlock();
6928 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
6929 }
6930 IRBuilder<> NewBaseBuilder(NewBaseInsertBB, NewBaseInsertPt);
6931 // Create a new base.
6932 // TODO: Avoid implicit trunc?
6933 // See https://github.com/llvm/llvm-project/issues/112510.
6934 Value *BaseIndex =
6935 ConstantInt::getSigned(PtrIdxTy, BaseOffset, /*ImplicitTrunc=*/true);
6936 NewBaseGEP = OldBase;
6937 if (NewBaseGEP->getType() != I8PtrTy)
6938 NewBaseGEP = NewBaseBuilder.CreatePointerCast(NewBaseGEP, I8PtrTy);
6939 NewBaseGEP =
6940 NewBaseBuilder.CreatePtrAdd(NewBaseGEP, BaseIndex, "splitgep");
6941 NewGEPBases.insert(NewBaseGEP);
6942 return;
6943 };
6944
6945 // Check whether all the offsets can be encoded with prefered common base.
6946 if (int64_t PreferBase = TLI->getPreferredLargeGEPBaseOffset(
6947 LargeOffsetGEPs.front().second, LargeOffsetGEPs.back().second)) {
6948 BaseOffset = PreferBase;
6949 // Create a new base if the offset of the BaseGEP can be decoded with one
6950 // instruction.
6951 createNewBase(BaseOffset, OldBase, BaseGEP);
6952 }
6953
6954 auto *LargeOffsetGEP = LargeOffsetGEPs.begin();
6955 while (LargeOffsetGEP != LargeOffsetGEPs.end()) {
6956 GetElementPtrInst *GEP = LargeOffsetGEP->first;
6957 int64_t Offset = LargeOffsetGEP->second;
6958 if (Offset != BaseOffset) {
6959 TargetLowering::AddrMode AddrMode;
6960 AddrMode.HasBaseReg = true;
6961 AddrMode.BaseOffs = Offset - BaseOffset;
6962 // The result type of the GEP might not be the type of the memory
6963 // access.
6964 if (!TLI->isLegalAddressingMode(*DL, AddrMode,
6965 GEP->getResultElementType(),
6966 GEP->getAddressSpace())) {
6967 // We need to create a new base if the offset to the current base is
6968 // too large to fit into the addressing mode. So, a very large struct
6969 // may be split into several parts.
6970 BaseGEP = GEP;
6971 BaseOffset = Offset;
6972 NewBaseGEP = nullptr;
6973 }
6974 }
6975
6976 // Generate a new GEP to replace the current one.
6977 Type *PtrIdxTy = DL->getIndexType(GEP->getType());
6978
6979 if (!NewBaseGEP) {
6980 // Create a new base if we don't have one yet. Find the insertion
6981 // pointer for the new base first.
6982 createNewBase(BaseOffset, OldBase, GEP);
6983 }
6984
6985 IRBuilder<> Builder(GEP);
6986 Value *NewGEP = NewBaseGEP;
6987 if (Offset != BaseOffset) {
6988 // Calculate the new offset for the new GEP.
6989 Value *Index = ConstantInt::get(PtrIdxTy, Offset - BaseOffset);
6990 NewGEP = Builder.CreatePtrAdd(NewBaseGEP, Index);
6991 }
6992 replaceAllUsesWith(GEP, NewGEP, FreshBBs, IsHugeFunc);
6993 LargeOffsetGEPID.erase(GEP);
6994 LargeOffsetGEP = LargeOffsetGEPs.erase(LargeOffsetGEP);
6995 GEP->eraseFromParent();
6996 Changed = true;
6997 }
6998 }
6999 return Changed;
7000}
7001
7002bool CodeGenPrepare::optimizePhiType(
7003 PHINode *I, SmallPtrSetImpl<PHINode *> &Visited,
7004 SmallPtrSetImpl<Instruction *> &DeletedInstrs) {
7005 // We are looking for a collection on interconnected phi nodes that together
7006 // only use loads/bitcasts and are used by stores/bitcasts, and the bitcasts
7007 // are of the same type. Convert the whole set of nodes to the type of the
7008 // bitcast.
7009 Type *PhiTy = I->getType();
7010 Type *ConvertTy = nullptr;
7011 if (Visited.count(I) ||
7012 (!I->getType()->isIntegerTy() && !I->getType()->isFloatingPointTy()))
7013 return false;
7014
7015 SmallVector<Instruction *, 4> Worklist;
7016 Worklist.push_back(cast<Instruction>(I));
7017 SmallPtrSet<PHINode *, 4> PhiNodes;
7018 SmallPtrSet<ConstantData *, 4> Constants;
7019 PhiNodes.insert(I);
7020 Visited.insert(I);
7021 SmallPtrSet<Instruction *, 4> Defs;
7022 SmallPtrSet<Instruction *, 4> Uses;
7023 // This works by adding extra bitcasts between load/stores and removing
7024 // existing bitcasts. If we have a phi(bitcast(load)) or a store(bitcast(phi))
7025 // we can get in the situation where we remove a bitcast in one iteration
7026 // just to add it again in the next. We need to ensure that at least one
7027 // bitcast we remove are anchored to something that will not change back.
7028 bool AnyAnchored = false;
7029
7030 while (!Worklist.empty()) {
7031 Instruction *II = Worklist.pop_back_val();
7032
7033 if (auto *Phi = dyn_cast<PHINode>(II)) {
7034 // Handle Defs, which might also be PHI's
7035 for (Value *V : Phi->incoming_values()) {
7036 if (auto *OpPhi = dyn_cast<PHINode>(V)) {
7037 if (!PhiNodes.count(OpPhi)) {
7038 if (!Visited.insert(OpPhi).second)
7039 return false;
7040 PhiNodes.insert(OpPhi);
7041 Worklist.push_back(OpPhi);
7042 }
7043 } else if (auto *OpLoad = dyn_cast<LoadInst>(V)) {
7044 if (!OpLoad->isSimple())
7045 return false;
7046 if (Defs.insert(OpLoad).second)
7047 Worklist.push_back(OpLoad);
7048 } else if (auto *OpEx = dyn_cast<ExtractElementInst>(V)) {
7049 if (Defs.insert(OpEx).second)
7050 Worklist.push_back(OpEx);
7051 } else if (auto *OpBC = dyn_cast<BitCastInst>(V)) {
7052 if (!ConvertTy)
7053 ConvertTy = OpBC->getOperand(0)->getType();
7054 if (OpBC->getOperand(0)->getType() != ConvertTy)
7055 return false;
7056 if (Defs.insert(OpBC).second) {
7057 Worklist.push_back(OpBC);
7058 AnyAnchored |= !isa<LoadInst>(OpBC->getOperand(0)) &&
7059 !isa<ExtractElementInst>(OpBC->getOperand(0));
7060 }
7061 } else if (auto *OpC = dyn_cast<ConstantData>(V))
7062 Constants.insert(OpC);
7063 else
7064 return false;
7065 }
7066 }
7067
7068 // Handle uses which might also be phi's
7069 for (User *V : II->users()) {
7070 if (auto *OpPhi = dyn_cast<PHINode>(V)) {
7071 if (!PhiNodes.count(OpPhi)) {
7072 if (Visited.count(OpPhi))
7073 return false;
7074 PhiNodes.insert(OpPhi);
7075 Visited.insert(OpPhi);
7076 Worklist.push_back(OpPhi);
7077 }
7078 } else if (auto *OpStore = dyn_cast<StoreInst>(V)) {
7079 if (!OpStore->isSimple() || OpStore->getOperand(0) != II)
7080 return false;
7081 Uses.insert(OpStore);
7082 } else if (auto *OpBC = dyn_cast<BitCastInst>(V)) {
7083 if (!ConvertTy)
7084 ConvertTy = OpBC->getType();
7085 if (OpBC->getType() != ConvertTy)
7086 return false;
7087 Uses.insert(OpBC);
7088 AnyAnchored |=
7089 any_of(OpBC->users(), [](User *U) { return !isa<StoreInst>(U); });
7090 } else {
7091 return false;
7092 }
7093 }
7094 }
7095
7096 if (!ConvertTy || !AnyAnchored || PhiTy == ConvertTy ||
7097 !TLI->shouldConvertPhiType(PhiTy, ConvertTy))
7098 return false;
7099
7100 LLVM_DEBUG(dbgs() << "Converting " << *I << "\n and connected nodes to "
7101 << *ConvertTy << "\n");
7102
7103 // Create all the new phi nodes of the new type, and bitcast any loads to the
7104 // correct type.
7105 ValueToValueMap ValMap;
7106 for (ConstantData *C : Constants)
7107 ValMap[C] = ConstantExpr::getBitCast(C, ConvertTy);
7108 for (Instruction *D : Defs) {
7109 if (isa<BitCastInst>(D)) {
7110 ValMap[D] = D->getOperand(0);
7111 DeletedInstrs.insert(D);
7112 } else {
7113 BasicBlock::iterator insertPt = std::next(D->getIterator());
7114 ValMap[D] = new BitCastInst(D, ConvertTy, D->getName() + ".bc", insertPt);
7115 }
7116 }
7117 for (PHINode *Phi : PhiNodes)
7118 ValMap[Phi] = PHINode::Create(ConvertTy, Phi->getNumIncomingValues(),
7119 Phi->getName() + ".tc", Phi->getIterator());
7120 // Pipe together all the PhiNodes.
7121 for (PHINode *Phi : PhiNodes) {
7122 PHINode *NewPhi = cast<PHINode>(ValMap[Phi]);
7123 for (int i = 0, e = Phi->getNumIncomingValues(); i < e; i++)
7124 NewPhi->addIncoming(ValMap[Phi->getIncomingValue(i)],
7125 Phi->getIncomingBlock(i));
7126 Visited.insert(NewPhi);
7127 }
7128 // And finally pipe up the stores and bitcasts
7129 for (Instruction *U : Uses) {
7130 if (isa<BitCastInst>(U)) {
7131 DeletedInstrs.insert(U);
7132 replaceAllUsesWith(U, ValMap[U->getOperand(0)], FreshBBs, IsHugeFunc);
7133 } else {
7134 U->setOperand(0, new BitCastInst(ValMap[U->getOperand(0)], PhiTy, "bc",
7135 U->getIterator()));
7136 }
7137 }
7138
7139 // Save the removed phis to be deleted later.
7140 DeletedInstrs.insert_range(PhiNodes);
7141 return true;
7142}
7143
7144bool CodeGenPrepare::optimizePhiTypes(Function &F) {
7145 if (!OptimizePhiTypes)
7146 return false;
7147
7148 bool Changed = false;
7149 SmallPtrSet<PHINode *, 4> Visited;
7150 SmallPtrSet<Instruction *, 4> DeletedInstrs;
7151
7152 // Attempt to optimize all the phis in the functions to the correct type.
7153 for (auto &BB : F)
7154 for (auto &Phi : BB.phis())
7155 Changed |= optimizePhiType(&Phi, Visited, DeletedInstrs);
7156
7157 // Remove any old phi's that have been converted.
7158 for (auto *I : DeletedInstrs) {
7159 replaceAllUsesWith(I, PoisonValue::get(I->getType()), FreshBBs, IsHugeFunc);
7160 I->eraseFromParent();
7161 }
7162
7163 return Changed;
7164}
7165
7166/// Return true, if an ext(load) can be formed from an extension in
7167/// \p MovedExts.
7168bool CodeGenPrepare::canFormExtLd(
7169 const SmallVectorImpl<Instruction *> &MovedExts, LoadInst *&LI,
7170 Instruction *&Inst, bool HasPromoted) {
7171 for (auto *MovedExtInst : MovedExts) {
7172 if (isa<LoadInst>(MovedExtInst->getOperand(0))) {
7173 LI = cast<LoadInst>(MovedExtInst->getOperand(0));
7174 Inst = MovedExtInst;
7175 break;
7176 }
7177 }
7178 if (!LI)
7179 return false;
7180
7181 // If they're already in the same block, there's nothing to do.
7182 // Make the cheap checks first if we did not promote.
7183 // If we promoted, we need to check if it is indeed profitable.
7184 if (!HasPromoted && LI->getParent() == Inst->getParent())
7185 return false;
7186
7187 return TLI->isExtLoad(LI, Inst, *DL);
7188}
7189
7190/// Move a zext or sext fed by a load into the same basic block as the load,
7191/// unless conditions are unfavorable. This allows SelectionDAG to fold the
7192/// extend into the load.
7193///
7194/// E.g.,
7195/// \code
7196/// %ld = load i32* %addr
7197/// %add = add nuw i32 %ld, 4
7198/// %zext = zext i32 %add to i64
7199// \endcode
7200/// =>
7201/// \code
7202/// %ld = load i32* %addr
7203/// %zext = zext i32 %ld to i64
7204/// %add = add nuw i64 %zext, 4
7205/// \encode
7206/// Note that the promotion in %add to i64 is done in tryToPromoteExts(), which
7207/// allow us to match zext(load i32*) to i64.
7208///
7209/// Also, try to promote the computations used to obtain a sign extended
7210/// value used into memory accesses.
7211/// E.g.,
7212/// \code
7213/// a = add nsw i32 b, 3
7214/// d = sext i32 a to i64
7215/// e = getelementptr ..., i64 d
7216/// \endcode
7217/// =>
7218/// \code
7219/// f = sext i32 b to i64
7220/// a = add nsw i64 f, 3
7221/// e = getelementptr ..., i64 a
7222/// \endcode
7223///
7224/// \p Inst[in/out] the extension may be modified during the process if some
7225/// promotions apply.
7226bool CodeGenPrepare::optimizeExt(Instruction *&Inst) {
7227 bool AllowPromotionWithoutCommonHeader = false;
7228 /// See if it is an interesting sext operations for the address type
7229 /// promotion before trying to promote it, e.g., the ones with the right
7230 /// type and used in memory accesses.
7231 bool ATPConsiderable = TTI->shouldConsiderAddressTypePromotion(
7232 *Inst, AllowPromotionWithoutCommonHeader);
7233 TypePromotionTransaction TPT(RemovedInsts);
7234 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
7235 TPT.getRestorationPoint();
7237 SmallVector<Instruction *, 2> SpeculativelyMovedExts;
7238 Exts.push_back(Inst);
7239
7240 bool HasPromoted = tryToPromoteExts(TPT, Exts, SpeculativelyMovedExts);
7241
7242 // Look for a load being extended.
7243 LoadInst *LI = nullptr;
7244 Instruction *ExtFedByLoad;
7245
7246 // Try to promote a chain of computation if it allows to form an extended
7247 // load.
7248 if (canFormExtLd(SpeculativelyMovedExts, LI, ExtFedByLoad, HasPromoted)) {
7249 assert(LI && ExtFedByLoad && "Expect a valid load and extension");
7250 TPT.commit();
7251 // Move the extend into the same block as the load.
7252 ExtFedByLoad->moveAfter(LI);
7253 ++NumExtsMoved;
7254 Inst = ExtFedByLoad;
7255 return true;
7256 }
7257
7258 // Continue promoting SExts if known as considerable depending on targets.
7259 if (ATPConsiderable &&
7260 performAddressTypePromotion(Inst, AllowPromotionWithoutCommonHeader,
7261 HasPromoted, TPT, SpeculativelyMovedExts))
7262 return true;
7263
7264 TPT.rollback(LastKnownGood);
7265 return false;
7266}
7267
7268// Perform address type promotion if doing so is profitable.
7269// If AllowPromotionWithoutCommonHeader == false, we should find other sext
7270// instructions that sign extended the same initial value. However, if
7271// AllowPromotionWithoutCommonHeader == true, we expect promoting the
7272// extension is just profitable.
7273bool CodeGenPrepare::performAddressTypePromotion(
7274 Instruction *&Inst, bool AllowPromotionWithoutCommonHeader,
7275 bool HasPromoted, TypePromotionTransaction &TPT,
7276 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts) {
7277 bool Promoted = false;
7278 SmallPtrSet<Instruction *, 1> UnhandledExts;
7279 bool AllSeenFirst = true;
7280 for (auto *I : SpeculativelyMovedExts) {
7281 Value *HeadOfChain = I->getOperand(0);
7282 auto AlreadySeen = SeenChainsForSExt.find(HeadOfChain);
7283 // If there is an unhandled SExt which has the same header, try to promote
7284 // it as well.
7285 if (AlreadySeen != SeenChainsForSExt.end()) {
7286 if (AlreadySeen->second != nullptr)
7287 UnhandledExts.insert(AlreadySeen->second);
7288 AllSeenFirst = false;
7289 }
7290 }
7291
7292 if (!AllSeenFirst || (AllowPromotionWithoutCommonHeader &&
7293 SpeculativelyMovedExts.size() == 1)) {
7294 TPT.commit();
7295 if (HasPromoted)
7296 Promoted = true;
7297 for (auto *I : SpeculativelyMovedExts) {
7298 Value *HeadOfChain = I->getOperand(0);
7299 SeenChainsForSExt[HeadOfChain] = nullptr;
7300 ValToSExtendedUses[HeadOfChain].push_back(I);
7301 }
7302 // Update Inst as promotion happen.
7303 Inst = SpeculativelyMovedExts.pop_back_val();
7304 } else {
7305 // This is the first chain visited from the header, keep the current chain
7306 // as unhandled. Defer to promote this until we encounter another SExt
7307 // chain derived from the same header.
7308 for (auto *I : SpeculativelyMovedExts) {
7309 Value *HeadOfChain = I->getOperand(0);
7310 SeenChainsForSExt[HeadOfChain] = Inst;
7311 }
7312 return false;
7313 }
7314
7315 if (!AllSeenFirst && !UnhandledExts.empty())
7316 for (auto *VisitedSExt : UnhandledExts) {
7317 if (RemovedInsts.count(VisitedSExt))
7318 continue;
7319 TypePromotionTransaction TPT(RemovedInsts);
7321 SmallVector<Instruction *, 2> Chains;
7322 Exts.push_back(VisitedSExt);
7323 bool HasPromoted = tryToPromoteExts(TPT, Exts, Chains);
7324 TPT.commit();
7325 if (HasPromoted)
7326 Promoted = true;
7327 for (auto *I : Chains) {
7328 Value *HeadOfChain = I->getOperand(0);
7329 // Mark this as handled.
7330 SeenChainsForSExt[HeadOfChain] = nullptr;
7331 ValToSExtendedUses[HeadOfChain].push_back(I);
7332 }
7333 }
7334 return Promoted;
7335}
7336
7337bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
7338 BasicBlock *DefBB = I->getParent();
7339
7340 // If the result of a {s|z}ext and its source are both live out, rewrite all
7341 // other uses of the source with result of extension.
7342 Value *Src = I->getOperand(0);
7343 if (Src->hasOneUse())
7344 return false;
7345
7346 // Only do this xform if truncating is free.
7347 if (!TLI->isTruncateFree(I->getType(), Src->getType()))
7348 return false;
7349
7350 // Only safe to perform the optimization if the source is also defined in
7351 // this block.
7352 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
7353 return false;
7354
7355 bool DefIsLiveOut = false;
7356 for (User *U : I->users()) {
7358
7359 // Figure out which BB this ext is used in.
7360 BasicBlock *UserBB = UI->getParent();
7361 if (UserBB == DefBB)
7362 continue;
7363 DefIsLiveOut = true;
7364 break;
7365 }
7366 if (!DefIsLiveOut)
7367 return false;
7368
7369 // Make sure none of the uses are PHI nodes.
7370 for (User *U : Src->users()) {
7372 BasicBlock *UserBB = UI->getParent();
7373 if (UserBB == DefBB)
7374 continue;
7375 // Be conservative. We don't want this xform to end up introducing
7376 // reloads just before load / store instructions.
7377 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
7378 return false;
7379 }
7380
7381 // InsertedTruncs - Only insert one trunc in each block once.
7382 DenseMap<BasicBlock *, Instruction *> InsertedTruncs;
7383
7384 bool MadeChange = false;
7385 for (Use &U : make_early_inc_range(Src->uses())) {
7386 Instruction *User = cast<Instruction>(U.getUser());
7387
7388 // Figure out which BB this ext is used in.
7389 BasicBlock *UserBB = User->getParent();
7390 if (UserBB == DefBB)
7391 continue;
7392
7393 // Both src and def are live in this block. Rewrite the use.
7394 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
7395
7396 if (!InsertedTrunc) {
7397 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
7398 assert(InsertPt != UserBB->end());
7399 InsertedTrunc = new TruncInst(I, Src->getType(), "");
7400 InsertedTrunc->insertBefore(*UserBB, InsertPt);
7401 InsertedInsts.insert(InsertedTrunc);
7402 }
7403
7404 // Replace a use of the {s|z}ext source with a use of the result.
7405 U = InsertedTrunc;
7406 ++NumExtUses;
7407 MadeChange = true;
7408 }
7409
7410 return MadeChange;
7411}
7412
7413// Find loads whose uses only use some of the loaded value's bits. Add an "and"
7414// just after the load if the target can fold this into one extload instruction,
7415// with the hope of eliminating some of the other later "and" instructions using
7416// the loaded value. "and"s that are made trivially redundant by the insertion
7417// of the new "and" are removed by this function, while others (e.g. those whose
7418// path from the load goes through a phi) are left for isel to potentially
7419// remove.
7420//
7421// For example:
7422//
7423// b0:
7424// x = load i32
7425// ...
7426// b1:
7427// y = and x, 0xff
7428// z = use y
7429//
7430// becomes:
7431//
7432// b0:
7433// x = load i32
7434// x' = and x, 0xff
7435// ...
7436// b1:
7437// z = use x'
7438//
7439// whereas:
7440//
7441// b0:
7442// x1 = load i32
7443// ...
7444// b1:
7445// x2 = load i32
7446// ...
7447// b2:
7448// x = phi x1, x2
7449// y = and x, 0xff
7450//
7451// becomes (after a call to optimizeLoadExt for each load):
7452//
7453// b0:
7454// x1 = load i32
7455// x1' = and x1, 0xff
7456// ...
7457// b1:
7458// x2 = load i32
7459// x2' = and x2, 0xff
7460// ...
7461// b2:
7462// x = phi x1', x2'
7463// y = and x, 0xff
7464bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
7465 if (!Load->isSimple() || !Load->getType()->isIntOrPtrTy())
7466 return false;
7467
7468 // Skip loads we've already transformed.
7469 if (Load->hasOneUse() &&
7470 InsertedInsts.count(cast<Instruction>(*Load->user_begin())))
7471 return false;
7472
7473 // Look at all uses of Load, looking through phis, to determine how many bits
7474 // of the loaded value are needed.
7475 SmallVector<Instruction *, 8> WorkList;
7476 SmallPtrSet<Instruction *, 16> Visited;
7477 SmallVector<Instruction *, 8> AndsToMaybeRemove;
7478 SmallVector<Instruction *, 8> DropFlags;
7479 for (auto *U : Load->users())
7480 WorkList.push_back(cast<Instruction>(U));
7481
7482 EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
7483 unsigned BitWidth = LoadResultVT.getSizeInBits();
7484 // If the BitWidth is 0, do not try to optimize the type
7485 if (BitWidth == 0)
7486 return false;
7487
7488 APInt DemandBits(BitWidth, 0);
7489 APInt WidestAndBits(BitWidth, 0);
7490
7491 while (!WorkList.empty()) {
7492 Instruction *I = WorkList.pop_back_val();
7493
7494 // Break use-def graph loops.
7495 if (!Visited.insert(I).second)
7496 continue;
7497
7498 // For a PHI node, push all of its users.
7499 if (auto *Phi = dyn_cast<PHINode>(I)) {
7500 for (auto *U : Phi->users())
7501 WorkList.push_back(cast<Instruction>(U));
7502 continue;
7503 }
7504
7505 switch (I->getOpcode()) {
7506 case Instruction::And: {
7507 auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
7508 if (!AndC)
7509 return false;
7510 APInt AndBits = AndC->getValue();
7511 DemandBits |= AndBits;
7512 // Keep track of the widest and mask we see.
7513 if (AndBits.ugt(WidestAndBits))
7514 WidestAndBits = AndBits;
7515 if (AndBits == WidestAndBits && I->getOperand(0) == Load)
7516 AndsToMaybeRemove.push_back(I);
7517 break;
7518 }
7519
7520 case Instruction::Shl: {
7521 auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
7522 if (!ShlC)
7523 return false;
7524 uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
7525 DemandBits.setLowBits(BitWidth - ShiftAmt);
7526 DropFlags.push_back(I);
7527 break;
7528 }
7529
7530 case Instruction::Trunc: {
7531 EVT TruncVT = TLI->getValueType(*DL, I->getType());
7532 unsigned TruncBitWidth = TruncVT.getSizeInBits();
7533 DemandBits.setLowBits(TruncBitWidth);
7534 DropFlags.push_back(I);
7535 break;
7536 }
7537
7538 default:
7539 return false;
7540 }
7541 }
7542
7543 uint32_t ActiveBits = DemandBits.getActiveBits();
7544 // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
7545 // target even if isLoadLegal says an i1 EXTLOAD is valid. For example,
7546 // for the AArch64 target isLoadLegal(i32, i1, ..., ZEXTLOAD, false) returns
7547 // true, but (and (load x) 1) is not matched as a single instruction, rather
7548 // as a LDR followed by an AND.
7549 // TODO: Look into removing this restriction by fixing backends to either
7550 // return false for isLoadLegal for i1 or have them select this pattern to
7551 // a single instruction.
7552 //
7553 // Also avoid hoisting if we didn't see any ands with the exact DemandBits
7554 // mask, since these are the only ands that will be removed by isel.
7555 if (ActiveBits <= 1 || !DemandBits.isMask(ActiveBits) ||
7556 WidestAndBits != DemandBits)
7557 return false;
7558
7559 LLVMContext &Ctx = Load->getType()->getContext();
7560 Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
7561 EVT TruncVT = TLI->getValueType(*DL, TruncTy);
7562
7563 // Reject cases that won't be matched as extloads.
7564 if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
7565 !TLI->isLoadLegal(LoadResultVT, TruncVT, Load->getAlign(),
7566 Load->getPointerAddressSpace(), ISD::ZEXTLOAD, false))
7567 return false;
7568
7569 IRBuilder<> Builder(Load->getNextNode());
7570 auto *NewAnd = cast<Instruction>(
7571 Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
7572 // Mark this instruction as "inserted by CGP", so that other
7573 // optimizations don't touch it.
7574 InsertedInsts.insert(NewAnd);
7575
7576 // Replace all uses of load with new and (except for the use of load in the
7577 // new and itself).
7578 replaceAllUsesWith(Load, NewAnd, FreshBBs, IsHugeFunc);
7579 NewAnd->setOperand(0, Load);
7580
7581 // Remove any and instructions that are now redundant.
7582 for (auto *And : AndsToMaybeRemove)
7583 // Check that the and mask is the same as the one we decided to put on the
7584 // new and.
7585 if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
7586 replaceAllUsesWith(And, NewAnd, FreshBBs, IsHugeFunc);
7587 if (&*CurInstIterator == And)
7588 CurInstIterator = std::next(And->getIterator());
7589 And->eraseFromParent();
7590 ++NumAndUses;
7591 }
7592
7593 // NSW flags may not longer hold.
7594 for (auto *Inst : DropFlags)
7595 Inst->setHasNoSignedWrap(false);
7596
7597 ++NumAndsAdded;
7598 return true;
7599}
7600
7601/// Check if V (an operand of a select instruction) is an expensive instruction
7602/// that is only used once.
7604 auto *I = dyn_cast<Instruction>(V);
7605 // If it's safe to speculatively execute, then it should not have side
7606 // effects; therefore, it's safe to sink and possibly *not* execute.
7607 return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
7608 TTI->isExpensiveToSpeculativelyExecute(I);
7609}
7610
7611/// Returns true if a SelectInst should be turned into an explicit branch.
7613 const TargetLowering *TLI,
7614 SelectInst *SI) {
7615 // If even a predictable select is cheap, then a branch can't be cheaper.
7616 if (!TLI->isPredictableSelectExpensive())
7617 return false;
7618
7619 // FIXME: This should use the same heuristics as IfConversion to determine
7620 // whether a select is better represented as a branch.
7621
7622 // If metadata tells us that the select condition is obviously predictable,
7623 // then we want to replace the select with a branch.
7624 uint64_t TrueWeight, FalseWeight;
7625 if (extractBranchWeights(*SI, TrueWeight, FalseWeight)) {
7626 uint64_t Max = std::max(TrueWeight, FalseWeight);
7627 uint64_t Sum = TrueWeight + FalseWeight;
7628 if (Sum != 0) {
7629 auto Probability = BranchProbability::getBranchProbability(Max, Sum);
7630 if (Probability > TTI->getPredictableBranchThreshold())
7631 return true;
7632 }
7633 }
7634
7635 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
7636
7637 // If a branch is predictable, an out-of-order CPU can avoid blocking on its
7638 // comparison condition. If the compare has more than one use, there's
7639 // probably another cmov or setcc around, so it's not worth emitting a branch.
7640 if (!Cmp || !Cmp->hasOneUse())
7641 return false;
7642
7643 // If either operand of the select is expensive and only needed on one side
7644 // of the select, we should form a branch.
7645 if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
7646 sinkSelectOperand(TTI, SI->getFalseValue()))
7647 return true;
7648
7649 return false;
7650}
7651
7652/// If \p isTrue is true, return the true value of \p SI, otherwise return
7653/// false value of \p SI. If the true/false value of \p SI is defined by any
7654/// select instructions in \p Selects, look through the defining select
7655/// instruction until the true/false value is not defined in \p Selects.
7656static Value *
7658 const SmallPtrSet<const Instruction *, 2> &Selects) {
7659 Value *V = nullptr;
7660
7661 for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI);
7662 DefSI = dyn_cast<SelectInst>(V)) {
7663 assert(DefSI->getCondition() == SI->getCondition() &&
7664 "The condition of DefSI does not match with SI");
7665 V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
7666 }
7667
7668 assert(V && "Failed to get select true/false value");
7669 return V;
7670}
7671
7672bool CodeGenPrepare::optimizeShiftInst(BinaryOperator *Shift) {
7673 assert(Shift->isShift() && "Expected a shift");
7674
7675 // If this is (1) a vector shift, (2) shifts by scalars are cheaper than
7676 // general vector shifts, and (3) the shift amount is a select-of-splatted
7677 // values, hoist the shifts before the select:
7678 // shift Op0, (select Cond, TVal, FVal) -->
7679 // select Cond, (shift Op0, TVal), (shift Op0, FVal)
7680 //
7681 // This is inverting a generic IR transform when we know that the cost of a
7682 // general vector shift is more than the cost of 2 shift-by-scalars.
7683 // We can't do this effectively in SDAG because we may not be able to
7684 // determine if the select operands are splats from within a basic block.
7685 Type *Ty = Shift->getType();
7686 if (!Ty->isVectorTy() || !TTI->isVectorShiftByScalarCheap(Ty))
7687 return false;
7688 Value *Cond, *TVal, *FVal;
7689 if (!match(Shift->getOperand(1),
7690 m_OneUse(m_Select(m_Value(Cond), m_Value(TVal), m_Value(FVal)))))
7691 return false;
7692 if (!isSplatValue(TVal) || !isSplatValue(FVal))
7693 return false;
7694
7695 IRBuilder<> Builder(Shift);
7696 BinaryOperator::BinaryOps Opcode = Shift->getOpcode();
7697 Value *NewTVal = Builder.CreateBinOp(Opcode, Shift->getOperand(0), TVal);
7698 Value *NewFVal = Builder.CreateBinOp(Opcode, Shift->getOperand(0), FVal);
7699 Value *NewSel = Builder.CreateSelect(Cond, NewTVal, NewFVal);
7700 replaceAllUsesWith(Shift, NewSel, FreshBBs, IsHugeFunc);
7701 Shift->eraseFromParent();
7702 return true;
7703}
7704
7705bool CodeGenPrepare::optimizeFunnelShift(IntrinsicInst *Fsh) {
7706 Intrinsic::ID Opcode = Fsh->getIntrinsicID();
7707 assert((Opcode == Intrinsic::fshl || Opcode == Intrinsic::fshr) &&
7708 "Expected a funnel shift");
7709
7710 // If this is (1) a vector funnel shift, (2) shifts by scalars are cheaper
7711 // than general vector shifts, and (3) the shift amount is select-of-splatted
7712 // values, hoist the funnel shifts before the select:
7713 // fsh Op0, Op1, (select Cond, TVal, FVal) -->
7714 // select Cond, (fsh Op0, Op1, TVal), (fsh Op0, Op1, FVal)
7715 //
7716 // This is inverting a generic IR transform when we know that the cost of a
7717 // general vector shift is more than the cost of 2 shift-by-scalars.
7718 // We can't do this effectively in SDAG because we may not be able to
7719 // determine if the select operands are splats from within a basic block.
7720 Type *Ty = Fsh->getType();
7721 if (!Ty->isVectorTy() || !TTI->isVectorShiftByScalarCheap(Ty))
7722 return false;
7723 Value *Cond, *TVal, *FVal;
7724 if (!match(Fsh->getOperand(2),
7725 m_OneUse(m_Select(m_Value(Cond), m_Value(TVal), m_Value(FVal)))))
7726 return false;
7727 if (!isSplatValue(TVal) || !isSplatValue(FVal))
7728 return false;
7729
7730 IRBuilder<> Builder(Fsh);
7731 Value *X = Fsh->getOperand(0), *Y = Fsh->getOperand(1);
7732 Value *NewTVal = Builder.CreateIntrinsic(Opcode, Ty, {X, Y, TVal});
7733 Value *NewFVal = Builder.CreateIntrinsic(Opcode, Ty, {X, Y, FVal});
7734 Value *NewSel = Builder.CreateSelect(Cond, NewTVal, NewFVal);
7735 replaceAllUsesWith(Fsh, NewSel, FreshBBs, IsHugeFunc);
7736 Fsh->eraseFromParent();
7737 return true;
7738}
7739
7740/// If we have a SelectInst that will likely profit from branch prediction,
7741/// turn it into a branch.
7742bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
7744 return false;
7745
7746 // If the SelectOptimize pass is enabled, selects have already been optimized.
7748 return false;
7749
7750 // Find all consecutive select instructions that share the same condition.
7752 ASI.push_back(SI);
7754 It != SI->getParent()->end(); ++It) {
7755 SelectInst *I = dyn_cast<SelectInst>(&*It);
7756 if (I && SI->getCondition() == I->getCondition()) {
7757 ASI.push_back(I);
7758 } else {
7759 break;
7760 }
7761 }
7762
7763 SelectInst *LastSI = ASI.back();
7764 // Increment the current iterator to skip all the rest of select instructions
7765 // because they will be either "not lowered" or "all lowered" to branch.
7766 CurInstIterator = std::next(LastSI->getIterator());
7767 // Examine debug-info attached to the consecutive select instructions. They
7768 // won't be individually optimised by optimizeInst, so we need to perform
7769 // DbgVariableRecord maintenence here instead.
7770 for (SelectInst *SI : ArrayRef(ASI).drop_front())
7771 fixupDbgVariableRecordsOnInst(*SI);
7772
7773 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
7774
7775 // Can we convert the 'select' to CF ?
7776 if (VectorCond || SI->getMetadata(LLVMContext::MD_unpredictable))
7777 return false;
7778
7779 TargetLowering::SelectSupportKind SelectKind;
7780 if (SI->getType()->isVectorTy())
7781 SelectKind = TargetLowering::ScalarCondVectorVal;
7782 else
7783 SelectKind = TargetLowering::ScalarValSelect;
7784
7785 if (TLI->isSelectSupported(SelectKind) &&
7787 llvm::shouldOptimizeForSize(SI->getParent(), PSI, BFI)))
7788 return false;
7789
7790 // Transform a sequence like this:
7791 // start:
7792 // %cmp = cmp uge i32 %a, %b
7793 // %sel = select i1 %cmp, i32 %c, i32 %d
7794 //
7795 // Into:
7796 // start:
7797 // %cmp = cmp uge i32 %a, %b
7798 // %cmp.frozen = freeze %cmp
7799 // br i1 %cmp.frozen, label %select.true, label %select.false
7800 // select.true:
7801 // br label %select.end
7802 // select.false:
7803 // br label %select.end
7804 // select.end:
7805 // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
7806 //
7807 // %cmp should be frozen, otherwise it may introduce undefined behavior.
7808 // In addition, we may sink instructions that produce %c or %d from
7809 // the entry block into the destination(s) of the new branch.
7810 // If the true or false blocks do not contain a sunken instruction, that
7811 // block and its branch may be optimized away. In that case, one side of the
7812 // first branch will point directly to select.end, and the corresponding PHI
7813 // predecessor block will be the start block.
7814 // The CFG is altered here and we update the DominatorTree and the LoopInfo,
7815 // but we don't set a ModifiedDT flag to avoid restarting the function walk in
7816 // runOnFunction for each select optimized.
7817
7818 // Collect values that go on the true side and the values that go on the false
7819 // side.
7820 SmallVector<Instruction *> TrueInstrs, FalseInstrs;
7821 for (SelectInst *SI : ASI) {
7822 if (Value *V = SI->getTrueValue(); sinkSelectOperand(TTI, V))
7823 TrueInstrs.push_back(cast<Instruction>(V));
7824 if (Value *V = SI->getFalseValue(); sinkSelectOperand(TTI, V))
7825 FalseInstrs.push_back(cast<Instruction>(V));
7826 }
7827
7828 // Split the select block, according to how many (if any) values go on each
7829 // side.
7830 BasicBlock *StartBlock = SI->getParent();
7831 BasicBlock::iterator SplitPt = std::next(BasicBlock::iterator(LastSI));
7832 // We should split before any debug-info.
7833 SplitPt.setHeadBit(true);
7834
7835 IRBuilder<> IB(SI);
7836 auto *CondFr = IB.CreateFreeze(SI->getCondition(), SI->getName() + ".frozen");
7837
7838 BasicBlock *TrueBlock = nullptr;
7839 BasicBlock *FalseBlock = nullptr;
7840 BasicBlock *EndBlock = nullptr;
7841 UncondBrInst *TrueBranch = nullptr;
7842 UncondBrInst *FalseBranch = nullptr;
7843 if (TrueInstrs.size() == 0) {
7844 FalseBranch = cast<UncondBrInst>(
7845 SplitBlockAndInsertIfElse(CondFr, SplitPt, false, nullptr, DTU, LI));
7846 FalseBlock = FalseBranch->getParent();
7847 EndBlock = cast<BasicBlock>(FalseBranch->getOperand(0));
7848 } else if (FalseInstrs.size() == 0) {
7849 TrueBranch = cast<UncondBrInst>(
7850 SplitBlockAndInsertIfThen(CondFr, SplitPt, false, nullptr, DTU, LI));
7851 TrueBlock = TrueBranch->getParent();
7852 EndBlock = TrueBranch->getSuccessor();
7853 } else {
7854 Instruction *ThenTerm = nullptr;
7855 Instruction *ElseTerm = nullptr;
7856 SplitBlockAndInsertIfThenElse(CondFr, SplitPt, &ThenTerm, &ElseTerm,
7857 nullptr, DTU, LI);
7858 TrueBranch = cast<UncondBrInst>(ThenTerm);
7859 FalseBranch = cast<UncondBrInst>(ElseTerm);
7860 TrueBlock = TrueBranch->getParent();
7861 FalseBlock = FalseBranch->getParent();
7862 EndBlock = TrueBranch->getSuccessor();
7863 }
7864
7865 EndBlock->setName("select.end");
7866 if (TrueBlock)
7867 TrueBlock->setName("select.true.sink");
7868 if (FalseBlock)
7869 FalseBlock->setName(FalseInstrs.size() == 0 ? "select.false"
7870 : "select.false.sink");
7871
7872 if (IsHugeFunc) {
7873 if (TrueBlock)
7874 FreshBBs.insert(TrueBlock);
7875 if (FalseBlock)
7876 FreshBBs.insert(FalseBlock);
7877 FreshBBs.insert(EndBlock);
7878 }
7879
7880 BFI->setBlockFreq(EndBlock, BFI->getBlockFreq(StartBlock));
7881
7882 static const unsigned MD[] = {
7883 LLVMContext::MD_prof, LLVMContext::MD_unpredictable,
7884 LLVMContext::MD_make_implicit, LLVMContext::MD_dbg};
7885 StartBlock->getTerminator()->copyMetadata(*SI, MD);
7886
7887 // Sink expensive instructions into the conditional blocks to avoid executing
7888 // them speculatively.
7889 for (Instruction *I : TrueInstrs)
7890 I->moveBefore(TrueBranch->getIterator());
7891 for (Instruction *I : FalseInstrs)
7892 I->moveBefore(FalseBranch->getIterator());
7893
7894 // If we did not create a new block for one of the 'true' or 'false' paths
7895 // of the condition, it means that side of the branch goes to the end block
7896 // directly and the path originates from the start block from the point of
7897 // view of the new PHI.
7898 if (TrueBlock == nullptr)
7899 TrueBlock = StartBlock;
7900 else if (FalseBlock == nullptr)
7901 FalseBlock = StartBlock;
7902
7903 SmallPtrSet<const Instruction *, 2> INS(llvm::from_range, ASI);
7904 // Use reverse iterator because later select may use the value of the
7905 // earlier select, and we need to propagate value through earlier select
7906 // to get the PHI operand.
7907 for (SelectInst *SI : llvm::reverse(ASI)) {
7908 // The select itself is replaced with a PHI Node.
7909 PHINode *PN = PHINode::Create(SI->getType(), 2, "");
7910 PN->insertBefore(EndBlock->begin());
7911 PN->takeName(SI);
7912 PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock);
7913 PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock);
7914 PN->setDebugLoc(SI->getDebugLoc());
7915
7916 replaceAllUsesWith(SI, PN, FreshBBs, IsHugeFunc);
7917 SI->eraseFromParent();
7918 INS.erase(SI);
7919 ++NumSelectsExpanded;
7920 }
7921
7922 // Instruct OptimizeBlock to skip to the next block.
7923 CurInstIterator = StartBlock->end();
7924 return true;
7925}
7926
7927/// Some targets only accept certain types for splat inputs. For example a VDUP
7928/// in MVE takes a GPR (integer) register, and the instruction that incorporate
7929/// a VDUP (such as a VADD qd, qm, rm) also require a gpr register.
7930bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
7931 // Accept shuf(insertelem(undef/poison, val, 0), undef/poison, <0,0,..>) only
7933 m_Undef(), m_ZeroMask())))
7934 return false;
7935 Type *NewType = TLI->shouldConvertSplatType(SVI);
7936 if (!NewType)
7937 return false;
7938
7939 auto *SVIVecType = cast<FixedVectorType>(SVI->getType());
7940 assert(!NewType->isVectorTy() && "Expected a scalar type!");
7941 assert(NewType->getScalarSizeInBits() == SVIVecType->getScalarSizeInBits() &&
7942 "Expected a type of the same size!");
7943 auto *NewVecType =
7944 FixedVectorType::get(NewType, SVIVecType->getNumElements());
7945
7946 // Create a bitcast (shuffle (insert (bitcast(..))))
7947 IRBuilder<> Builder(SVI);
7948 Value *BC1 = Builder.CreateBitCast(
7949 cast<Instruction>(SVI->getOperand(0))->getOperand(1), NewType);
7950 Value *Shuffle = Builder.CreateVectorSplat(NewVecType->getNumElements(), BC1);
7951 Value *BC2 = Builder.CreateBitCast(Shuffle, SVIVecType);
7952
7953 replaceAllUsesWith(SVI, BC2, FreshBBs, IsHugeFunc);
7955 SVI, TLInfo, nullptr,
7956 [&](Value *V) { removeAllAssertingVHReferences(V); });
7957
7958 // Also hoist the bitcast up to its operand if it they are not in the same
7959 // block.
7960 if (auto *BCI = dyn_cast<Instruction>(BC1))
7961 if (auto *Op = dyn_cast<Instruction>(BCI->getOperand(0)))
7962 if (BCI->getParent() != Op->getParent() && !isa<PHINode>(Op) &&
7963 !Op->isTerminator() && !Op->isEHPad())
7964 BCI->moveAfter(Op);
7965
7966 return true;
7967}
7968
7969bool CodeGenPrepare::tryToSinkFreeOperands(Instruction *I) {
7970 // If the operands of I can be folded into a target instruction together with
7971 // I, duplicate and sink them.
7972 SmallVector<Use *, 4> OpsToSink;
7973 if (!TTI->isProfitableToSinkOperands(I, OpsToSink))
7974 return false;
7975
7976 // OpsToSink can contain multiple uses in a use chain (e.g.
7977 // (%u1 with %u1 = shufflevector), (%u2 with %u2 = zext %u1)). The dominating
7978 // uses must come first, so we process the ops in reverse order so as to not
7979 // create invalid IR.
7980 BasicBlock *TargetBB = I->getParent();
7981 bool Changed = false;
7982 SmallVector<Use *, 4> ToReplace;
7983 Instruction *InsertPoint = I;
7984 for (Use *U : reverse(OpsToSink)) {
7985 auto *UI = cast<Instruction>(U->get());
7986 if (isa<PHINode>(UI) || UI->mayHaveSideEffects() || UI->mayReadFromMemory())
7987 continue;
7988 if (UI->getParent() == TargetBB) {
7989 if (UI->comesBefore(InsertPoint))
7990 InsertPoint = UI;
7991 continue;
7992 }
7993 ToReplace.push_back(U);
7994 }
7995
7996 SetVector<Instruction *> MaybeDead;
7997 DenseMap<Instruction *, Instruction *> NewInstructions;
7998 for (Use *U : ToReplace) {
7999 auto *UI = cast<Instruction>(U->get());
8000 Instruction *NI = UI->clone();
8001
8002 if (IsHugeFunc) {
8003 // Now we clone an instruction, its operands' defs may sink to this BB
8004 // now. So we put the operands defs' BBs into FreshBBs to do optimization.
8005 for (Value *Op : NI->operands())
8006 if (auto *OpDef = dyn_cast<Instruction>(Op))
8007 FreshBBs.insert(OpDef->getParent());
8008 }
8009
8010 NewInstructions[UI] = NI;
8011 MaybeDead.insert(UI);
8012 LLVM_DEBUG(dbgs() << "Sinking " << *UI << " to user " << *I << "\n");
8013 NI->insertBefore(InsertPoint->getIterator());
8014 InsertPoint = NI;
8015 InsertedInsts.insert(NI);
8016
8017 // Update the use for the new instruction, making sure that we update the
8018 // sunk instruction uses, if it is part of a chain that has already been
8019 // sunk.
8020 Instruction *OldI = cast<Instruction>(U->getUser());
8021 if (auto It = NewInstructions.find(OldI); It != NewInstructions.end())
8022 It->second->setOperand(U->getOperandNo(), NI);
8023 else
8024 U->set(NI);
8025 Changed = true;
8026 }
8027
8028 // Remove instructions that are dead after sinking.
8029 for (auto *I : MaybeDead) {
8030 if (!I->hasNUsesOrMore(1)) {
8031 LLVM_DEBUG(dbgs() << "Removing dead instruction: " << *I << "\n");
8032 I->eraseFromParent();
8033 }
8034 }
8035
8036 return Changed;
8037}
8038
8039bool CodeGenPrepare::optimizeSwitchType(SwitchInst *SI) {
8040 Value *Cond = SI->getCondition();
8041 Type *OldType = Cond->getType();
8042 LLVMContext &Context = Cond->getContext();
8043 EVT OldVT = TLI->getValueType(*DL, OldType);
8045 unsigned RegWidth = RegType.getSizeInBits();
8046
8047 if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
8048 return false;
8049
8050 // If the register width is greater than the type width, expand the condition
8051 // of the switch instruction and each case constant to the width of the
8052 // register. By widening the type of the switch condition, subsequent
8053 // comparisons (for case comparisons) will not need to be extended to the
8054 // preferred register width, so we will potentially eliminate N-1 extends,
8055 // where N is the number of cases in the switch.
8056 auto *NewType = Type::getIntNTy(Context, RegWidth);
8057
8058 // Extend the switch condition and case constants using the target preferred
8059 // extend unless the switch condition is a function argument with an extend
8060 // attribute. In that case, we can avoid an unnecessary mask/extension by
8061 // matching the argument extension instead.
8062 Instruction::CastOps ExtType = Instruction::ZExt;
8063 // Some targets prefer SExt over ZExt.
8064 if (TLI->isSExtCheaperThanZExt(OldVT, RegType))
8065 ExtType = Instruction::SExt;
8066
8067 if (auto *Arg = dyn_cast<Argument>(Cond)) {
8068 if (Arg->hasSExtAttr())
8069 ExtType = Instruction::SExt;
8070 if (Arg->hasZExtAttr())
8071 ExtType = Instruction::ZExt;
8072 }
8073
8074 auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
8075 ExtInst->insertBefore(SI->getIterator());
8076 ExtInst->setDebugLoc(SI->getDebugLoc());
8077 SI->setCondition(ExtInst);
8078 for (auto Case : SI->cases()) {
8079 const APInt &NarrowConst = Case.getCaseValue()->getValue();
8080 APInt WideConst = (ExtType == Instruction::ZExt)
8081 ? NarrowConst.zext(RegWidth)
8082 : NarrowConst.sext(RegWidth);
8083 Case.setValue(ConstantInt::get(Context, WideConst));
8084 }
8085
8086 return true;
8087}
8088
8089bool CodeGenPrepare::optimizeSwitchPhiConstants(SwitchInst *SI) {
8090 // The SCCP optimization tends to produce code like this:
8091 // switch(x) { case 42: phi(42, ...) }
8092 // Materializing the constant for the phi-argument needs instructions; So we
8093 // change the code to:
8094 // switch(x) { case 42: phi(x, ...) }
8095
8096 Value *Condition = SI->getCondition();
8097 // Avoid endless loop in degenerate case.
8098 if (isa<ConstantInt>(*Condition))
8099 return false;
8100
8101 bool Changed = false;
8102 BasicBlock *SwitchBB = SI->getParent();
8103 Type *ConditionType = Condition->getType();
8104
8105 for (const SwitchInst::CaseHandle &Case : SI->cases()) {
8106 ConstantInt *CaseValue = Case.getCaseValue();
8107 BasicBlock *CaseBB = Case.getCaseSuccessor();
8108 // Set to true if we previously checked that `CaseBB` is only reached by
8109 // a single case from this switch.
8110 bool CheckedForSinglePred = false;
8111 for (PHINode &PHI : CaseBB->phis()) {
8112 Type *PHIType = PHI.getType();
8113 // If ZExt is free then we can also catch patterns like this:
8114 // switch((i32)x) { case 42: phi((i64)42, ...); }
8115 // and replace `(i64)42` with `zext i32 %x to i64`.
8116 bool TryZExt =
8117 PHIType->isIntegerTy() &&
8118 PHIType->getIntegerBitWidth() > ConditionType->getIntegerBitWidth() &&
8119 TLI->isZExtFree(ConditionType, PHIType);
8120 if (PHIType == ConditionType || TryZExt) {
8121 // Set to true to skip this case because of multiple preds.
8122 bool SkipCase = false;
8123 Value *Replacement = nullptr;
8124 for (unsigned I = 0, E = PHI.getNumIncomingValues(); I != E; I++) {
8125 Value *PHIValue = PHI.getIncomingValue(I);
8126 if (PHIValue != CaseValue) {
8127 if (!TryZExt)
8128 continue;
8129 ConstantInt *PHIValueInt = dyn_cast<ConstantInt>(PHIValue);
8130 if (!PHIValueInt ||
8131 PHIValueInt->getValue() !=
8132 CaseValue->getValue().zext(PHIType->getIntegerBitWidth()))
8133 continue;
8134 }
8135 if (PHI.getIncomingBlock(I) != SwitchBB)
8136 continue;
8137 // We cannot optimize if there are multiple case labels jumping to
8138 // this block. This check may get expensive when there are many
8139 // case labels so we test for it last.
8140 if (!CheckedForSinglePred) {
8141 CheckedForSinglePred = true;
8142 if (SI->findCaseDest(CaseBB) == nullptr) {
8143 SkipCase = true;
8144 break;
8145 }
8146 }
8147
8148 if (Replacement == nullptr) {
8149 if (PHIValue == CaseValue) {
8150 Replacement = Condition;
8151 } else {
8152 IRBuilder<> Builder(SI);
8153 Replacement = Builder.CreateZExt(Condition, PHIType);
8154 }
8155 }
8156 PHI.setIncomingValue(I, Replacement);
8157 Changed = true;
8158 }
8159 if (SkipCase)
8160 break;
8161 }
8162 }
8163 }
8164 return Changed;
8165}
8166
8167bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
8168 bool Changed = optimizeSwitchType(SI);
8169 Changed |= optimizeSwitchPhiConstants(SI);
8170 return Changed;
8171}
8172
8173namespace {
8174
8175/// Helper class to promote a scalar operation to a vector one.
8176/// This class is used to move downward extractelement transition.
8177/// E.g.,
8178/// a = vector_op <2 x i32>
8179/// b = extractelement <2 x i32> a, i32 0
8180/// c = scalar_op b
8181/// store c
8182///
8183/// =>
8184/// a = vector_op <2 x i32>
8185/// c = vector_op a (equivalent to scalar_op on the related lane)
8186/// * d = extractelement <2 x i32> c, i32 0
8187/// * store d
8188/// Assuming both extractelement and store can be combine, we get rid of the
8189/// transition.
8190class VectorPromoteHelper {
8191 /// DataLayout associated with the current module.
8192 const DataLayout &DL;
8193
8194 /// Used to perform some checks on the legality of vector operations.
8195 const TargetLowering &TLI;
8196
8197 /// Used to estimated the cost of the promoted chain.
8198 const TargetTransformInfo &TTI;
8199
8200 /// The transition being moved downwards.
8201 Instruction *Transition;
8202
8203 /// The sequence of instructions to be promoted.
8204 SmallVector<Instruction *, 4> InstsToBePromoted;
8205
8206 /// Cost of combining a store and an extract.
8207 unsigned StoreExtractCombineCost;
8208
8209 /// Instruction that will be combined with the transition.
8210 Instruction *CombineInst = nullptr;
8211
8212 /// The instruction that represents the current end of the transition.
8213 /// Since we are faking the promotion until we reach the end of the chain
8214 /// of computation, we need a way to get the current end of the transition.
8215 Instruction *getEndOfTransition() const {
8216 if (InstsToBePromoted.empty())
8217 return Transition;
8218 return InstsToBePromoted.back();
8219 }
8220
8221 /// Return the index of the original value in the transition.
8222 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
8223 /// c, is at index 0.
8224 unsigned getTransitionOriginalValueIdx() const {
8225 assert(isa<ExtractElementInst>(Transition) &&
8226 "Other kind of transitions are not supported yet");
8227 return 0;
8228 }
8229
8230 /// Return the index of the index in the transition.
8231 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
8232 /// is at index 1.
8233 unsigned getTransitionIdx() const {
8234 assert(isa<ExtractElementInst>(Transition) &&
8235 "Other kind of transitions are not supported yet");
8236 return 1;
8237 }
8238
8239 /// Get the type of the transition.
8240 /// This is the type of the original value.
8241 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
8242 /// transition is <2 x i32>.
8243 Type *getTransitionType() const {
8244 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
8245 }
8246
8247 /// Promote \p ToBePromoted by moving \p Def downward through.
8248 /// I.e., we have the following sequence:
8249 /// Def = Transition <ty1> a to <ty2>
8250 /// b = ToBePromoted <ty2> Def, ...
8251 /// =>
8252 /// b = ToBePromoted <ty1> a, ...
8253 /// Def = Transition <ty1> ToBePromoted to <ty2>
8254 void promoteImpl(Instruction *ToBePromoted);
8255
8256 /// Check whether or not it is profitable to promote all the
8257 /// instructions enqueued to be promoted.
8258 bool isProfitableToPromote() {
8259 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
8260 unsigned Index = isa<ConstantInt>(ValIdx)
8261 ? cast<ConstantInt>(ValIdx)->getZExtValue()
8262 : -1;
8263 Type *PromotedType = getTransitionType();
8264
8265 StoreInst *ST = cast<StoreInst>(CombineInst);
8266 unsigned AS = ST->getPointerAddressSpace();
8267 // Check if this store is supported.
8269 TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
8270 ST->getAlign())) {
8271 // If this is not supported, there is no way we can combine
8272 // the extract with the store.
8273 return false;
8274 }
8275
8276 // The scalar chain of computation has to pay for the transition
8277 // scalar to vector.
8278 // The vector chain has to account for the combining cost.
8281 InstructionCost ScalarCost =
8282 TTI.getVectorInstrCost(*Transition, PromotedType, CostKind, Index);
8283 InstructionCost VectorCost = StoreExtractCombineCost;
8284 for (const auto &Inst : InstsToBePromoted) {
8285 // Compute the cost.
8286 // By construction, all instructions being promoted are arithmetic ones.
8287 // Moreover, one argument is a constant that can be viewed as a splat
8288 // constant.
8289 Value *Arg0 = Inst->getOperand(0);
8290 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
8291 isa<ConstantFP>(Arg0);
8292 TargetTransformInfo::OperandValueInfo Arg0Info, Arg1Info;
8293 if (IsArg0Constant)
8295 else
8297
8298 ScalarCost += TTI.getArithmeticInstrCost(
8299 Inst->getOpcode(), Inst->getType(), CostKind, Arg0Info, Arg1Info);
8300 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
8301 CostKind, Arg0Info, Arg1Info);
8302 }
8303 LLVM_DEBUG(
8304 dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
8305 << ScalarCost << "\nVector: " << VectorCost << '\n');
8306 return ScalarCost > VectorCost;
8307 }
8308
8309 /// Generate a constant vector with \p Val with the same
8310 /// number of elements as the transition.
8311 /// \p UseSplat defines whether or not \p Val should be replicated
8312 /// across the whole vector.
8313 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
8314 /// otherwise we generate a vector with as many poison as possible:
8315 /// <poison, ..., poison, Val, poison, ..., poison> where \p Val is only
8316 /// used at the index of the extract.
8317 Value *getConstantVector(Constant *Val, bool UseSplat) const {
8318 unsigned ExtractIdx = std::numeric_limits<unsigned>::max();
8319 if (!UseSplat) {
8320 // If we cannot determine where the constant must be, we have to
8321 // use a splat constant.
8322 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
8323 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
8324 ExtractIdx = CstVal->getSExtValue();
8325 else
8326 UseSplat = true;
8327 }
8328
8329 ElementCount EC = cast<VectorType>(getTransitionType())->getElementCount();
8330 if (UseSplat)
8331 return ConstantVector::getSplat(EC, Val);
8332
8333 if (!EC.isScalable()) {
8334 SmallVector<Constant *, 4> ConstVec;
8335 PoisonValue *PoisonVal = PoisonValue::get(Val->getType());
8336 for (unsigned Idx = 0; Idx != EC.getKnownMinValue(); ++Idx) {
8337 if (Idx == ExtractIdx)
8338 ConstVec.push_back(Val);
8339 else
8340 ConstVec.push_back(PoisonVal);
8341 }
8342 return ConstantVector::get(ConstVec);
8343 } else
8345 "Generate scalable vector for non-splat is unimplemented");
8346 }
8347
8348 /// Check if promoting to a vector type an operand at \p OperandIdx
8349 /// in \p Use can trigger undefined behavior.
8350 static bool canCauseUndefinedBehavior(const Instruction *Use,
8351 unsigned OperandIdx) {
8352 // This is not safe to introduce undef when the operand is on
8353 // the right hand side of a division-like instruction.
8354 if (OperandIdx != 1)
8355 return false;
8356 switch (Use->getOpcode()) {
8357 default:
8358 return false;
8359 case Instruction::SDiv:
8360 case Instruction::UDiv:
8361 case Instruction::SRem:
8362 case Instruction::URem:
8363 return true;
8364 case Instruction::FDiv:
8365 case Instruction::FRem:
8366 return !Use->hasNoNaNs();
8367 }
8368 llvm_unreachable(nullptr);
8369 }
8370
8371public:
8372 VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
8373 const TargetTransformInfo &TTI, Instruction *Transition,
8374 unsigned CombineCost)
8375 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
8376 StoreExtractCombineCost(CombineCost) {
8377 assert(Transition && "Do not know how to promote null");
8378 }
8379
8380 /// Check if we can promote \p ToBePromoted to \p Type.
8381 bool canPromote(const Instruction *ToBePromoted) const {
8382 // We could support CastInst too.
8383 return isa<BinaryOperator>(ToBePromoted);
8384 }
8385
8386 /// Check if it is profitable to promote \p ToBePromoted
8387 /// by moving downward the transition through.
8388 bool shouldPromote(const Instruction *ToBePromoted) const {
8390 return false;
8391 // Promote only if all the operands can be statically expanded.
8392 // Indeed, we do not want to introduce any new kind of transitions.
8393 for (const Use &U : ToBePromoted->operands()) {
8394 const Value *Val = U.get();
8395 if (Val == getEndOfTransition()) {
8396 continue;
8397 }
8398 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
8399 !isa<ConstantFP>(Val))
8400 return false;
8401 }
8402 // Check that the resulting operation is legal.
8403 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
8404 if (!ISDOpcode)
8405 return false;
8406 return StressStoreExtract ||
8408 ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
8409 }
8410
8411 /// Check whether or not \p Use can be combined
8412 /// with the transition.
8413 /// I.e., is it possible to do Use(Transition) => AnotherUse?
8414 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
8415
8416 /// Record \p ToBePromoted as part of the chain to be promoted.
8417 void enqueueForPromotion(Instruction *ToBePromoted) {
8418 InstsToBePromoted.push_back(ToBePromoted);
8419 }
8420
8421 /// Set the instruction that will be combined with the transition.
8422 void recordCombineInstruction(Instruction *ToBeCombined) {
8423 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
8424 CombineInst = ToBeCombined;
8425 }
8426
8427 /// Promote all the instructions enqueued for promotion if it is
8428 /// is profitable.
8429 /// \return True if the promotion happened, false otherwise.
8430 bool promote() {
8431 // Check if there is something to promote.
8432 // Right now, if we do not have anything to combine with,
8433 // we assume the promotion is not profitable.
8434 if (InstsToBePromoted.empty() || !CombineInst)
8435 return false;
8436
8437 // Check cost.
8438 if (!StressStoreExtract && !isProfitableToPromote())
8439 return false;
8440
8441 // Promote.
8442 for (auto &ToBePromoted : InstsToBePromoted)
8443 promoteImpl(ToBePromoted);
8444 InstsToBePromoted.clear();
8445 return true;
8446 }
8447};
8448
8449} // end anonymous namespace
8450
8451void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
8452 // At this point, we know that all the operands of ToBePromoted but Def
8453 // can be statically promoted.
8454 // For Def, we need to use its parameter in ToBePromoted:
8455 // b = ToBePromoted ty1 a
8456 // Def = Transition ty1 b to ty2
8457 // Move the transition down.
8458 // 1. Replace all uses of the promoted operation by the transition.
8459 // = ... b => = ... Def.
8460 assert(ToBePromoted->getType() == Transition->getType() &&
8461 "The type of the result of the transition does not match "
8462 "the final type");
8463 ToBePromoted->replaceAllUsesWith(Transition);
8464 // 2. Update the type of the uses.
8465 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
8466 Type *TransitionTy = getTransitionType();
8467 ToBePromoted->mutateType(TransitionTy);
8468 // 3. Update all the operands of the promoted operation with promoted
8469 // operands.
8470 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
8471 for (Use &U : ToBePromoted->operands()) {
8472 Value *Val = U.get();
8473 Value *NewVal = nullptr;
8474 if (Val == Transition)
8475 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
8476 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
8477 isa<ConstantFP>(Val)) {
8478 // Use a splat constant if it is not safe to use undef.
8479 NewVal = getConstantVector(
8480 cast<Constant>(Val),
8481 isa<UndefValue>(Val) ||
8482 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
8483 } else
8484 llvm_unreachable("Did you modified shouldPromote and forgot to update "
8485 "this?");
8486 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
8487 }
8488 Transition->moveAfter(ToBePromoted);
8489 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
8490}
8491
8492/// Some targets can do store(extractelement) with one instruction.
8493/// Try to push the extractelement towards the stores when the target
8494/// has this feature and this is profitable.
8495bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
8496 unsigned CombineCost = std::numeric_limits<unsigned>::max();
8497 if (DisableStoreExtract ||
8500 Inst->getOperand(1), CombineCost)))
8501 return false;
8502
8503 // At this point we know that Inst is a vector to scalar transition.
8504 // Try to move it down the def-use chain, until:
8505 // - We can combine the transition with its single use
8506 // => we got rid of the transition.
8507 // - We escape the current basic block
8508 // => we would need to check that we are moving it at a cheaper place and
8509 // we do not do that for now.
8510 BasicBlock *Parent = Inst->getParent();
8511 LLVM_DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
8512 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
8513 // If the transition has more than one use, assume this is not going to be
8514 // beneficial.
8515 while (Inst->hasOneUse()) {
8516 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
8517 LLVM_DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
8518
8519 if (ToBePromoted->getParent() != Parent) {
8520 LLVM_DEBUG(dbgs() << "Instruction to promote is in a different block ("
8521 << ToBePromoted->getParent()->getName()
8522 << ") than the transition (" << Parent->getName()
8523 << ").\n");
8524 return false;
8525 }
8526
8527 if (VPH.canCombine(ToBePromoted)) {
8528 LLVM_DEBUG(dbgs() << "Assume " << *Inst << '\n'
8529 << "will be combined with: " << *ToBePromoted << '\n');
8530 VPH.recordCombineInstruction(ToBePromoted);
8531 bool Changed = VPH.promote();
8532 NumStoreExtractExposed += Changed;
8533 return Changed;
8534 }
8535
8536 LLVM_DEBUG(dbgs() << "Try promoting.\n");
8537 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
8538 return false;
8539
8540 LLVM_DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
8541
8542 VPH.enqueueForPromotion(ToBePromoted);
8543 Inst = ToBePromoted;
8544 }
8545 return false;
8546}
8547
8548/// For the instruction sequence of store below, F and I values
8549/// are bundled together as an i64 value before being stored into memory.
8550/// Sometimes it is more efficient to generate separate stores for F and I,
8551/// which can remove the bitwise instructions or sink them to colder places.
8552///
8553/// (store (or (zext (bitcast F to i32) to i64),
8554/// (shl (zext I to i64), 32)), addr) -->
8555/// (store F, addr) and (store I, addr+4)
8556///
8557/// Similarly, splitting for other merged store can also be beneficial, like:
8558/// For pair of {i32, i32}, i64 store --> two i32 stores.
8559/// For pair of {i32, i16}, i64 store --> two i32 stores.
8560/// For pair of {i16, i16}, i32 store --> two i16 stores.
8561/// For pair of {i16, i8}, i32 store --> two i16 stores.
8562/// For pair of {i8, i8}, i16 store --> two i8 stores.
8563///
8564/// We allow each target to determine specifically which kind of splitting is
8565/// supported.
8566///
8567/// The store patterns are commonly seen from the simple code snippet below
8568/// if only std::make_pair(...) is sroa transformed before inlined into hoo.
8569/// void goo(const std::pair<int, float> &);
8570/// hoo() {
8571/// ...
8572/// goo(std::make_pair(tmp, ftmp));
8573/// ...
8574/// }
8575///
8576/// Although we already have similar splitting in DAG Combine, we duplicate
8577/// it in CodeGenPrepare to catch the case in which pattern is across
8578/// multiple BBs. The logic in DAG Combine is kept to catch case generated
8579/// during code expansion.
8581 const TargetLowering &TLI) {
8582 // Handle simple but common cases only.
8583 Type *StoreType = SI.getValueOperand()->getType();
8584
8585 // The code below assumes shifting a value by <number of bits>,
8586 // whereas scalable vectors would have to be shifted by
8587 // <2log(vscale) + number of bits> in order to store the
8588 // low/high parts. Bailing out for now.
8589 if (StoreType->isScalableTy())
8590 return false;
8591
8592 if (!DL.typeSizeEqualsStoreSize(StoreType) ||
8593 DL.getTypeSizeInBits(StoreType) == 0)
8594 return false;
8595
8596 unsigned HalfValBitSize = DL.getTypeSizeInBits(StoreType) / 2;
8597 Type *SplitStoreType = Type::getIntNTy(SI.getContext(), HalfValBitSize);
8598 if (!DL.typeSizeEqualsStoreSize(SplitStoreType))
8599 return false;
8600
8601 // Don't split the store if it is volatile or atomic.
8602 if (!SI.isSimple())
8603 return false;
8604
8605 // Match the following patterns:
8606 // (store (or (zext LValue to i64),
8607 // (shl (zext HValue to i64), 32)), HalfValBitSize)
8608 // or
8609 // (store (or (shl (zext HValue to i64), 32)), HalfValBitSize)
8610 // (zext LValue to i64),
8611 // Expect both operands of OR and the first operand of SHL have only
8612 // one use.
8613 Value *LValue, *HValue;
8614 if (!match(SI.getValueOperand(),
8617 m_SpecificInt(HalfValBitSize))))))
8618 return false;
8619
8620 // Check LValue and HValue are int with size less or equal than 32.
8621 if (!LValue->getType()->isIntegerTy() ||
8622 DL.getTypeSizeInBits(LValue->getType()) > HalfValBitSize ||
8623 !HValue->getType()->isIntegerTy() ||
8624 DL.getTypeSizeInBits(HValue->getType()) > HalfValBitSize)
8625 return false;
8626
8627 // If LValue/HValue is a bitcast instruction, use the EVT before bitcast
8628 // as the input of target query.
8629 auto *LBC = dyn_cast<BitCastInst>(LValue);
8630 auto *HBC = dyn_cast<BitCastInst>(HValue);
8631 EVT LowTy = LBC ? EVT::getEVT(LBC->getOperand(0)->getType())
8632 : EVT::getEVT(LValue->getType());
8633 EVT HighTy = HBC ? EVT::getEVT(HBC->getOperand(0)->getType())
8634 : EVT::getEVT(HValue->getType());
8635 if (!ForceSplitStore && !TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
8636 return false;
8637
8638 // Start to split store.
8639 IRBuilder<> Builder(&SI);
8640
8641 // If LValue/HValue is a bitcast in another BB, create a new one in current
8642 // BB so it may be merged with the splitted stores by dag combiner.
8643 if (LBC && LBC->getParent() != SI.getParent())
8644 LValue = Builder.CreateBitCast(LBC->getOperand(0), LBC->getType());
8645 if (HBC && HBC->getParent() != SI.getParent())
8646 HValue = Builder.CreateBitCast(HBC->getOperand(0), HBC->getType());
8647
8648 bool IsLE = SI.getDataLayout().isLittleEndian();
8649 auto CreateSplitStore = [&](Value *V, bool Upper) {
8650 V = Builder.CreateZExtOrBitCast(V, SplitStoreType);
8651 Value *Addr = SI.getPointerOperand();
8652 Align Alignment = SI.getAlign();
8653 const bool IsOffsetStore = (IsLE && Upper) || (!IsLE && !Upper);
8654 if (IsOffsetStore) {
8655 Addr = Builder.CreateGEP(
8656 SplitStoreType, Addr,
8657 ConstantInt::get(Type::getInt32Ty(SI.getContext()), 1));
8658
8659 // When splitting the store in half, naturally one half will retain the
8660 // alignment of the original wider store, regardless of whether it was
8661 // over-aligned or not, while the other will require adjustment.
8662 Alignment = commonAlignment(Alignment, HalfValBitSize / 8);
8663 }
8664 Builder.CreateAlignedStore(V, Addr, Alignment);
8665 };
8666
8667 CreateSplitStore(LValue, false);
8668 CreateSplitStore(HValue, true);
8669
8670 // Delete the old store.
8671 SI.eraseFromParent();
8672 return true;
8673}
8674
8675// Return true if the GEP has two operands, the first operand is of a sequential
8676// type, and the second operand is a constant.
8679 return GEP->getNumOperands() == 2 && I.isSequential() &&
8680 isa<ConstantInt>(GEP->getOperand(1));
8681}
8682
8683// Try unmerging GEPs to reduce liveness interference (register pressure) across
8684// IndirectBr edges. Since IndirectBr edges tend to touch on many blocks,
8685// reducing liveness interference across those edges benefits global register
8686// allocation. Currently handles only certain cases.
8687//
8688// For example, unmerge %GEPI and %UGEPI as below.
8689//
8690// ---------- BEFORE ----------
8691// SrcBlock:
8692// ...
8693// %GEPIOp = ...
8694// ...
8695// %GEPI = gep %GEPIOp, Idx
8696// ...
8697// indirectbr ... [ label %DstB0, label %DstB1, ... label %DstBi ... ]
8698// (* %GEPI is alive on the indirectbr edges due to other uses ahead)
8699// (* %GEPIOp is alive on the indirectbr edges only because of it's used by
8700// %UGEPI)
8701//
8702// DstB0: ... (there may be a gep similar to %UGEPI to be unmerged)
8703// DstB1: ... (there may be a gep similar to %UGEPI to be unmerged)
8704// ...
8705//
8706// DstBi:
8707// ...
8708// %UGEPI = gep %GEPIOp, UIdx
8709// ...
8710// ---------------------------
8711//
8712// ---------- AFTER ----------
8713// SrcBlock:
8714// ... (same as above)
8715// (* %GEPI is still alive on the indirectbr edges)
8716// (* %GEPIOp is no longer alive on the indirectbr edges as a result of the
8717// unmerging)
8718// ...
8719//
8720// DstBi:
8721// ...
8722// %UGEPI = gep %GEPI, (UIdx-Idx)
8723// ...
8724// ---------------------------
8725//
8726// The register pressure on the IndirectBr edges is reduced because %GEPIOp is
8727// no longer alive on them.
8728//
8729// We try to unmerge GEPs here in CodGenPrepare, as opposed to limiting merging
8730// of GEPs in the first place in InstCombiner::visitGetElementPtrInst() so as
8731// not to disable further simplications and optimizations as a result of GEP
8732// merging.
8733//
8734// Note this unmerging may increase the length of the data flow critical path
8735// (the path from %GEPIOp to %UGEPI would go through %GEPI), which is a tradeoff
8736// between the register pressure and the length of data-flow critical
8737// path. Restricting this to the uncommon IndirectBr case would minimize the
8738// impact of potentially longer critical path, if any, and the impact on compile
8739// time.
8741 const TargetTransformInfo *TTI) {
8742 BasicBlock *SrcBlock = GEPI->getParent();
8743 // Check that SrcBlock ends with an IndirectBr. If not, give up. The common
8744 // (non-IndirectBr) cases exit early here.
8745 if (!isa<IndirectBrInst>(SrcBlock->getTerminator()))
8746 return false;
8747 // Check that GEPI is a simple gep with a single constant index.
8748 if (!GEPSequentialConstIndexed(GEPI))
8749 return false;
8750 ConstantInt *GEPIIdx = cast<ConstantInt>(GEPI->getOperand(1));
8751 // Check that GEPI is a cheap one.
8752 if (TTI->getIntImmCost(GEPIIdx->getValue(), GEPIIdx->getType(),
8755 return false;
8756 Value *GEPIOp = GEPI->getOperand(0);
8757 // Check that GEPIOp is an instruction that's also defined in SrcBlock.
8758 if (!isa<Instruction>(GEPIOp))
8759 return false;
8760 auto *GEPIOpI = cast<Instruction>(GEPIOp);
8761 if (GEPIOpI->getParent() != SrcBlock)
8762 return false;
8763 // Check that GEP is used outside the block, meaning it's alive on the
8764 // IndirectBr edge(s).
8765 if (llvm::none_of(GEPI->users(), [&](User *Usr) {
8766 if (auto *I = dyn_cast<Instruction>(Usr)) {
8767 if (I->getParent() != SrcBlock) {
8768 return true;
8769 }
8770 }
8771 return false;
8772 }))
8773 return false;
8774 // The second elements of the GEP chains to be unmerged.
8775 std::vector<GetElementPtrInst *> UGEPIs;
8776 // Check each user of GEPIOp to check if unmerging would make GEPIOp not alive
8777 // on IndirectBr edges.
8778 for (User *Usr : GEPIOp->users()) {
8779 if (Usr == GEPI)
8780 continue;
8781 // Check if Usr is an Instruction. If not, give up.
8782 if (!isa<Instruction>(Usr))
8783 return false;
8784 auto *UI = cast<Instruction>(Usr);
8785 // Check if Usr in the same block as GEPIOp, which is fine, skip.
8786 if (UI->getParent() == SrcBlock)
8787 continue;
8788 // Check if Usr is a GEP. If not, give up.
8789 if (!isa<GetElementPtrInst>(Usr))
8790 return false;
8791 auto *UGEPI = cast<GetElementPtrInst>(Usr);
8792 // Check if UGEPI is a simple gep with a single constant index and GEPIOp is
8793 // the pointer operand to it. If so, record it in the vector. If not, give
8794 // up.
8795 if (!GEPSequentialConstIndexed(UGEPI))
8796 return false;
8797 if (UGEPI->getOperand(0) != GEPIOp)
8798 return false;
8799 if (UGEPI->getSourceElementType() != GEPI->getSourceElementType())
8800 return false;
8801 if (GEPIIdx->getType() !=
8802 cast<ConstantInt>(UGEPI->getOperand(1))->getType())
8803 return false;
8804 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
8805 if (TTI->getIntImmCost(UGEPIIdx->getValue(), UGEPIIdx->getType(),
8808 return false;
8809 UGEPIs.push_back(UGEPI);
8810 }
8811 if (UGEPIs.size() == 0)
8812 return false;
8813 // Check the materializing cost of (Uidx-Idx).
8814 for (GetElementPtrInst *UGEPI : UGEPIs) {
8815 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
8816 APInt NewIdx = UGEPIIdx->getValue() - GEPIIdx->getValue();
8818 NewIdx, GEPIIdx->getType(), TargetTransformInfo::TCK_SizeAndLatency);
8819 if (ImmCost > TargetTransformInfo::TCC_Basic)
8820 return false;
8821 }
8822 // Now unmerge between GEPI and UGEPIs.
8823 for (GetElementPtrInst *UGEPI : UGEPIs) {
8824 UGEPI->setOperand(0, GEPI);
8825 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
8826 auto NewIdx = UGEPIIdx->getValue() - GEPIIdx->getValue();
8827 Constant *NewUGEPIIdx = ConstantInt::get(GEPIIdx->getType(), NewIdx);
8828 UGEPI->setOperand(1, NewUGEPIIdx);
8829
8830 auto SourceFlags = GEPI->getNoWrapFlags();
8831 // Intersect flags to avoid UB in updated GEP.
8832 auto TargetFlags =
8833 UGEPI->getNoWrapFlags().intersectForOffsetAdd(SourceFlags);
8834 // If UGEPI now has a negative index, drop the nuw flag.
8835 if (NewIdx.isNegative() && TargetFlags.hasNoUnsignedWrap())
8836 TargetFlags = TargetFlags.withoutNoUnsignedWrap();
8837 UGEPI->setNoWrapFlags(TargetFlags);
8838 }
8839 // After unmerging, verify that GEPIOp is actually only used in SrcBlock (not
8840 // alive on IndirectBr edges).
8841 assert(llvm::none_of(GEPIOp->users(),
8842 [&](User *Usr) {
8843 return cast<Instruction>(Usr)->getParent() != SrcBlock;
8844 }) &&
8845 "GEPIOp is used outside SrcBlock");
8846 return true;
8847}
8848
8849static bool optimizeBranch(CondBrInst *Branch, const TargetLowering &TLI,
8851 bool IsHugeFunc) {
8852 // Try and convert
8853 // %c = icmp ult %x, 8
8854 // br %c, bla, blb
8855 // %tc = lshr %x, 3
8856 // to
8857 // %tc = lshr %x, 3
8858 // %c = icmp eq %tc, 0
8859 // br %c, bla, blb
8860 // Creating the cmp to zero can be better for the backend, especially if the
8861 // lshr produces flags that can be used automatically.
8862 if (!TLI.preferZeroCompareBranch())
8863 return false;
8864
8865 ICmpInst *Cmp = dyn_cast<ICmpInst>(Branch->getCondition());
8866 if (!Cmp || !isa<ConstantInt>(Cmp->getOperand(1)) || !Cmp->hasOneUse())
8867 return false;
8868
8869 Value *X = Cmp->getOperand(0);
8870 if (!X->hasUseList())
8871 return false;
8872
8873 APInt CmpC = cast<ConstantInt>(Cmp->getOperand(1))->getValue();
8874
8875 for (auto *U : X->users()) {
8877 // A quick dominance check
8878 if (!UI ||
8879 (UI->getParent() != Branch->getParent() &&
8880 UI->getParent() != Branch->getSuccessor(0) &&
8881 UI->getParent() != Branch->getSuccessor(1)) ||
8882 (UI->getParent() != Branch->getParent() &&
8883 !UI->getParent()->getSinglePredecessor()))
8884 continue;
8885
8886 if (CmpC.isPowerOf2() && Cmp->getPredicate() == ICmpInst::ICMP_ULT &&
8887 match(UI, m_Shr(m_Specific(X), m_SpecificInt(CmpC.logBase2())))) {
8888 IRBuilder<> Builder(Branch);
8889 if (UI->getParent() != Branch->getParent())
8890 UI->moveBefore(Branch->getIterator());
8892 Value *NewCmp = Builder.CreateCmp(ICmpInst::ICMP_EQ, UI,
8893 ConstantInt::get(UI->getType(), 0));
8894 LLVM_DEBUG(dbgs() << "Converting " << *Cmp << "\n");
8895 LLVM_DEBUG(dbgs() << " to compare on zero: " << *NewCmp << "\n");
8896 replaceAllUsesWith(Cmp, NewCmp, FreshBBs, IsHugeFunc);
8897 return true;
8898 }
8899 if (Cmp->isEquality() &&
8900 (match(UI, m_Add(m_Specific(X), m_SpecificInt(-CmpC))) ||
8901 match(UI, m_Sub(m_Specific(X), m_SpecificInt(CmpC))) ||
8902 match(UI, m_Xor(m_Specific(X), m_SpecificInt(CmpC))))) {
8903 IRBuilder<> Builder(Branch);
8904 if (UI->getParent() != Branch->getParent())
8905 UI->moveBefore(Branch->getIterator());
8907 Value *NewCmp = Builder.CreateCmp(Cmp->getPredicate(), UI,
8908 ConstantInt::get(UI->getType(), 0));
8909 LLVM_DEBUG(dbgs() << "Converting " << *Cmp << "\n");
8910 LLVM_DEBUG(dbgs() << " to compare on zero: " << *NewCmp << "\n");
8911 replaceAllUsesWith(Cmp, NewCmp, FreshBBs, IsHugeFunc);
8912 return true;
8913 }
8914 }
8915 return false;
8916}
8917
8918bool CodeGenPrepare::optimizeInst(Instruction *I, ModifyDT &ModifiedDT) {
8919 bool AnyChange = false;
8920 AnyChange = fixupDbgVariableRecordsOnInst(*I);
8921
8922 // Bail out if we inserted the instruction to prevent optimizations from
8923 // stepping on each other's toes.
8924 if (InsertedInsts.count(I))
8925 return AnyChange;
8926
8927 // TODO: Move into the switch on opcode below here.
8928 if (PHINode *P = dyn_cast<PHINode>(I)) {
8929 // It is possible for very late stage optimizations (such as SimplifyCFG)
8930 // to introduce PHI nodes too late to be cleaned up. If we detect such a
8931 // trivial PHI, go ahead and zap it here.
8932 if (Value *V = simplifyInstruction(P, {*DL, TLInfo})) {
8933 LargeOffsetGEPMap.erase(P);
8934 replaceAllUsesWith(P, V, FreshBBs, IsHugeFunc);
8935 P->eraseFromParent();
8936 ++NumPHIsElim;
8937 return true;
8938 }
8939 return AnyChange;
8940 }
8941
8942 if (CastInst *CI = dyn_cast<CastInst>(I)) {
8943 // If the source of the cast is a constant, then this should have
8944 // already been constant folded. The only reason NOT to constant fold
8945 // it is if something (e.g. LSR) was careful to place the constant
8946 // evaluation in a block other than then one that uses it (e.g. to hoist
8947 // the address of globals out of a loop). If this is the case, we don't
8948 // want to forward-subst the cast.
8949 if (auto *BCI = dyn_cast<BitCastInst>(CI)) {
8950 // Hoist bitcasts of illegal types to reduce cross-block register pressure
8951 // and prevent register splitting.
8952 if (optimizeBitCast(BCI, *TLI, *DL)) {
8953 return true;
8954 }
8955 }
8956
8957 if (isa<Constant>(CI->getOperand(0)))
8958 return AnyChange;
8959
8960 if (OptimizeNoopCopyExpression(CI, *TLI, *DL))
8961 return true;
8962
8964 isa<TruncInst>(I)) &&
8966 I, LI->getLoopFor(I->getParent()), *TTI))
8967 return true;
8968
8969 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
8970 /// Sink a zext or sext into its user blocks if the target type doesn't
8971 /// fit in one register
8972 if (TLI->getTypeAction(CI->getContext(),
8973 TLI->getValueType(*DL, CI->getType())) ==
8974 TargetLowering::TypeExpandInteger) {
8975 return SinkCast(CI);
8976 } else {
8978 I, LI->getLoopFor(I->getParent()), *TTI))
8979 return true;
8980
8981 bool MadeChange = optimizeExt(I);
8982 return MadeChange | optimizeExtUses(I);
8983 }
8984 }
8985 return AnyChange;
8986 }
8987
8988 if (auto *Cmp = dyn_cast<CmpInst>(I))
8989 if (optimizeCmp(Cmp, ModifiedDT))
8990 return true;
8991
8992 if (match(I, m_URem(m_Value(), m_Value())))
8993 if (optimizeURem(I))
8994 return true;
8995
8996 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
8997 LI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
8998 bool Modified = optimizeLoadExt(LI);
8999 unsigned AS = LI->getPointerAddressSpace();
9000 Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
9001 return Modified;
9002 }
9003
9004 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
9005 if (splitMergedValStore(*SI, *DL, *TLI))
9006 return true;
9007 SI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
9008 unsigned AS = SI->getPointerAddressSpace();
9009 return optimizeMemoryInst(I, SI->getOperand(1),
9010 SI->getOperand(0)->getType(), AS);
9011 }
9012
9013 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
9014 unsigned AS = RMW->getPointerAddressSpace();
9015 return optimizeMemoryInst(I, RMW->getPointerOperand(), RMW->getType(), AS);
9016 }
9017
9018 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(I)) {
9019 unsigned AS = CmpX->getPointerAddressSpace();
9020 return optimizeMemoryInst(I, CmpX->getPointerOperand(),
9021 CmpX->getCompareOperand()->getType(), AS);
9022 }
9023
9024 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
9025
9026 if (BinOp && BinOp->getOpcode() == Instruction::And && EnableAndCmpSinking &&
9027 sinkAndCmp0Expression(BinOp, *TLI, InsertedInsts))
9028 return true;
9029
9030 // TODO: Move this into the switch on opcode - it handles shifts already.
9031 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
9032 BinOp->getOpcode() == Instruction::LShr)) {
9033 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
9034 if (CI && TLI->hasExtractBitsInsn())
9035 if (OptimizeExtractBits(BinOp, CI, *TLI, *DL))
9036 return true;
9037 }
9038
9039 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
9040 if (GEPI->hasAllZeroIndices()) {
9041 /// The GEP operand must be a pointer, so must its result -> BitCast
9042 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
9043 GEPI->getName(), GEPI->getIterator());
9044 NC->setDebugLoc(GEPI->getDebugLoc());
9045 replaceAllUsesWith(GEPI, NC, FreshBBs, IsHugeFunc);
9047 GEPI, TLInfo, nullptr,
9048 [&](Value *V) { removeAllAssertingVHReferences(V); });
9049 ++NumGEPsElim;
9050 optimizeInst(NC, ModifiedDT);
9051 return true;
9052 }
9054 return true;
9055 }
9056 }
9057
9058 if (FreezeInst *FI = dyn_cast<FreezeInst>(I)) {
9059 // freeze(icmp a, const)) -> icmp (freeze a), const
9060 // This helps generate efficient conditional jumps.
9061 CmpInst *CmpI = dyn_cast<CmpInst>(FI->getOperand(0));
9062 if (CmpI && CmpI->hasOneUse()) {
9063 auto Op0 = CmpI->getOperand(0), Op1 = CmpI->getOperand(1);
9064 bool Const0 = isa<ConstantInt>(Op0) || isa<ConstantFP>(Op0) ||
9066 bool Const1 = isa<ConstantInt>(Op1) || isa<ConstantFP>(Op1) ||
9068 if (Const0 || Const1) {
9069 if (!Const0 || !Const1) {
9070 auto *F = new FreezeInst(Const0 ? Op1 : Op0, "", CmpI->getIterator());
9071 F->takeName(FI);
9072 CmpI->setOperand(Const0 ? 1 : 0, F);
9073 }
9075 replaceAllUsesWith(FI, CmpI, FreshBBs, IsHugeFunc);
9076 FI->eraseFromParent();
9077 return true;
9078 }
9079 }
9080 return AnyChange;
9081 }
9082
9083 if (tryToSinkFreeOperands(I))
9084 return true;
9085
9086 switch (I->getOpcode()) {
9087 case Instruction::Shl:
9088 case Instruction::LShr:
9089 case Instruction::AShr:
9090 return optimizeShiftInst(cast<BinaryOperator>(I));
9091 case Instruction::Call:
9092 return optimizeCallInst(cast<CallInst>(I), ModifiedDT);
9093 case Instruction::Select:
9094 return optimizeSelectInst(cast<SelectInst>(I));
9095 case Instruction::ShuffleVector:
9096 return optimizeShuffleVectorInst(cast<ShuffleVectorInst>(I));
9097 case Instruction::Switch:
9098 return optimizeSwitchInst(cast<SwitchInst>(I));
9099 case Instruction::ExtractElement:
9100 return optimizeExtractElementInst(cast<ExtractElementInst>(I));
9101 case Instruction::CondBr:
9102 return optimizeBranch(cast<CondBrInst>(I), *TLI, FreshBBs, IsHugeFunc);
9103 }
9104
9105 return AnyChange;
9106}
9107
9108/// Given an OR instruction, check to see if this is a bitreverse
9109/// idiom. If so, insert the new intrinsic and return true.
9110bool CodeGenPrepare::makeBitReverse(Instruction &I) {
9111 if (!I.getType()->isIntegerTy() ||
9113 TLI->getValueType(*DL, I.getType(), true)))
9114 return false;
9115
9116 SmallVector<Instruction *, 4> Insts;
9117 if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts))
9118 return false;
9119 Instruction *LastInst = Insts.back();
9120 replaceAllUsesWith(&I, LastInst, FreshBBs, IsHugeFunc);
9122 &I, TLInfo, nullptr,
9123 [&](Value *V) { removeAllAssertingVHReferences(V); });
9124 return true;
9125}
9126
9127// In this pass we look for GEP and cast instructions that are used
9128// across basic blocks and rewrite them to improve basic-block-at-a-time
9129// selection.
9130bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, ModifyDT &ModifiedDT) {
9131 SunkAddrs.clear();
9132 bool MadeChange = false;
9133
9134 do {
9135 CurInstIterator = BB.begin();
9136 ModifiedDT = ModifyDT::NotModifyDT;
9137 while (CurInstIterator != BB.end()) {
9138 MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
9139 if (ModifiedDT != ModifyDT::NotModifyDT) {
9140 // For huge function we tend to quickly go though the inner optmization
9141 // opportunities in the BB. So we go back to the BB head to re-optimize
9142 // each instruction instead of go back to the function head.
9143 if (IsHugeFunc)
9144 break;
9145 return true;
9146 }
9147 }
9148 } while (ModifiedDT == ModifyDT::ModifyInstDT);
9149
9150 bool MadeBitReverse = true;
9151 while (MadeBitReverse) {
9152 MadeBitReverse = false;
9153 for (auto &I : reverse(BB)) {
9154 if (makeBitReverse(I)) {
9155 MadeBitReverse = MadeChange = true;
9156 break;
9157 }
9158 }
9159 }
9160 MadeChange |= dupRetToEnableTailCallOpts(&BB, ModifiedDT);
9161
9162 return MadeChange;
9163}
9164
9165bool CodeGenPrepare::fixupDbgVariableRecordsOnInst(Instruction &I) {
9166 bool AnyChange = false;
9167 for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange()))
9168 AnyChange |= fixupDbgVariableRecord(DVR);
9169 return AnyChange;
9170}
9171
9172// FIXME: should updating debug-info really cause the "changed" flag to fire,
9173// which can cause a function to be reprocessed?
9174bool CodeGenPrepare::fixupDbgVariableRecord(DbgVariableRecord &DVR) {
9175 if (DVR.Type != DbgVariableRecord::LocationType::Value &&
9176 DVR.Type != DbgVariableRecord::LocationType::Assign)
9177 return false;
9178
9179 // Does this DbgVariableRecord refer to a sunk address calculation?
9180 bool AnyChange = false;
9181 SmallDenseSet<Value *> LocationOps(DVR.location_ops().begin(),
9182 DVR.location_ops().end());
9183 for (Value *Location : LocationOps) {
9184 WeakTrackingVH SunkAddrVH = SunkAddrs[Location];
9185 Value *SunkAddr = SunkAddrVH.pointsToAliveValue() ? SunkAddrVH : nullptr;
9186 if (SunkAddr) {
9187 // Point dbg.value at locally computed address, which should give the best
9188 // opportunity to be accurately lowered. This update may change the type
9189 // of pointer being referred to; however this makes no difference to
9190 // debugging information, and we can't generate bitcasts that may affect
9191 // codegen.
9192 DVR.replaceVariableLocationOp(Location, SunkAddr);
9193 AnyChange = true;
9194 }
9195 }
9196 return AnyChange;
9197}
9198
9200 DVR->removeFromParent();
9201 BasicBlock *VIBB = VI->getParent();
9202 if (isa<PHINode>(VI))
9203 VIBB->insertDbgRecordBefore(DVR, VIBB->getFirstInsertionPt());
9204 else
9205 VIBB->insertDbgRecordAfter(DVR, &*VI);
9206}
9207
9208// A llvm.dbg.value may be using a value before its definition, due to
9209// optimizations in this pass and others. Scan for such dbg.values, and rescue
9210// them by moving the dbg.value to immediately after the value definition.
9211// FIXME: Ideally this should never be necessary, and this has the potential
9212// to re-order dbg.value intrinsics.
9213bool CodeGenPrepare::placeDbgValues(Function &F) {
9214 bool MadeChange = false;
9215 DominatorTree &DT = getDT();
9216
9217 auto DbgProcessor = [&](auto *DbgItem, Instruction *Position) {
9218 SmallVector<Instruction *, 4> VIs;
9219 for (Value *V : DbgItem->location_ops())
9220 if (Instruction *VI = dyn_cast_or_null<Instruction>(V))
9221 VIs.push_back(VI);
9222
9223 // This item may depend on multiple instructions, complicating any
9224 // potential sink. This block takes the defensive approach, opting to
9225 // "undef" the item if it has more than one instruction and any of them do
9226 // not dominate iem.
9227 for (Instruction *VI : VIs) {
9228 if (VI->isTerminator())
9229 continue;
9230
9231 // If VI is a phi in a block with an EHPad terminator, we can't insert
9232 // after it.
9233 if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
9234 continue;
9235
9236 // If the defining instruction dominates the dbg.value, we do not need
9237 // to move the dbg.value.
9238 if (DT.dominates(VI, Position))
9239 continue;
9240
9241 // If we depend on multiple instructions and any of them doesn't
9242 // dominate this DVI, we probably can't salvage it: moving it to
9243 // after any of the instructions could cause us to lose the others.
9244 if (VIs.size() > 1) {
9245 LLVM_DEBUG(
9246 dbgs()
9247 << "Unable to find valid location for Debug Value, undefing:\n"
9248 << *DbgItem);
9249 DbgItem->setKillLocation();
9250 break;
9251 }
9252
9253 LLVM_DEBUG(dbgs() << "Moving Debug Value before :\n"
9254 << *DbgItem << ' ' << *VI);
9255 DbgInserterHelper(DbgItem, VI->getIterator());
9256 MadeChange = true;
9257 ++NumDbgValueMoved;
9258 }
9259 };
9260
9261 for (BasicBlock &BB : F) {
9262 for (Instruction &Insn : llvm::make_early_inc_range(BB)) {
9263 // Process any DbgVariableRecord records attached to this
9264 // instruction.
9265 for (DbgVariableRecord &DVR : llvm::make_early_inc_range(
9266 filterDbgVars(Insn.getDbgRecordRange()))) {
9267 if (DVR.Type != DbgVariableRecord::LocationType::Value)
9268 continue;
9269 DbgProcessor(&DVR, &Insn);
9270 }
9271 }
9272 }
9273
9274 return MadeChange;
9275}
9276
9277// Group scattered pseudo probes in a block to favor SelectionDAG. Scattered
9278// probes can be chained dependencies of other regular DAG nodes and block DAG
9279// combine optimizations.
9280bool CodeGenPrepare::placePseudoProbes(Function &F) {
9281 bool MadeChange = false;
9282 for (auto &Block : F) {
9283 // Move the rest probes to the beginning of the block.
9284 auto FirstInst = Block.getFirstInsertionPt();
9285 while (FirstInst != Block.end() && FirstInst->isDebugOrPseudoInst())
9286 ++FirstInst;
9287 BasicBlock::iterator I(FirstInst);
9288 I++;
9289 while (I != Block.end()) {
9290 if (auto *II = dyn_cast<PseudoProbeInst>(I++)) {
9291 II->moveBefore(FirstInst);
9292 MadeChange = true;
9293 }
9294 }
9295 }
9296 return MadeChange;
9297}
9298
9299/// Some targets prefer to split a conditional branch like:
9300/// \code
9301/// %0 = icmp ne i32 %a, 0
9302/// %1 = icmp ne i32 %b, 0
9303/// %or.cond = or i1 %0, %1
9304/// br i1 %or.cond, label %TrueBB, label %FalseBB
9305/// \endcode
9306/// into multiple branch instructions like:
9307/// \code
9308/// bb1:
9309/// %0 = icmp ne i32 %a, 0
9310/// br i1 %0, label %TrueBB, label %bb2
9311/// bb2:
9312/// %1 = icmp ne i32 %b, 0
9313/// br i1 %1, label %TrueBB, label %FalseBB
9314/// \endcode
9315/// This usually allows instruction selection to do even further optimizations
9316/// and combine the compare with the branch instruction. Currently this is
9317/// applied for targets which have "cheap" jump instructions.
9318///
9319/// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
9320///
9321bool CodeGenPrepare::splitBranchCondition(Function &F) {
9322 if (!TM->Options.EnableFastISel || TLI->isJumpExpensive())
9323 return false;
9324
9325 bool MadeChange = false;
9326 for (auto &BB : F) {
9327 // Does this BB end with the following?
9328 // %cond1 = icmp|fcmp|binary instruction ...
9329 // %cond2 = icmp|fcmp|binary instruction ...
9330 // %cond.or = or|and i1 %cond1, cond2
9331 // br i1 %cond.or label %dest1, label %dest2"
9332 Instruction *LogicOp;
9333 BasicBlock *TBB, *FBB;
9334 if (!match(BB.getTerminator(),
9335 m_Br(m_OneUse(m_Instruction(LogicOp)), TBB, FBB)))
9336 continue;
9337
9338 auto *Br1 = cast<CondBrInst>(BB.getTerminator());
9339 if (Br1->getMetadata(LLVMContext::MD_unpredictable))
9340 continue;
9341
9342 // The merging of mostly empty BB can cause a degenerate branch.
9343 if (TBB == FBB)
9344 continue;
9345
9346 unsigned Opc;
9347 Value *Cond1, *Cond2;
9348 if (match(LogicOp,
9349 m_LogicalAnd(m_OneUse(m_Value(Cond1)), m_OneUse(m_Value(Cond2)))))
9350 Opc = Instruction::And;
9351 else if (match(LogicOp, m_LogicalOr(m_OneUse(m_Value(Cond1)),
9352 m_OneUse(m_Value(Cond2)))))
9353 Opc = Instruction::Or;
9354 else
9355 continue;
9356
9357 auto IsGoodCond = [](Value *Cond) {
9358 return match(
9359 Cond,
9361 m_LogicalOr(m_Value(), m_Value()))));
9362 };
9363 if (!IsGoodCond(Cond1) || !IsGoodCond(Cond2))
9364 continue;
9365
9366 LLVM_DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
9367
9368 // Create a new BB.
9369 auto *TmpBB =
9370 BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split",
9371 BB.getParent(), BB.getNextNode());
9372 if (IsHugeFunc)
9373 FreshBBs.insert(TmpBB);
9374
9375 // Update original basic block by using the first condition directly by the
9376 // branch instruction and removing the no longer needed and/or instruction.
9377 Br1->setCondition(Cond1);
9378 LogicOp->eraseFromParent();
9379
9380 // Depending on the condition we have to either replace the true or the
9381 // false successor of the original branch instruction.
9382 if (Opc == Instruction::And)
9383 Br1->setSuccessor(0, TmpBB);
9384 else
9385 Br1->setSuccessor(1, TmpBB);
9386
9387 // Fill in the new basic block.
9388 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
9389 if (auto *I = dyn_cast<Instruction>(Cond2)) {
9390 I->removeFromParent();
9391 I->insertBefore(Br2->getIterator());
9392 }
9393
9394 // Update PHI nodes in both successors. The original BB needs to be
9395 // replaced in one successor's PHI nodes, because the branch comes now from
9396 // the newly generated BB (NewBB). In the other successor we need to add one
9397 // incoming edge to the PHI nodes, because both branch instructions target
9398 // now the same successor. Depending on the original branch condition
9399 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
9400 // we perform the correct update for the PHI nodes.
9401 // This doesn't change the successor order of the just created branch
9402 // instruction (or any other instruction).
9403 if (Opc == Instruction::Or)
9404 std::swap(TBB, FBB);
9405
9406 // Replace the old BB with the new BB.
9407 TBB->replacePhiUsesWith(&BB, TmpBB);
9408
9409 // Add another incoming edge from the new BB.
9410 for (PHINode &PN : FBB->phis()) {
9411 auto *Val = PN.getIncomingValueForBlock(&BB);
9412 PN.addIncoming(Val, TmpBB);
9413 }
9414
9415 if (Loop *L = LI->getLoopFor(&BB))
9416 L->addBasicBlockToLoop(TmpBB, *LI);
9417
9418 // The edge we need to delete starts at BB and ends at whatever TBB ends
9419 // up pointing to.
9420 DTU->applyUpdates({{DominatorTree::Insert, &BB, TmpBB},
9421 {DominatorTree::Insert, TmpBB, TBB},
9422 {DominatorTree::Insert, TmpBB, FBB},
9423 {DominatorTree::Delete, &BB, TBB}});
9424
9425 // Update the branch weights (from SelectionDAGBuilder::
9426 // FindMergedConditions).
9427 if (Opc == Instruction::Or) {
9428 // Codegen X | Y as:
9429 // BB1:
9430 // jmp_if_X TBB
9431 // jmp TmpBB
9432 // TmpBB:
9433 // jmp_if_Y TBB
9434 // jmp FBB
9435 //
9436
9437 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
9438 // The requirement is that
9439 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
9440 // = TrueProb for original BB.
9441 // Assuming the original weights are A and B, one choice is to set BB1's
9442 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
9443 // assumes that
9444 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
9445 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
9446 // TmpBB, but the math is more complicated.
9447 uint64_t TrueWeight, FalseWeight;
9448 if (extractBranchWeights(*Br1, TrueWeight, FalseWeight)) {
9449 uint64_t NewTrueWeight = TrueWeight;
9450 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
9451 setFittedBranchWeights(*Br1, {NewTrueWeight, NewFalseWeight},
9452 hasBranchWeightOrigin(*Br1));
9453
9454 NewTrueWeight = TrueWeight;
9455 NewFalseWeight = 2 * FalseWeight;
9456 setFittedBranchWeights(*Br2, {NewTrueWeight, NewFalseWeight},
9457 /*IsExpected=*/false);
9458 }
9459 } else {
9460 // Codegen X & Y as:
9461 // BB1:
9462 // jmp_if_X TmpBB
9463 // jmp FBB
9464 // TmpBB:
9465 // jmp_if_Y TBB
9466 // jmp FBB
9467 //
9468 // This requires creation of TmpBB after CurBB.
9469
9470 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
9471 // The requirement is that
9472 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
9473 // = FalseProb for original BB.
9474 // Assuming the original weights are A and B, one choice is to set BB1's
9475 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
9476 // assumes that
9477 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
9478 uint64_t TrueWeight, FalseWeight;
9479 if (extractBranchWeights(*Br1, TrueWeight, FalseWeight)) {
9480 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
9481 uint64_t NewFalseWeight = FalseWeight;
9482 setFittedBranchWeights(*Br1, {NewTrueWeight, NewFalseWeight},
9483 /*IsExpected=*/false);
9484
9485 NewTrueWeight = 2 * TrueWeight;
9486 NewFalseWeight = FalseWeight;
9487 setFittedBranchWeights(*Br2, {NewTrueWeight, NewFalseWeight},
9488 /*IsExpected=*/false);
9489 }
9490 }
9491
9492 MadeChange = true;
9493
9494 LLVM_DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
9495 TmpBB->dump());
9496 }
9497 return MadeChange;
9498}
#define Success
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:683
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:1226
#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:1057
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1186
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:325
bool isSignedIntN(unsigned N) const
Check if this APInt has an N-bits signed integer value.
Definition APInt.h:431
unsigned getSignificantBits() const
Get the minimum bit size for this signed APInt.
Definition APInt.h:1551
unsigned logBase2() const
Definition APInt.h:1781
LLVM_ABI APInt sext(unsigned width) const
Sign extend to a new width.
Definition APInt.cpp:1030
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:436
int64_t getSExtValue() const
Get sign extended value.
Definition APInt.h:1582
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:782
iterator end()
Definition DenseMap.h:702
unsigned size() const
Definition DenseMap.h:733
bool erase(const KeyT &Val)
Definition DenseMap.h:946
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:843
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.
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:843
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:2901
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.
user_iterator_impl< Instruction > user_iterator
Specialize the methods defined in Value, as we know that an instruction can only be used by other ins...
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()
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.
iterator_range< user_iterator > users()
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
user_iterator user_begin()
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
user_iterator user_end()
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)
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.
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation.
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 isFreeAddrSpaceCast(const DataLayout &DL, unsigned SrcAS, unsigned DestAS) const
Returns true if a cast from SrcAS to DestAS is "cheap", such that e.g.
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 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(const DataLayout &DL, 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
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 *CtxI=nullptr, const TargetLibraryInfo *TLibInfo=nullptr) const
This is an approximation of reciprocal throughput of a math/logic op.
@ 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 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:283
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:299
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:363
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:222
LLVM_ABI bool isScalableTy() const
Return true if this is a type whose size is a known multiple of vscale.
Definition Type.cpp:61
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
Definition Type.h:265
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:303
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition Type.h:222
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:257
user_iterator user_begin()
Definition Value.h:404
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:441
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:260
iterator_range< user_iterator > users()
Definition Value.h:428
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:712
bool use_empty() const
Definition Value.h:348
iterator_range< use_iterator > uses()
Definition Value.h:382
void mutateType(Type *Ty)
Mutate the type of this Value to be of the specified type.
Definition Value.h:809
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:83
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)
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the 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:316
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:1781
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:1755
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:1685
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:2261
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:1676
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:2139
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:2224
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:649
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:2150
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:2189
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
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
Definition STLExtras.h:2216
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:1762
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:408
LLVM_ABI bool recognizeBSwapOrBitReverseIdiom(Instruction *I, bool MatchBSwaps, bool MatchBitReversals, SmallVectorImpl< Instruction * > &InsertedInsts)
Try to match a bswap or bitreverse idiom.
Definition Local.cpp:3794
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
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:1769
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
auto make_first_range(ContainerTy &&c)
Given a container of pairs, return a range over the first elements.
Definition STLExtras.h:1415
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:214
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:705
TargetTransformInfo TTI
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:2028
IntPtrTy
Definition InstrProf.h:82
DWARFExpression::Operation Op
bool isSafeToSpeculativelyExecuteWithVariableReplaced(const Instruction *I, bool IgnoreUBImplyingAttrs=true)
Don't use information from its non-constant operands.
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:2208
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition Alignment.h:201
Align getKnownAlignment(Value *V, const DataLayout &DL, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr)
Try to infer an alignment for the specified pointer.
Definition Local.h:240
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.