LLVM 24.0.0git
CodeGenPrepare.cpp
Go to the documentation of this file.
1//===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This pass munges the code in the input function to better prepare it for
10// SelectionDAG-based code generation. This works around limitations in it's
11// basic-block-at-a-time approach. It should eventually be removed.
12//
13//===----------------------------------------------------------------------===//
14
16#include "llvm/ADT/APInt.h"
17#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/DenseMap.h"
19#include "llvm/ADT/MapVector.h"
21#include "llvm/ADT/STLExtras.h"
24#include "llvm/ADT/Statistic.h"
46#include "llvm/Config/llvm-config.h"
47#include "llvm/IR/Argument.h"
48#include "llvm/IR/Attributes.h"
49#include "llvm/IR/BasicBlock.h"
50#include "llvm/IR/CFG.h"
51#include "llvm/IR/Constant.h"
52#include "llvm/IR/Constants.h"
53#include "llvm/IR/CycleInfo.h"
54#include "llvm/IR/DataLayout.h"
55#include "llvm/IR/DebugInfo.h"
57#include "llvm/IR/Dominators.h"
58#include "llvm/IR/Function.h"
60#include "llvm/IR/GlobalValue.h"
62#include "llvm/IR/IRBuilder.h"
63#include "llvm/IR/InlineAsm.h"
64#include "llvm/IR/InstrTypes.h"
65#include "llvm/IR/Instruction.h"
68#include "llvm/IR/Intrinsics.h"
69#include "llvm/IR/IntrinsicsAArch64.h"
70#include "llvm/IR/LLVMContext.h"
71#include "llvm/IR/MDBuilder.h"
72#include "llvm/IR/Module.h"
73#include "llvm/IR/Operator.h"
76#include "llvm/IR/Statepoint.h"
77#include "llvm/IR/Type.h"
78#include "llvm/IR/Use.h"
79#include "llvm/IR/User.h"
80#include "llvm/IR/Value.h"
81#include "llvm/IR/ValueHandle.h"
82#include "llvm/IR/ValueMap.h"
84#include "llvm/Pass.h"
90#include "llvm/Support/Debug.h"
100#include <algorithm>
101#include <cassert>
102#include <cstdint>
103#include <iterator>
104#include <limits>
105#include <memory>
106#include <optional>
107#include <utility>
108#include <vector>
109
110using namespace llvm;
111using namespace llvm::PatternMatch;
112
113#define DEBUG_TYPE "codegenprepare"
114
115STATISTIC(NumBlocksElim, "Number of blocks eliminated");
116STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
117STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
118STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
119 "sunken Cmps");
120STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
121 "of sunken Casts");
122STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
123 "computations were sunk");
124STATISTIC(NumMemoryInstsPhiCreated,
125 "Number of phis created when address "
126 "computations were sunk to memory instructions");
127STATISTIC(NumMemoryInstsSelectCreated,
128 "Number of select created when address "
129 "computations were sunk to memory instructions");
130STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
131STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
132STATISTIC(NumAndsAdded,
133 "Number of and mask instructions added to form ext loads");
134STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized");
135STATISTIC(NumRetsDup, "Number of return instructions duplicated");
136STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
137STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
138STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
139
141 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
142 cl::desc("Disable branch optimizations in CodeGenPrepare"));
143
144static cl::opt<bool>
145 DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
146 cl::desc("Disable GC optimizations in CodeGenPrepare"));
147
148static cl::opt<bool>
149 DisableSelectToBranch("disable-cgp-select2branch", cl::Hidden,
150 cl::init(false),
151 cl::desc("Disable select to branch conversion."));
152
153static cl::opt<bool>
154 AddrSinkUsingGEPs("addr-sink-using-gep", cl::Hidden, cl::init(true),
155 cl::desc("Address sinking in CGP using GEPs."));
156
157static cl::opt<bool>
158 EnableAndCmpSinking("enable-andcmp-sinking", cl::Hidden, cl::init(true),
159 cl::desc("Enable sinking and/cmp into branches."));
160
162 "disable-cgp-store-extract", cl::Hidden, cl::init(false),
163 cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
164
166 "stress-cgp-store-extract", cl::Hidden, cl::init(false),
167 cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
168
170 "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
171 cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
172 "CodeGenPrepare"));
173
175 "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
176 cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
177 "optimization in CodeGenPrepare"));
178
180 "disable-preheader-prot", cl::Hidden, cl::init(false),
181 cl::desc("Disable protection against removing loop preheaders"));
182
184 "profile-guided-section-prefix", cl::Hidden, cl::init(true),
185 cl::desc("Use profile info to add section prefix for hot/cold functions"));
186
188 "profile-unknown-in-special-section", cl::Hidden,
189 cl::desc("In profiling mode like sampleFDO, if a function doesn't have "
190 "profile, we cannot tell the function is cold for sure because "
191 "it may be a function newly added without ever being sampled. "
192 "With the flag enabled, compiler can put such profile unknown "
193 "functions into a special section, so runtime system can choose "
194 "to handle it in a different way than .text section, to save "
195 "RAM for example. "));
196
198 "bbsections-guided-section-prefix", cl::Hidden, cl::init(true),
199 cl::desc("Use the basic-block-sections profile to determine the text "
200 "section prefix for hot functions. Functions with "
201 "basic-block-sections profile will be placed in `.text.hot` "
202 "regardless of their FDO profile info. Other functions won't be "
203 "impacted, i.e., their prefixes will be decided by FDO/sampleFDO "
204 "profiles."));
205
207 "cgp-freq-ratio-to-skip-merge", cl::Hidden, cl::init(2),
208 cl::desc("Skip merging empty blocks if (frequency of empty block) / "
209 "(frequency of destination block) is greater than this ratio"));
210
212 "force-split-store", cl::Hidden, cl::init(false),
213 cl::desc("Force store splitting no matter what the target query says."));
214
216 "cgp-type-promotion-merge", cl::Hidden,
217 cl::desc("Enable merging of redundant sexts when one is dominating"
218 " the other."),
219 cl::init(true));
220
222 "disable-complex-addr-modes", cl::Hidden, cl::init(false),
223 cl::desc("Disables combining addressing modes with different parts "
224 "in optimizeMemoryInst."));
225
226static cl::opt<bool>
227 AddrSinkNewPhis("addr-sink-new-phis", cl::Hidden, cl::init(false),
228 cl::desc("Allow creation of Phis in Address sinking."));
229
231 "addr-sink-new-select", cl::Hidden, cl::init(true),
232 cl::desc("Allow creation of selects in Address sinking."));
233
235 "addr-sink-combine-base-reg", cl::Hidden, cl::init(true),
236 cl::desc("Allow combining of BaseReg field in Address sinking."));
237
239 "addr-sink-combine-base-gv", cl::Hidden, cl::init(true),
240 cl::desc("Allow combining of BaseGV field in Address sinking."));
241
243 "addr-sink-combine-base-offs", cl::Hidden, cl::init(true),
244 cl::desc("Allow combining of BaseOffs field in Address sinking."));
245
247 "addr-sink-combine-scaled-reg", cl::Hidden, cl::init(true),
248 cl::desc("Allow combining of ScaledReg field in Address sinking."));
249
250static cl::opt<bool>
251 EnableGEPOffsetSplit("cgp-split-large-offset-gep", cl::Hidden,
252 cl::init(true),
253 cl::desc("Enable splitting large offset of GEP."));
254
256 "cgp-icmp-eq2icmp-st", cl::Hidden, cl::init(false),
257 cl::desc("Enable ICMP_EQ to ICMP_S(L|G)T conversion."));
258
259static cl::opt<bool>
260 VerifyBFIUpdates("cgp-verify-bfi-updates", cl::Hidden, cl::init(false),
261 cl::desc("Enable BFI update verification for "
262 "CodeGenPrepare."));
263
264static cl::opt<bool>
265 OptimizePhiTypes("cgp-optimize-phi-types", cl::Hidden, cl::init(true),
266 cl::desc("Enable converting phi types in CodeGenPrepare"));
267
269 HugeFuncThresholdInCGPP("cgpp-huge-func", cl::init(10000), cl::Hidden,
270 cl::desc("Least BB number of huge function."));
271
273 MaxAddressUsersToScan("cgp-max-address-users-to-scan", cl::init(100),
275 cl::desc("Max number of address users to look at"));
276
277static cl::opt<bool>
278 DisableDeletePHIs("disable-cgp-delete-phis", cl::Hidden, cl::init(false),
279 cl::desc("Disable elimination of dead PHI nodes."));
280
281namespace {
282
283enum ExtType {
284 ZeroExtension, // Zero extension has been seen.
285 SignExtension, // Sign extension has been seen.
286 BothExtension // This extension type is used if we saw sext after
287 // ZeroExtension had been set, or if we saw zext after
288 // SignExtension had been set. It makes the type
289 // information of a promoted instruction invalid.
290};
291
292enum ModifyDT {
293 NotModifyDT, // Not Modify any DT.
294 ModifyBBDT, // Modify the Basic Block Dominator Tree.
295 ModifyInstDT // Modify the Instruction Dominator in a Basic Block,
296 // This usually means we move/delete/insert instruction
297 // in a Basic Block. So we should re-iterate instructions
298 // in such Basic Block.
299};
300
301using SetOfInstrs = SmallPtrSet<Instruction *, 16>;
302using TypeIsSExt = PointerIntPair<Type *, 2, ExtType>;
303using InstrToOrigTy = DenseMap<Instruction *, TypeIsSExt>;
305using ValueToSExts = MapVector<Value *, SExts>;
306
307class TypePromotionTransaction;
308
309class CodeGenPrepare {
310 friend class CodeGenPrepareLegacyPass;
311 const TargetMachine *TM = nullptr;
312 const TargetSubtargetInfo *SubtargetInfo = nullptr;
313 const TargetLowering *TLI = nullptr;
314 const TargetRegisterInfo *TRI = nullptr;
315 const TargetTransformInfo *TTI = nullptr;
316 const BasicBlockSectionsProfileReader *BBSectionsProfileReader = nullptr;
317 const TargetLibraryInfo *TLInfo = nullptr;
318 DomTreeUpdater *DTU = nullptr;
319 LoopInfo *LI = nullptr;
320 BlockFrequencyInfo *BFI;
321 BranchProbabilityInfo *BPI;
322 ProfileSummaryInfo *PSI = nullptr;
323
324 /// As we scan instructions optimizing them, this is the next instruction
325 /// to optimize. Transforms that can invalidate this should update it.
326 BasicBlock::iterator CurInstIterator;
327
328 /// Keeps track of non-local addresses that have been sunk into a block.
329 /// This allows us to avoid inserting duplicate code for blocks with
330 /// multiple load/stores of the same address. The usage of WeakTrackingVH
331 /// enables SunkAddrs to be treated as a cache whose entries can be
332 /// invalidated if a sunken address computation has been erased.
333 ValueMap<Value *, WeakTrackingVH> SunkAddrs;
334
335 /// Keeps track of all instructions inserted for the current function.
336 SetOfInstrs InsertedInsts;
337
338 /// Keeps track of the type of the related instruction before their
339 /// promotion for the current function.
340 InstrToOrigTy PromotedInsts;
341
342 /// Keep track of instructions removed during promotion.
343 SetOfInstrs RemovedInsts;
344
345 /// Keep track of sext chains based on their initial value.
346 DenseMap<Value *, Instruction *> SeenChainsForSExt;
347
348 /// Keep track of GEPs accessing the same data structures such as structs or
349 /// arrays that are candidates to be split later because of their large
350 /// size.
351 MapVector<AssertingVH<Value>,
353 LargeOffsetGEPMap;
354
355 /// Keep track of new GEP base after splitting the GEPs having large offset.
356 SmallSet<AssertingVH<Value>, 2> NewGEPBases;
357
358 /// Map serial numbers to Large offset GEPs.
359 DenseMap<AssertingVH<GetElementPtrInst>, int> LargeOffsetGEPID;
360
361 /// Keep track of SExt promoted.
362 ValueToSExts ValToSExtendedUses;
363
364 /// True if the function has the OptSize attribute.
365 bool OptSize;
366
367 /// DataLayout for the Function being processed.
368 const DataLayout *DL = nullptr;
369
370public:
371 CodeGenPrepare() = default;
372 CodeGenPrepare(const TargetMachine *TM) : TM(TM){};
373 /// If encounter huge function, we need to limit the build time.
374 bool IsHugeFunc = false;
375
376 /// FreshBBs is like worklist, it collected the updated BBs which need
377 /// to be optimized again.
378 /// Note: Consider building time in this pass, when a BB updated, we need
379 /// to insert such BB into FreshBBs for huge function.
380 SmallPtrSet<BasicBlock *, 32> FreshBBs;
381
382 void releaseMemory() {
383 // Clear per function information.
384 InsertedInsts.clear();
385 PromotedInsts.clear();
386 FreshBBs.clear();
387 }
388
390
391private:
392 template <typename F>
393 void resetIteratorIfInvalidatedWhileCalling(BasicBlock *BB, F f) {
394 // Substituting can cause recursive simplifications, which can invalidate
395 // our iterator. Use a WeakTrackingVH to hold onto it in case this
396 // happens.
397 Value *CurValue = &*CurInstIterator;
398 WeakTrackingVH IterHandle(CurValue);
399
400 f();
401
402 // If the iterator instruction was recursively deleted, start over at the
403 // start of the block.
404 if (IterHandle != CurValue) {
405 CurInstIterator = BB->begin();
406 SunkAddrs.clear();
407 }
408 }
409
410 // Get the DominatorTree, updating it if necessary.
411 DominatorTree &getDT() { return DTU->getDomTree(); }
412
413 void removeAllAssertingVHReferences(Value *V);
414 bool eliminateAssumptions(Function &F);
415 bool eliminateFallThrough(Function &F);
416 bool eliminateMostlyEmptyBlocks(Function &F, bool &ResetLI);
417 BasicBlock *findDestBlockOfMergeableEmptyBlock(BasicBlock *BB);
418 bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
419 bool eliminateMostlyEmptyBlock(BasicBlock *BB);
420 bool isMergingEmptyBlockProfitable(BasicBlock *BB, BasicBlock *DestBB,
421 bool isPreheader);
422 bool makeBitReverse(Instruction &I);
423 bool optimizeBlock(BasicBlock &BB, ModifyDT &ModifiedDT);
424 bool optimizeInst(Instruction *I, ModifyDT &ModifiedDT);
425 bool optimizeMemoryInst(Instruction *MemoryInst, Value *Addr, Type *AccessTy,
426 unsigned AddrSpace);
427 bool optimizeGatherScatterInst(Instruction *MemoryInst, Value *Ptr);
428 bool optimizeMulWithOverflow(Instruction *I, bool IsSigned,
429 ModifyDT &ModifiedDT);
430 bool optimizeInlineAsmInst(CallInst *CS);
431 bool optimizeCallInst(CallInst *CI, ModifyDT &ModifiedDT);
432 bool optimizeExt(Instruction *&I);
433 bool optimizeExtUses(Instruction *I);
434 bool optimizeLoadExt(LoadInst *Load);
435 bool optimizeShiftInst(BinaryOperator *BO);
436 bool optimizeFunnelShift(IntrinsicInst *Fsh);
437 bool optimizeSelectInst(SelectInst *SI);
438 bool optimizeShuffleVectorInst(ShuffleVectorInst *SVI);
439 bool optimizeSwitchType(SwitchInst *SI);
440 bool optimizeSwitchPhiConstants(SwitchInst *SI);
441 bool optimizeSwitchInst(SwitchInst *SI);
442 bool optimizeExtractElementInst(Instruction *Inst);
443 bool dupRetToEnableTailCallOpts(BasicBlock *BB, ModifyDT &ModifiedDT);
444 bool fixupDbgVariableRecord(DbgVariableRecord &I);
445 bool fixupDbgVariableRecordsOnInst(Instruction &I);
446 bool placeDbgValues(Function &F);
447 bool placePseudoProbes(Function &F);
448 bool canFormExtLd(const SmallVectorImpl<Instruction *> &MovedExts,
449 LoadInst *&LI, Instruction *&Inst, bool HasPromoted);
450 bool tryToPromoteExts(TypePromotionTransaction &TPT,
451 const SmallVectorImpl<Instruction *> &Exts,
452 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
453 unsigned CreatedInstsCost = 0);
454 bool mergeSExts(Function &F);
455 bool splitLargeGEPOffsets();
456 bool optimizePhiType(PHINode *Inst, SmallPtrSetImpl<PHINode *> &Visited,
457 SmallPtrSetImpl<Instruction *> &DeletedInstrs);
458 bool optimizePhiTypes(Function &F);
459 bool performAddressTypePromotion(
460 Instruction *&Inst, bool AllowPromotionWithoutCommonHeader,
461 bool HasPromoted, TypePromotionTransaction &TPT,
462 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts);
463 bool splitBranchCondition(Function &F);
464 bool simplifyOffsetableRelocate(GCStatepointInst &I);
465
466 bool tryToSinkFreeOperands(Instruction *I);
467 bool replaceMathCmpWithIntrinsic(BinaryOperator *BO, Value *Arg0, Value *Arg1,
468 CmpInst *Cmp, Intrinsic::ID IID);
469 bool optimizeCmp(CmpInst *Cmp, ModifyDT &ModifiedDT);
470 bool optimizeURem(Instruction *Rem);
471 bool combineToUSubWithOverflow(CmpInst *Cmp, ModifyDT &ModifiedDT);
472 bool combineToUAddWithOverflow(CmpInst *Cmp, ModifyDT &ModifiedDT);
473 bool unfoldPowerOf2Test(CmpInst *Cmp);
474 void verifyBFIUpdates(Function &F);
475 bool _run(Function &F);
476};
477
478class CodeGenPrepareLegacyPass : public FunctionPass {
479public:
480 static char ID; // Pass identification, replacement for typeid
481
482 CodeGenPrepareLegacyPass() : FunctionPass(ID) {}
483
484 bool runOnFunction(Function &F) override;
485
486 StringRef getPassName() const override { return "CodeGen Prepare"; }
487
488 void getAnalysisUsage(AnalysisUsage &AU) const override {
489 // FIXME: When we can selectively preserve passes, preserve the domtree.
490 AU.addRequired<ProfileSummaryInfoWrapperPass>();
491 AU.addRequired<TargetLibraryInfoWrapperPass>();
492 AU.addRequired<TargetPassConfig>();
493 AU.addRequired<TargetTransformInfoWrapperPass>();
494 AU.addRequired<DominatorTreeWrapperPass>();
495 AU.addRequired<LoopInfoWrapperPass>();
496 AU.addRequired<BranchProbabilityInfoWrapperPass>();
497 AU.addRequired<BlockFrequencyInfoWrapperPass>();
498 AU.addUsedIfAvailable<BasicBlockSectionsProfileReaderWrapperPass>();
499 }
500};
501
502} // end anonymous namespace
503
504char CodeGenPrepareLegacyPass::ID = 0;
505
506bool CodeGenPrepareLegacyPass::runOnFunction(Function &F) {
507 if (skipFunction(F))
508 return false;
509 auto TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
510 CodeGenPrepare CGP(TM);
511 CGP.DL = &F.getDataLayout();
512 CGP.SubtargetInfo = TM->getSubtargetImpl(F);
513 CGP.TLI = CGP.SubtargetInfo->getTargetLowering();
514 CGP.TRI = CGP.SubtargetInfo->getRegisterInfo();
515 CGP.TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
516 CGP.TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
517 CGP.LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
518 CGP.BPI = &getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
519 CGP.BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
520 CGP.PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
521 auto BBSPRWP =
522 getAnalysisIfAvailable<BasicBlockSectionsProfileReaderWrapperPass>();
523 CGP.BBSectionsProfileReader = BBSPRWP ? &BBSPRWP->getBBSPR() : nullptr;
524 DomTreeUpdater DTUpdater(
525 &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
526 DomTreeUpdater::UpdateStrategy::Lazy);
527 CGP.DTU = &DTUpdater;
528
529 return CGP._run(F);
530}
531
532INITIALIZE_PASS_BEGIN(CodeGenPrepareLegacyPass, DEBUG_TYPE,
533 "Optimize for code generation", false, false)
541INITIALIZE_PASS_END(CodeGenPrepareLegacyPass, DEBUG_TYPE,
542 "Optimize for code generation", false, false)
543
545 return new CodeGenPrepareLegacyPass();
546}
547
550 CodeGenPrepare CGP(TM);
551
552 bool Changed = CGP.run(F, AM);
553 if (!Changed)
554 return PreservedAnalyses::all();
555
559 return PA;
560}
561
562bool CodeGenPrepare::run(Function &F, FunctionAnalysisManager &AM) {
563 DL = &F.getDataLayout();
564 SubtargetInfo = TM->getSubtargetImpl(F);
565 TLI = SubtargetInfo->getTargetLowering();
566 TRI = SubtargetInfo->getRegisterInfo();
567 TLInfo = &AM.getResult<TargetLibraryAnalysis>(F);
569 LI = &AM.getResult<LoopAnalysis>(F);
572 auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
573 PSI = MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
574 if (!PSI)
575 reportFatalUsageError("this pass requires the profile-summary module "
576 "analysis to be available");
577 BBSectionsProfileReader =
580 DomTreeUpdater::UpdateStrategy::Lazy);
581 DTU = &DTUpdater;
582 return _run(F);
583}
584
585bool CodeGenPrepare::_run(Function &F) {
586 bool EverMadeChange = false;
587
588 OptSize = F.hasOptSize();
589 // Use the basic-block-sections profile to promote hot functions to .text.hot
590 // if requested.
591 if (BBSectionsGuidedSectionPrefix && BBSectionsProfileReader &&
592 BBSectionsProfileReader->isFunctionHot(F.getName())) {
593 (void)F.setSectionPrefix("hot");
594 } else if (ProfileGuidedSectionPrefix) {
595 // The hot attribute overwrites profile count based hotness while profile
596 // counts based hotness overwrite the cold attribute.
597 // This is a conservative behabvior.
598 if (F.hasFnAttribute(Attribute::Hot) ||
599 PSI->isFunctionHotInCallGraph(&F, *BFI))
600 (void)F.setSectionPrefix("hot");
601 // If PSI shows this function is not hot, we will placed the function
602 // into unlikely section if (1) PSI shows this is a cold function, or
603 // (2) the function has a attribute of cold.
604 else if (PSI->isFunctionColdInCallGraph(&F, *BFI) ||
605 F.hasFnAttribute(Attribute::Cold))
606 (void)F.setSectionPrefix("unlikely");
607 else if (ProfileUnknownInSpecialSection && PSI->hasPartialSampleProfile() &&
608 PSI->isFunctionHotnessUnknown(F))
609 (void)F.setSectionPrefix("unknown");
610 }
611
612 /// This optimization identifies DIV instructions that can be
613 /// profitably bypassed and carried out with a shorter, faster divide.
614 if (!OptSize && !PSI->hasHugeWorkingSetSize() && TLI->isSlowDivBypassed()) {
615 const DenseMap<unsigned int, unsigned int> &BypassWidths =
617 BasicBlock *BB = &*F.begin();
618 while (BB != nullptr) {
619 // bypassSlowDivision may create new BBs, but we don't want to reapply the
620 // optimization to those blocks.
621 BasicBlock *Next = BB->getNextNode();
622 if (!llvm::shouldOptimizeForSize(BB, PSI, BFI))
623 EverMadeChange |= bypassSlowDivision(BB, BypassWidths, DTU, LI, BPI);
624 BB = Next;
625 }
626 }
627
628 // Get rid of @llvm.assume builtins before attempting to eliminate empty
629 // blocks, since there might be blocks that only contain @llvm.assume calls
630 // (plus arguments that we can get rid of).
631 EverMadeChange |= eliminateAssumptions(F);
632
633 auto resetLoopInfo = [this]() {
634 LI->releaseMemory();
635 LI->analyze(DTU->getDomTree());
636 };
637
638 // Eliminate blocks that contain only PHI nodes and an
639 // unconditional branch.
640 bool ResetLI = false;
641 EverMadeChange |= eliminateMostlyEmptyBlocks(F, ResetLI);
642 if (ResetLI)
643 resetLoopInfo();
644
646 EverMadeChange |= splitBranchCondition(F);
647
648 // Split some critical edges where one of the sources is an indirect branch,
649 // to help generate sane code for PHIs involving such edges.
650 bool Split = SplitIndirectBrCriticalEdges(F, /*IgnoreBlocksWithoutPHI=*/true,
651 BPI, BFI, DTU);
652 EverMadeChange |= Split;
653 if (Split)
654 resetLoopInfo();
655
656#ifndef NDEBUG
657 if (VerifyDomInfo)
658 assert(getDT().verify(DominatorTree::VerificationLevel::Fast) &&
659 "Incorrect DominatorTree updates in CGP");
660
661 if (VerifyLoopInfo)
662 LI->verify();
663#endif
664
665 // If we are optimzing huge function, we need to consider the build time.
666 // Because the basic algorithm's complex is near O(N!).
667 IsHugeFunc = F.size() > HugeFuncThresholdInCGPP;
668
669 bool MadeChange = true;
670 bool FuncIterated = false;
671 while (MadeChange) {
672 MadeChange = false;
673
674 // This is required because optimizeBlock() calls getDT() inside the loop
675 // below, which flushes pending updates and may delete dead blocks, leading
676 // to iterator invalidation.
677 DTU->flush();
678
679 for (BasicBlock &BB : llvm::make_early_inc_range(F)) {
680 if (FuncIterated && !FreshBBs.contains(&BB))
681 continue;
682
683 ModifyDT ModifiedDTOnIteration = ModifyDT::NotModifyDT;
684 bool Changed = optimizeBlock(BB, ModifiedDTOnIteration);
685
686 MadeChange |= Changed;
687 if (IsHugeFunc) {
688 // If the BB is updated, it may still has chance to be optimized.
689 // This usually happen at sink optimization.
690 // For example:
691 //
692 // bb0:
693 // %and = and i32 %a, 4
694 // %cmp = icmp eq i32 %and, 0
695 //
696 // If the %cmp sink to other BB, the %and will has chance to sink.
697 if (Changed)
698 FreshBBs.insert(&BB);
699 else if (FuncIterated)
700 FreshBBs.erase(&BB);
701 } else {
702 // For small/normal functions, we restart BB iteration if the dominator
703 // tree of the Function was changed.
704 if (ModifiedDTOnIteration != ModifyDT::NotModifyDT)
705 break;
706 }
707 }
708 // We have iterated all the BB in the (only work for huge) function.
709 FuncIterated = IsHugeFunc;
710
711 if (EnableTypePromotionMerge && !ValToSExtendedUses.empty())
712 MadeChange |= mergeSExts(F);
713 if (!LargeOffsetGEPMap.empty())
714 MadeChange |= splitLargeGEPOffsets();
715 MadeChange |= optimizePhiTypes(F);
716
717 if (MadeChange)
718 eliminateFallThrough(F);
719
720#ifndef NDEBUG
721 if (VerifyDomInfo)
722 assert(getDT().verify(DominatorTree::VerificationLevel::Fast) &&
723 "Incorrect DominatorTree updates in CGP");
724
725 if (VerifyLoopInfo)
726 LI->verify();
727#endif
728
729 // Really free removed instructions during promotion.
730 for (Instruction *I : RemovedInsts)
731 I->deleteValue();
732
733 EverMadeChange |= MadeChange;
734 SeenChainsForSExt.clear();
735 ValToSExtendedUses.clear();
736 RemovedInsts.clear();
737 LargeOffsetGEPMap.clear();
738 LargeOffsetGEPID.clear();
739 }
740
741 NewGEPBases.clear();
742 SunkAddrs.clear();
743
744 // LoopInfo is not needed anymore and ConstantFoldTerminator can break it.
745 LI = nullptr;
746
747 if (!DisableBranchOpts) {
748 MadeChange = false;
749 // Use a set vector to get deterministic iteration order. The order the
750 // blocks are removed may affect whether or not PHI nodes in successors
751 // are removed.
752 SmallSetVector<BasicBlock *, 8> WorkList;
753 for (BasicBlock &BB : F) {
755 MadeChange |= ConstantFoldTerminator(&BB, true, nullptr, DTU);
756 if (!MadeChange)
757 continue;
758
759 for (BasicBlock *Succ : Successors)
760 if (pred_empty(Succ))
761 WorkList.insert(Succ);
762 }
763
764 // Delete the dead blocks and any of their dead successors.
765 MadeChange |= !WorkList.empty();
766 while (!WorkList.empty()) {
767 BasicBlock *BB = WorkList.pop_back_val();
769
770 DeleteDeadBlock(BB, DTU);
771
772 for (BasicBlock *Succ : Successors)
773 if (pred_empty(Succ))
774 WorkList.insert(Succ);
775 }
776
777 // Flush pending DT updates in order to finalise deletion of dead blocks.
778 DTU->flush();
779
780 // Merge pairs of basic blocks with unconditional branches, connected by
781 // a single edge.
782 if (EverMadeChange || MadeChange)
783 MadeChange |= eliminateFallThrough(F);
784
785 EverMadeChange |= MadeChange;
786 }
787
788 if (!DisableGCOpts) {
790 for (BasicBlock &BB : F)
791 for (Instruction &I : BB)
792 if (auto *SP = dyn_cast<GCStatepointInst>(&I))
793 Statepoints.push_back(SP);
794 for (auto &I : Statepoints)
795 EverMadeChange |= simplifyOffsetableRelocate(*I);
796 }
797
798 // Do this last to clean up use-before-def scenarios introduced by other
799 // preparatory transforms.
800 EverMadeChange |= placeDbgValues(F);
801 EverMadeChange |= placePseudoProbes(F);
802
803#ifndef NDEBUG
805 verifyBFIUpdates(F);
806#endif
807
808 return EverMadeChange;
809}
810
811bool CodeGenPrepare::eliminateAssumptions(Function &F) {
812 bool MadeChange = false;
813 for (BasicBlock &BB : F) {
814 CurInstIterator = BB.begin();
815 while (CurInstIterator != BB.end()) {
816 Instruction *I = &*(CurInstIterator++);
817 if (auto *Assume = dyn_cast<AssumeInst>(I)) {
818 MadeChange = true;
819 Value *Operand = Assume->getOperand(0);
820 Assume->eraseFromParent();
821
822 resetIteratorIfInvalidatedWhileCalling(&BB, [&]() {
823 RecursivelyDeleteTriviallyDeadInstructions(Operand, TLInfo, nullptr);
824 });
825 }
826 }
827 }
828 return MadeChange;
829}
830
831/// An instruction is about to be deleted, so remove all references to it in our
832/// GEP-tracking data strcutures.
833void CodeGenPrepare::removeAllAssertingVHReferences(Value *V) {
834 LargeOffsetGEPMap.erase(V);
835 NewGEPBases.erase(V);
836
838 if (!GEP)
839 return;
840
841 LargeOffsetGEPID.erase(GEP);
842
843 auto VecI = LargeOffsetGEPMap.find(GEP->getPointerOperand());
844 if (VecI == LargeOffsetGEPMap.end())
845 return;
846
847 auto &GEPVector = VecI->second;
848 llvm::erase_if(GEPVector, [=](auto &Elt) { return Elt.first == GEP; });
849
850 if (GEPVector.empty())
851 LargeOffsetGEPMap.erase(VecI);
852}
853
854// Verify BFI has been updated correctly by recomputing BFI and comparing them.
855[[maybe_unused]] void CodeGenPrepare::verifyBFIUpdates(Function &F) {
856 DominatorTree NewDT(F);
857 CycleInfo NewCI;
858 NewCI.compute(F);
859 BranchProbabilityInfo NewBPI(F, NewCI, TLInfo);
860 BlockFrequencyInfo NewBFI(F, NewBPI, NewCI);
861 NewBFI.verifyMatch(*BFI);
862}
863
864/// Merge basic blocks which are connected by a single edge, where one of the
865/// basic blocks has a single successor pointing to the other basic block,
866/// which has a single predecessor.
867bool CodeGenPrepare::eliminateFallThrough(Function &F) {
868 bool Changed = false;
869 SmallPtrSet<BasicBlock *, 8> Preds;
870 // Scan all of the blocks in the function, except for the entry block.
871 for (auto &Block : llvm::drop_begin(F)) {
872 auto *BB = &Block;
873 if (DTU->isBBPendingDeletion(BB))
874 continue;
875 // If the destination block has a single pred, then this is a trivial
876 // edge, just collapse it.
877 BasicBlock *SinglePred = BB->getSinglePredecessor();
878
879 // Don't merge if BB's address is taken.
880 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken())
881 continue;
882
883 if (isa<UncondBrInst>(SinglePred->getTerminator())) {
884 Changed = true;
885 LLVM_DEBUG(dbgs() << "To merge:\n" << *BB << "\n\n\n");
886
887 // Merge BB into SinglePred and delete it.
888 MergeBlockIntoPredecessor(BB, DTU, LI);
889 Preds.insert(SinglePred);
890
891 if (IsHugeFunc) {
892 // Update FreshBBs to optimize the merged BB.
893 FreshBBs.insert(SinglePred);
894 FreshBBs.erase(BB);
895 }
896 }
897 }
898
899 // (Repeatedly) merging blocks into their predecessors can create redundant
900 // debug intrinsics.
901 for (auto *Pred : Preds)
902 if (!DTU->isBBPendingDeletion(Pred))
904
905 return Changed;
906}
907
908/// Find a destination block from BB if BB is mergeable empty block.
909BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) {
910 // If this block doesn't end with an uncond branch, ignore it.
911 UncondBrInst *BI = dyn_cast<UncondBrInst>(BB->getTerminator());
912 if (!BI)
913 return nullptr;
914
915 // If the instruction before the branch (skipping debug info) isn't a phi
916 // node, then other stuff is happening here.
918 if (BBI != BB->begin()) {
919 --BBI;
920 if (!isa<PHINode>(BBI))
921 return nullptr;
922 }
923
924 // Do not break infinite loops.
925 BasicBlock *DestBB = BI->getSuccessor();
926 if (DestBB == BB)
927 return nullptr;
928
929 if (!canMergeBlocks(BB, DestBB))
930 DestBB = nullptr;
931
932 return DestBB;
933}
934
935/// Eliminate blocks that contain only PHI nodes, debug info directives, and an
936/// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
937/// edges in ways that are non-optimal for isel. Start by eliminating these
938/// blocks so we can split them the way we want them.
939bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F, bool &ResetLI) {
940 SmallPtrSet<BasicBlock *, 16> Preheaders;
941 SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end());
942 while (!LoopList.empty()) {
943 Loop *L = LoopList.pop_back_val();
944 llvm::append_range(LoopList, *L);
945 if (BasicBlock *Preheader = L->getLoopPreheader())
946 Preheaders.insert(Preheader);
947 }
948
949 ResetLI = false;
950 bool MadeChange = false;
951 SmallPtrSet<PHINode *, 32> KnownNonDeadPHIs;
952 // Note that this intentionally skips the entry block.
953 for (auto &Block : llvm::drop_begin(F)) {
954 // Delete phi nodes that could block deleting other empty blocks.
956 MadeChange |= DeleteDeadPHIs(&Block, TLInfo, nullptr, &KnownNonDeadPHIs);
957 }
958
959 for (auto &Block : llvm::drop_begin(F)) {
960 auto *BB = &Block;
961 if (DTU->isBBPendingDeletion(BB))
962 continue;
963 BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB);
964 if (!DestBB ||
965 !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.count(BB)))
966 continue;
967
968 ResetLI |= eliminateMostlyEmptyBlock(BB);
969 MadeChange = true;
970 }
971 return MadeChange;
972}
973
974bool CodeGenPrepare::isMergingEmptyBlockProfitable(BasicBlock *BB,
975 BasicBlock *DestBB,
976 bool isPreheader) {
977 // Do not delete loop preheaders if doing so would create a critical edge.
978 // Loop preheaders can be good locations to spill registers. If the
979 // preheader is deleted and we create a critical edge, registers may be
980 // spilled in the loop body instead.
981 if (!DisablePreheaderProtect && isPreheader &&
982 !(BB->getSinglePredecessor() &&
984 return false;
985
986 // Skip merging if the block's successor is also a successor to any callbr
987 // that leads to this block.
988 // FIXME: Is this really needed? Is this a correctness issue?
989 for (BasicBlock *Pred : predecessors(BB)) {
990 if (isa<CallBrInst>(Pred->getTerminator()) &&
991 llvm::is_contained(successors(Pred), DestBB))
992 return false;
993 }
994
995 // Try to skip merging if the unique predecessor of BB is terminated by a
996 // switch or indirect branch instruction, and BB is used as an incoming block
997 // of PHIs in DestBB. In such case, merging BB and DestBB would cause ISel to
998 // add COPY instructions in the predecessor of BB instead of BB (if it is not
999 // merged). Note that the critical edge created by merging such blocks wont be
1000 // split in MachineSink because the jump table is not analyzable. By keeping
1001 // such empty block (BB), ISel will place COPY instructions in BB, not in the
1002 // predecessor of BB.
1003 BasicBlock *Pred = BB->getUniquePredecessor();
1004 if (!Pred || !(isa<SwitchInst>(Pred->getTerminator()) ||
1006 return true;
1007
1008 if (BB->getTerminator() != &*BB->getFirstNonPHIOrDbg())
1009 return true;
1010
1011 // We use a simple cost heuristic which determine skipping merging is
1012 // profitable if the cost of skipping merging is less than the cost of
1013 // merging : Cost(skipping merging) < Cost(merging BB), where the
1014 // Cost(skipping merging) is Freq(BB) * (Cost(Copy) + Cost(Branch)), and
1015 // the Cost(merging BB) is Freq(Pred) * Cost(Copy).
1016 // Assuming Cost(Copy) == Cost(Branch), we could simplify it to :
1017 // Freq(Pred) / Freq(BB) > 2.
1018 // Note that if there are multiple empty blocks sharing the same incoming
1019 // value for the PHIs in the DestBB, we consider them together. In such
1020 // case, Cost(merging BB) will be the sum of their frequencies.
1021
1022 if (!isa<PHINode>(DestBB->begin()))
1023 return true;
1024
1025 SmallPtrSet<BasicBlock *, 16> SameIncomingValueBBs;
1026
1027 // Find all other incoming blocks from which incoming values of all PHIs in
1028 // DestBB are the same as the ones from BB.
1029 for (BasicBlock *DestBBPred : predecessors(DestBB)) {
1030 if (DestBBPred == BB)
1031 continue;
1032
1033 if (llvm::all_of(DestBB->phis(), [&](const PHINode &DestPN) {
1034 return DestPN.getIncomingValueForBlock(BB) ==
1035 DestPN.getIncomingValueForBlock(DestBBPred);
1036 }))
1037 SameIncomingValueBBs.insert(DestBBPred);
1038 }
1039
1040 // See if all BB's incoming values are same as the value from Pred. In this
1041 // case, no reason to skip merging because COPYs are expected to be place in
1042 // Pred already.
1043 if (SameIncomingValueBBs.count(Pred))
1044 return true;
1045
1046 BlockFrequency PredFreq = BFI->getBlockFreq(Pred);
1047 BlockFrequency BBFreq = BFI->getBlockFreq(BB);
1048
1049 for (auto *SameValueBB : SameIncomingValueBBs)
1050 if (SameValueBB->getUniquePredecessor() == Pred &&
1051 DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB))
1052 BBFreq += BFI->getBlockFreq(SameValueBB);
1053
1054 std::optional<BlockFrequency> Limit = BBFreq.mul(FreqRatioToSkipMerge);
1055 return !Limit || PredFreq <= *Limit;
1056}
1057
1058/// Return true if we can merge BB into DestBB if there is a single
1059/// unconditional branch between them, and BB contains no other non-phi
1060/// instructions.
1061bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
1062 const BasicBlock *DestBB) const {
1063 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
1064 // the successor. If there are more complex condition (e.g. preheaders),
1065 // don't mess around with them.
1066 for (const PHINode &PN : BB->phis()) {
1067 for (const User *U : PN.users()) {
1068 const Instruction *UI = cast<Instruction>(U);
1069 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
1070 return false;
1071 // If User is inside DestBB block and it is a PHINode then check
1072 // incoming value. If incoming value is not from BB then this is
1073 // a complex condition (e.g. preheaders) we want to avoid here.
1074 if (UI->getParent() == DestBB) {
1075 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
1076 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
1077 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
1078 if (Insn && Insn->getParent() == BB &&
1079 Insn->getParent() != UPN->getIncomingBlock(I))
1080 return false;
1081 }
1082 }
1083 }
1084 }
1085
1086 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
1087 // and DestBB may have conflicting incoming values for the block. If so, we
1088 // can't merge the block.
1089 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
1090 if (!DestBBPN)
1091 return true; // no conflict.
1092
1093 // Collect the preds of BB.
1094 SmallPtrSet<const BasicBlock *, 16> BBPreds;
1095 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
1096 // It is faster to get preds from a PHI than with pred_iterator.
1097 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
1098 BBPreds.insert(BBPN->getIncomingBlock(i));
1099 } else {
1100 BBPreds.insert_range(predecessors(BB));
1101 }
1102
1103 // Walk the preds of DestBB.
1104 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
1105 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
1106 if (BBPreds.count(Pred)) { // Common predecessor?
1107 for (const PHINode &PN : DestBB->phis()) {
1108 const Value *V1 = PN.getIncomingValueForBlock(Pred);
1109 const Value *V2 = PN.getIncomingValueForBlock(BB);
1110
1111 // If V2 is a phi node in BB, look up what the mapped value will be.
1112 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
1113 if (V2PN->getParent() == BB)
1114 V2 = V2PN->getIncomingValueForBlock(Pred);
1115
1116 // If there is a conflict, bail out.
1117 if (V1 != V2)
1118 return false;
1119 }
1120 }
1121 }
1122
1123 return true;
1124}
1125
1126/// Replace all old uses with new ones, and push the updated BBs into FreshBBs.
1127static void replaceAllUsesWith(Value *Old, Value *New,
1129 bool IsHuge) {
1130 auto *OldI = dyn_cast<Instruction>(Old);
1131 if (OldI) {
1132 for (Value::user_iterator UI = OldI->user_begin(), E = OldI->user_end();
1133 UI != E; ++UI) {
1135 if (IsHuge)
1136 FreshBBs.insert(User->getParent());
1137 }
1138 }
1139 Old->replaceAllUsesWith(New);
1140}
1141
1142/// Eliminate a basic block that has only phi's and an unconditional branch in
1143/// it.
1144/// Indicate that the LoopInfo was modified only if it wasn't updated.
1145bool CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
1146 UncondBrInst *BI = cast<UncondBrInst>(BB->getTerminator());
1147 BasicBlock *DestBB = BI->getSuccessor();
1148
1149 LLVM_DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n"
1150 << *BB << *DestBB);
1151
1152 // If the destination block has a single pred, then this is a trivial edge,
1153 // just collapse it.
1154 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
1155 if (SinglePred != DestBB) {
1156 assert(SinglePred == BB &&
1157 "Single predecessor not the same as predecessor");
1158 // Merge DestBB into SinglePred/BB and delete it.
1159 MergeBlockIntoPredecessor(DestBB, DTU, LI);
1160 // Note: BB(=SinglePred) will not be deleted on this path.
1161 // DestBB(=its single successor) is the one that was deleted.
1162 LLVM_DEBUG(dbgs() << "AFTER:\n" << *SinglePred << "\n\n\n");
1163
1164 if (IsHugeFunc) {
1165 // Update FreshBBs to optimize the merged BB.
1166 FreshBBs.insert(SinglePred);
1167 FreshBBs.erase(DestBB);
1168 }
1169 return false;
1170 }
1171 }
1172
1173 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
1174 // to handle the new incoming edges it is about to have.
1175 for (PHINode &PN : DestBB->phis()) {
1176 // Remove the incoming value for BB, and remember it.
1177 Value *InVal = PN.removeIncomingValue(BB, false);
1178
1179 // Two options: either the InVal is a phi node defined in BB or it is some
1180 // value that dominates BB.
1181 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
1182 if (InValPhi && InValPhi->getParent() == BB) {
1183 // Add all of the input values of the input PHI as inputs of this phi.
1184 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
1185 PN.addIncoming(InValPhi->getIncomingValue(i),
1186 InValPhi->getIncomingBlock(i));
1187 } else {
1188 // Otherwise, add one instance of the dominating value for each edge that
1189 // we will be adding.
1190 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
1191 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
1192 PN.addIncoming(InVal, BBPN->getIncomingBlock(i));
1193 } else {
1194 for (BasicBlock *Pred : predecessors(BB))
1195 PN.addIncoming(InVal, Pred);
1196 }
1197 }
1198 }
1199
1200 // Preserve loop Metadata.
1201 if (BI->hasMetadata(LLVMContext::MD_loop)) {
1202 for (auto *Pred : predecessors(BB))
1203 Pred->getTerminator()->copyMetadata(*BI, LLVMContext::MD_loop);
1204 }
1205
1206 // The PHIs are now updated, change everything that refers to BB to use
1207 // DestBB and remove BB.
1209 SmallPtrSet<BasicBlock *, 8> SeenPreds;
1210 SmallPtrSet<BasicBlock *, 8> PredOfDestBB(llvm::from_range,
1211 predecessors(DestBB));
1212 for (auto *Pred : predecessors(BB)) {
1213 if (!PredOfDestBB.contains(Pred)) {
1214 if (SeenPreds.insert(Pred).second)
1215 DTUpdates.push_back({DominatorTree::Insert, Pred, DestBB});
1216 }
1217 }
1218 SeenPreds.clear();
1219 for (auto *Pred : predecessors(BB)) {
1220 if (SeenPreds.insert(Pred).second)
1221 DTUpdates.push_back({DominatorTree::Delete, Pred, BB});
1222 }
1223 DTUpdates.push_back({DominatorTree::Delete, BB, DestBB});
1224 BB->replaceAllUsesWith(DestBB);
1225 DTU->applyUpdates(DTUpdates);
1226 DTU->deleteBB(BB);
1227 ++NumBlocksElim;
1228
1229 LLVM_DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
1230 return true;
1231}
1232
1233// Computes a map of base pointer relocation instructions to corresponding
1234// derived pointer relocation instructions given a vector of all relocate calls
1236 const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
1238 &RelocateInstMap) {
1239 // Collect information in two maps: one primarily for locating the base object
1240 // while filling the second map; the second map is the final structure holding
1241 // a mapping between Base and corresponding Derived relocate calls
1243 for (auto *ThisRelocate : AllRelocateCalls) {
1244 auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
1245 ThisRelocate->getDerivedPtrIndex());
1246 RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
1247 }
1248 for (auto &Item : RelocateIdxMap) {
1249 std::pair<unsigned, unsigned> Key = Item.first;
1250 if (Key.first == Key.second)
1251 // Base relocation: nothing to insert
1252 continue;
1253
1254 GCRelocateInst *I = Item.second;
1255 auto BaseKey = std::make_pair(Key.first, Key.first);
1256
1257 // We're iterating over RelocateIdxMap so we cannot modify it.
1258 auto MaybeBase = RelocateIdxMap.find(BaseKey);
1259 if (MaybeBase == RelocateIdxMap.end())
1260 // TODO: We might want to insert a new base object relocate and gep off
1261 // that, if there are enough derived object relocates.
1262 continue;
1263
1264 RelocateInstMap[MaybeBase->second].push_back(I);
1265 }
1266}
1267
1268// Accepts a GEP and extracts the operands into a vector provided they're all
1269// small integer constants
1271 SmallVectorImpl<Value *> &OffsetV) {
1272 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
1273 // Only accept small constant integer operands
1274 auto *Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
1275 if (!Op || Op->getZExtValue() > 20)
1276 return false;
1277 }
1278
1279 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
1280 OffsetV.push_back(GEP->getOperand(i));
1281 return true;
1282}
1283
1284// Takes a RelocatedBase (base pointer relocation instruction) and Targets to
1285// replace, computes a replacement, and affects it.
1286static bool
1288 const SmallVectorImpl<GCRelocateInst *> &Targets) {
1289 bool MadeChange = false;
1290 // We must ensure the relocation of derived pointer is defined after
1291 // relocation of base pointer. If we find a relocation corresponding to base
1292 // defined earlier than relocation of base then we move relocation of base
1293 // right before found relocation. We consider only relocation in the same
1294 // basic block as relocation of base. Relocations from other basic block will
1295 // be skipped by optimization and we do not care about them.
1296 for (auto R = RelocatedBase->getParent()->getFirstInsertionPt();
1297 &*R != RelocatedBase; ++R)
1298 if (auto *RI = dyn_cast<GCRelocateInst>(R))
1299 if (RI->getStatepoint() == RelocatedBase->getStatepoint())
1300 if (RI->getBasePtrIndex() == RelocatedBase->getBasePtrIndex()) {
1301 RelocatedBase->moveBefore(RI->getIterator());
1302 MadeChange = true;
1303 break;
1304 }
1305
1306 for (GCRelocateInst *ToReplace : Targets) {
1307 assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&
1308 "Not relocating a derived object of the original base object");
1309 if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
1310 // A duplicate relocate call. TODO: coalesce duplicates.
1311 continue;
1312 }
1313
1314 if (RelocatedBase->getParent() != ToReplace->getParent()) {
1315 // Base and derived relocates are in different basic blocks.
1316 // In this case transform is only valid when base dominates derived
1317 // relocate. However it would be too expensive to check dominance
1318 // for each such relocate, so we skip the whole transformation.
1319 continue;
1320 }
1321
1322 Value *Base = ToReplace->getBasePtr();
1323 auto *Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
1324 if (!Derived || Derived->getPointerOperand() != Base)
1325 continue;
1326
1328 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
1329 continue;
1330
1331 // Create a Builder and replace the target callsite with a gep
1332 assert(RelocatedBase->getNextNode() &&
1333 "Should always have one since it's not a terminator");
1334
1335 // Insert after RelocatedBase
1336 IRBuilder<> Builder(RelocatedBase->getNextNode());
1337 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
1338
1339 // If gc_relocate does not match the actual type, cast it to the right type.
1340 // In theory, there must be a bitcast after gc_relocate if the type does not
1341 // match, and we should reuse it to get the derived pointer. But it could be
1342 // cases like this:
1343 // bb1:
1344 // ...
1345 // %g1 = call coldcc i8 addrspace(1)*
1346 // @llvm.experimental.gc.relocate.p1i8(...) br label %merge
1347 //
1348 // bb2:
1349 // ...
1350 // %g2 = call coldcc i8 addrspace(1)*
1351 // @llvm.experimental.gc.relocate.p1i8(...) br label %merge
1352 //
1353 // merge:
1354 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
1355 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
1356 //
1357 // In this case, we can not find the bitcast any more. So we insert a new
1358 // bitcast no matter there is already one or not. In this way, we can handle
1359 // all cases, and the extra bitcast should be optimized away in later
1360 // passes.
1361 Value *ActualRelocatedBase = RelocatedBase;
1362 if (RelocatedBase->getType() != Base->getType()) {
1363 ActualRelocatedBase =
1364 Builder.CreateBitCast(RelocatedBase, Base->getType());
1365 }
1366 Value *Replacement =
1367 Builder.CreateGEP(Derived->getSourceElementType(), ActualRelocatedBase,
1368 ArrayRef(OffsetV));
1369 Replacement->takeName(ToReplace);
1370 // If the newly generated derived pointer's type does not match the original
1371 // derived pointer's type, cast the new derived pointer to match it. Same
1372 // reasoning as above.
1373 Value *ActualReplacement = Replacement;
1374 if (Replacement->getType() != ToReplace->getType()) {
1375 ActualReplacement =
1376 Builder.CreateBitCast(Replacement, ToReplace->getType());
1377 }
1378 ToReplace->replaceAllUsesWith(ActualReplacement);
1379 ToReplace->eraseFromParent();
1380
1381 MadeChange = true;
1382 }
1383 return MadeChange;
1384}
1385
1386// Turns this:
1387//
1388// %base = ...
1389// %ptr = gep %base + 15
1390// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1391// %base' = relocate(%tok, i32 4, i32 4)
1392// %ptr' = relocate(%tok, i32 4, i32 5)
1393// %val = load %ptr'
1394//
1395// into this:
1396//
1397// %base = ...
1398// %ptr = gep %base + 15
1399// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1400// %base' = gc.relocate(%tok, i32 4, i32 4)
1401// %ptr' = gep %base' + 15
1402// %val = load %ptr'
1403bool CodeGenPrepare::simplifyOffsetableRelocate(GCStatepointInst &I) {
1404 bool MadeChange = false;
1405 SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
1406 for (auto *U : I.users())
1407 if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
1408 // Collect all the relocate calls associated with a statepoint
1409 AllRelocateCalls.push_back(Relocate);
1410
1411 // We need at least one base pointer relocation + one derived pointer
1412 // relocation to mangle
1413 if (AllRelocateCalls.size() < 2)
1414 return false;
1415
1416 // RelocateInstMap is a mapping from the base relocate instruction to the
1417 // corresponding derived relocate instructions
1418 MapVector<GCRelocateInst *, SmallVector<GCRelocateInst *, 0>> RelocateInstMap;
1419 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
1420 if (RelocateInstMap.empty())
1421 return false;
1422
1423 for (auto &Item : RelocateInstMap)
1424 // Item.first is the RelocatedBase to offset against
1425 // Item.second is the vector of Targets to replace
1426 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
1427 return MadeChange;
1428}
1429
1430/// Sink the specified cast instruction into its user blocks.
1431static bool SinkCast(CastInst *CI) {
1432 BasicBlock *DefBB = CI->getParent();
1433
1434 /// InsertedCasts - Only insert a cast in each block once.
1436
1437 bool MadeChange = false;
1438 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
1439 UI != E;) {
1440 Use &TheUse = UI.getUse();
1442
1443 // Figure out which BB this cast is used in. For PHI's this is the
1444 // appropriate predecessor block.
1445 BasicBlock *UserBB = User->getParent();
1446 if (PHINode *PN = dyn_cast<PHINode>(User)) {
1447 UserBB = PN->getIncomingBlock(TheUse);
1448 }
1449
1450 // Preincrement use iterator so we don't invalidate it.
1451 ++UI;
1452
1453 // The first insertion point of a block containing an EH pad is after the
1454 // pad. If the pad is the user, we cannot sink the cast past the pad.
1455 if (User->isEHPad())
1456 continue;
1457
1458 // If the block selected to receive the cast is an EH pad that does not
1459 // allow non-PHI instructions before the terminator, we can't sink the
1460 // cast.
1461 if (UserBB->getTerminator()->isEHPad())
1462 continue;
1463
1464 // If this user is in the same block as the cast, don't change the cast.
1465 if (UserBB == DefBB)
1466 continue;
1467
1468 // If we have already inserted a cast into this block, use it.
1469 CastInst *&InsertedCast = InsertedCasts[UserBB];
1470
1471 if (!InsertedCast) {
1472 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1473 assert(InsertPt != UserBB->end());
1474 InsertedCast = cast<CastInst>(CI->clone());
1475 InsertedCast->insertBefore(*UserBB, InsertPt);
1476 }
1477
1478 // Replace a use of the cast with a use of the new cast.
1479 TheUse = InsertedCast;
1480 MadeChange = true;
1481 ++NumCastUses;
1482 }
1483
1484 // If we removed all uses, nuke the cast.
1485 if (CI->use_empty()) {
1486 salvageDebugInfo(*CI);
1487 CI->eraseFromParent();
1488 MadeChange = true;
1489 }
1490
1491 return MadeChange;
1492}
1493
1494/// If the specified cast instruction is a noop copy (e.g. it's casting from
1495/// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
1496/// reduce the number of virtual registers that must be created and coalesced.
1497///
1498/// Return true if any changes are made.
1500 const DataLayout &DL) {
1501 // Sink only "cheap" (or nop) address-space casts. This is a weaker condition
1502 // than sinking only nop casts, but is helpful on some platforms.
1503 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(CI)) {
1504 if (!TLI.isFreeAddrSpaceCast(ASC->getSrcAddressSpace(),
1505 ASC->getDestAddressSpace()))
1506 return false;
1507 }
1508
1509 // If this is a noop copy,
1510 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
1511 EVT DstVT = TLI.getValueType(DL, CI->getType());
1512
1513 // This is an fp<->int conversion?
1514 if (SrcVT.isInteger() != DstVT.isInteger())
1515 return false;
1516
1517 // If this is an extension, it will be a zero or sign extension, which
1518 // isn't a noop.
1519 if (SrcVT.bitsLT(DstVT))
1520 return false;
1521
1522 // If these values will be promoted, find out what they will be promoted
1523 // to. This helps us consider truncates on PPC as noop copies when they
1524 // are.
1525 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
1527 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
1528 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
1530 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
1531
1532 // If, after promotion, these are the same types, this is a noop copy.
1533 if (SrcVT != DstVT)
1534 return false;
1535
1536 return SinkCast(CI);
1537}
1538
1539// Match a simple increment by constant operation. Note that if a sub is
1540// matched, the step is negated (as if the step had been canonicalized to
1541// an add, even though we leave the instruction alone.)
1542static bool matchIncrement(const Instruction *IVInc, Instruction *&LHS,
1543 Constant *&Step) {
1544 if (match(IVInc, m_Add(m_Instruction(LHS), m_Constant(Step))) ||
1546 m_Instruction(LHS), m_Constant(Step)))))
1547 return true;
1548 if (match(IVInc, m_Sub(m_Instruction(LHS), m_Constant(Step))) ||
1550 m_Instruction(LHS), m_Constant(Step))))) {
1551 Step = ConstantExpr::getNeg(Step);
1552 return true;
1553 }
1554 return false;
1555}
1556
1557/// If given \p PN is an inductive variable with value IVInc coming from the
1558/// backedge, and on each iteration it gets increased by Step, return pair
1559/// <IVInc, Step>. Otherwise, return std::nullopt.
1560static std::optional<std::pair<Instruction *, Constant *>>
1561getIVIncrement(const PHINode *PN, const LoopInfo *LI) {
1562 const Loop *L = LI->getLoopFor(PN->getParent());
1563 if (!L || L->getHeader() != PN->getParent() || !L->getLoopLatch())
1564 return std::nullopt;
1565 auto *IVInc =
1566 dyn_cast<Instruction>(PN->getIncomingValueForBlock(L->getLoopLatch()));
1567 if (!IVInc || LI->getLoopFor(IVInc->getParent()) != L)
1568 return std::nullopt;
1569 Instruction *LHS = nullptr;
1570 Constant *Step = nullptr;
1571 if (matchIncrement(IVInc, LHS, Step) && LHS == PN)
1572 return std::make_pair(IVInc, Step);
1573 return std::nullopt;
1574}
1575
1576static bool isIVIncrement(const Value *V, const LoopInfo *LI) {
1577 auto *I = dyn_cast<Instruction>(V);
1578 if (!I)
1579 return false;
1580 Instruction *LHS = nullptr;
1581 Constant *Step = nullptr;
1582 if (!matchIncrement(I, LHS, Step))
1583 return false;
1584 if (auto *PN = dyn_cast<PHINode>(LHS))
1585 if (auto IVInc = getIVIncrement(PN, LI))
1586 return IVInc->first == I;
1587 return false;
1588}
1589
1590bool CodeGenPrepare::replaceMathCmpWithIntrinsic(BinaryOperator *BO,
1591 Value *Arg0, Value *Arg1,
1592 CmpInst *Cmp,
1593 Intrinsic::ID IID) {
1594 auto IsReplacableIVIncrement = [this, &Cmp](BinaryOperator *BO) {
1595 if (!isIVIncrement(BO, LI))
1596 return false;
1597 const Loop *L = LI->getLoopFor(BO->getParent());
1598 assert(L && "L should not be null after isIVIncrement()");
1599 // Do not risk on moving increment into a child loop.
1600 if (LI->getLoopFor(Cmp->getParent()) != L)
1601 return false;
1602
1603 // Finally, we need to ensure that the insert point will dominate all
1604 // existing uses of the increment.
1605
1606 auto &DT = getDT();
1607 if (DT.dominates(Cmp->getParent(), BO->getParent()))
1608 // If we're moving up the dom tree, all uses are trivially dominated.
1609 // (This is the common case for code produced by LSR.)
1610 return true;
1611
1612 // Otherwise, special case the single use in the phi recurrence.
1613 return BO->hasOneUse() && DT.dominates(Cmp->getParent(), L->getLoopLatch());
1614 };
1615 if (BO->getParent() != Cmp->getParent() && !IsReplacableIVIncrement(BO)) {
1616 // We used to use a dominator tree here to allow multi-block optimization.
1617 // But that was problematic because:
1618 // 1. It could cause a perf regression by hoisting the math op into the
1619 // critical path.
1620 // 2. It could cause a perf regression by creating a value that was live
1621 // across multiple blocks and increasing register pressure.
1622 // 3. Use of a dominator tree could cause large compile-time regression.
1623 // This is because we recompute the DT on every change in the main CGP
1624 // run-loop. The recomputing is probably unnecessary in many cases, so if
1625 // that was fixed, using a DT here would be ok.
1626 //
1627 // There is one important particular case we still want to handle: if BO is
1628 // the IV increment. Important properties that make it profitable:
1629 // - We can speculate IV increment anywhere in the loop (as long as the
1630 // indvar Phi is its only user);
1631 // - Upon computing Cmp, we effectively compute something equivalent to the
1632 // IV increment (despite it loops differently in the IR). So moving it up
1633 // to the cmp point does not really increase register pressure.
1634 return false;
1635 }
1636
1637 // We allow matching the canonical IR (add X, C) back to (usubo X, -C).
1638 if (BO->getOpcode() == Instruction::Add &&
1639 IID == Intrinsic::usub_with_overflow) {
1640 assert(isa<Constant>(Arg1) && "Unexpected input for usubo");
1642 }
1643
1644 // Insert at the first instruction of the pair.
1645 Instruction *InsertPt = nullptr;
1646 for (Instruction &Iter : *Cmp->getParent()) {
1647 // If BO is an XOR, it is not guaranteed that it comes after both inputs to
1648 // the overflow intrinsic are defined.
1649 if ((BO->getOpcode() != Instruction::Xor && &Iter == BO) || &Iter == Cmp) {
1650 InsertPt = &Iter;
1651 break;
1652 }
1653 }
1654 assert(InsertPt != nullptr && "Parent block did not contain cmp or binop");
1655
1656 IRBuilder<> Builder(InsertPt);
1657 Value *MathOV = Builder.CreateBinaryIntrinsic(IID, Arg0, Arg1);
1658 if (BO->getOpcode() != Instruction::Xor) {
1659 Value *Math = Builder.CreateExtractValue(MathOV, 0, "math");
1660 replaceAllUsesWith(BO, Math, FreshBBs, IsHugeFunc);
1661 } else
1662 assert(BO->hasOneUse() &&
1663 "Patterns with XOr should use the BO only in the compare");
1664 Value *OV = Builder.CreateExtractValue(MathOV, 1, "ov");
1665 replaceAllUsesWith(Cmp, OV, FreshBBs, IsHugeFunc);
1666 Cmp->eraseFromParent();
1667 BO->eraseFromParent();
1668 return true;
1669}
1670
1671/// Match special-case patterns that check for unsigned add overflow.
1673 BinaryOperator *&Add) {
1674 // Add = add A, 1; Cmp = icmp eq A,-1 (overflow if A is max val)
1675 // Add = add A,-1; Cmp = icmp ne A, 0 (overflow if A is non-zero)
1676 Value *A = Cmp->getOperand(0), *B = Cmp->getOperand(1);
1677
1678 // We are not expecting non-canonical/degenerate code. Just bail out.
1679 if (isa<Constant>(A))
1680 return false;
1681
1682 ICmpInst::Predicate Pred = Cmp->getPredicate();
1683 if (Pred == ICmpInst::ICMP_EQ && match(B, m_AllOnes()))
1684 B = ConstantInt::get(B->getType(), 1);
1685 else if (Pred == ICmpInst::ICMP_NE && match(B, m_ZeroInt()))
1686 B = Constant::getAllOnesValue(B->getType());
1687 else
1688 return false;
1689
1690 // Check the users of the variable operand of the compare looking for an add
1691 // with the adjusted constant.
1692 for (User *U : A->users()) {
1693 if (match(U, m_Add(m_Specific(A), m_Specific(B)))) {
1695 return true;
1696 }
1697 }
1698 return false;
1699}
1700
1701/// Try to combine the compare into a call to the llvm.uadd.with.overflow
1702/// intrinsic. Return true if any changes were made.
1703bool CodeGenPrepare::combineToUAddWithOverflow(CmpInst *Cmp,
1704 ModifyDT &ModifiedDT) {
1705 bool EdgeCase = false;
1706 Value *A, *B;
1707 BinaryOperator *Add;
1708 if (!match(Cmp, m_UAddWithOverflow(m_Value(A), m_Value(B), m_BinOp(Add)))) {
1710 return false;
1711 // Set A and B in case we match matchUAddWithOverflowConstantEdgeCases.
1712 A = Add->getOperand(0);
1713 B = Add->getOperand(1);
1714 EdgeCase = true;
1715 }
1716
1718 TLI->getValueType(*DL, Add->getType()),
1719 Add->hasNUsesOrMore(EdgeCase ? 1 : 2)))
1720 return false;
1721
1722 // We don't want to move around uses of condition values this late, so we
1723 // check if it is legal to create the call to the intrinsic in the basic
1724 // block containing the icmp.
1725 if (Add->getParent() != Cmp->getParent() && !Add->hasOneUse())
1726 return false;
1727
1728 if (!replaceMathCmpWithIntrinsic(Add, A, B, Cmp,
1729 Intrinsic::uadd_with_overflow))
1730 return false;
1731
1732 // Reset callers - do not crash by iterating over a dead instruction.
1733 ModifiedDT = ModifyDT::ModifyInstDT;
1734 return true;
1735}
1736
1737bool CodeGenPrepare::combineToUSubWithOverflow(CmpInst *Cmp,
1738 ModifyDT &ModifiedDT) {
1739 // We are not expecting non-canonical/degenerate code. Just bail out.
1740 Value *A = Cmp->getOperand(0), *B = Cmp->getOperand(1);
1741 if (isa<Constant>(A) && isa<Constant>(B))
1742 return false;
1743
1744 // Convert (A u> B) to (A u< B) to simplify pattern matching.
1745 ICmpInst::Predicate Pred = Cmp->getPredicate();
1746 if (Pred == ICmpInst::ICMP_UGT) {
1747 std::swap(A, B);
1748 Pred = ICmpInst::ICMP_ULT;
1749 }
1750 // Convert special-case: (A == 0) is the same as (A u< 1).
1751 if (Pred == ICmpInst::ICMP_EQ && match(B, m_ZeroInt())) {
1752 B = ConstantInt::get(B->getType(), 1);
1753 Pred = ICmpInst::ICMP_ULT;
1754 }
1755 // Convert special-case: (A != 0) is the same as (0 u< A).
1756 if (Pred == ICmpInst::ICMP_NE && match(B, m_ZeroInt())) {
1757 std::swap(A, B);
1758 Pred = ICmpInst::ICMP_ULT;
1759 }
1760 if (Pred != ICmpInst::ICMP_ULT)
1761 return false;
1762
1763 // Walk the users of a variable operand of a compare looking for a subtract or
1764 // add with that same operand. Also match the 2nd operand of the compare to
1765 // the add/sub, but that may be a negated constant operand of an add.
1766 Value *CmpVariableOperand = isa<Constant>(A) ? B : A;
1767 BinaryOperator *Sub = nullptr;
1768 for (User *U : CmpVariableOperand->users()) {
1769 // A - B, A u< B --> usubo(A, B)
1770 if (match(U, m_Sub(m_Specific(A), m_Specific(B)))) {
1772 break;
1773 }
1774
1775 // A + (-C), A u< C (canonicalized form of (sub A, C))
1776 const APInt *CmpC, *AddC;
1777 if (match(U, m_Add(m_Specific(A), m_APInt(AddC))) &&
1778 match(B, m_APInt(CmpC)) && *AddC == -(*CmpC)) {
1780 break;
1781 }
1782 }
1783 if (!Sub)
1784 return false;
1785
1787 TLI->getValueType(*DL, Sub->getType()),
1788 Sub->hasNUsesOrMore(1)))
1789 return false;
1790
1791 // We don't want to move around uses of condition values this late, so we
1792 // check if it is legal to create the call to the intrinsic in the basic
1793 // block containing the icmp.
1794 if (Sub->getParent() != Cmp->getParent() && !Sub->hasOneUse())
1795 return false;
1796
1797 if (!replaceMathCmpWithIntrinsic(Sub, Sub->getOperand(0), Sub->getOperand(1),
1798 Cmp, Intrinsic::usub_with_overflow))
1799 return false;
1800
1801 // Reset callers - do not crash by iterating over a dead instruction.
1802 ModifiedDT = ModifyDT::ModifyInstDT;
1803 return true;
1804}
1805
1806// Decanonicalizes icmp+ctpop power-of-two test if ctpop is slow.
1807// The same transformation exists in DAG combiner, but we repeat it here because
1808// DAG builder can break the pattern by moving icmp into a successor block.
1809bool CodeGenPrepare::unfoldPowerOf2Test(CmpInst *Cmp) {
1810 CmpPredicate Pred;
1811 Value *X;
1812 const APInt *C;
1813
1814 // (icmp (ctpop x), c)
1815 if (!match(Cmp, m_ICmp(Pred, m_Ctpop(m_Value(X)), m_APIntAllowPoison(C))))
1816 return false;
1817
1818 // We're only interested in "is power of 2 [or zero]" patterns.
1819 bool IsStrictlyPowerOf2Test = ICmpInst::isEquality(Pred) && *C == 1;
1820 bool IsPowerOf2OrZeroTest = (Pred == CmpInst::ICMP_ULT && *C == 2) ||
1821 (Pred == CmpInst::ICMP_UGT && *C == 1);
1822 if (!IsStrictlyPowerOf2Test && !IsPowerOf2OrZeroTest)
1823 return false;
1824
1825 // Some targets have better codegen for `ctpop(x) u</u>= 2/1`than for
1826 // `ctpop(x) ==/!= 1`. If ctpop is fast, only try changing the comparison,
1827 // and otherwise expand ctpop into a few simple instructions.
1828 Type *OpTy = X->getType();
1829 if (TLI->isCtpopFast(TLI->getValueType(*DL, OpTy))) {
1830 // Look for `ctpop(x) ==/!= 1`, where `ctpop(x)` is known to be non-zero.
1831 if (!IsStrictlyPowerOf2Test || !isKnownNonZero(Cmp->getOperand(0), *DL))
1832 return false;
1833
1834 // ctpop(x) == 1 -> ctpop(x) u< 2
1835 // ctpop(x) != 1 -> ctpop(x) u> 1
1836 if (Pred == ICmpInst::ICMP_EQ) {
1837 Cmp->setOperand(1, ConstantInt::get(OpTy, 2));
1838 Cmp->setPredicate(ICmpInst::ICMP_ULT);
1839 } else {
1840 Cmp->setPredicate(ICmpInst::ICMP_UGT);
1841 }
1842 return true;
1843 }
1844
1845 Value *NewCmp;
1846 if (IsPowerOf2OrZeroTest ||
1847 (IsStrictlyPowerOf2Test && isKnownNonZero(Cmp->getOperand(0), *DL))) {
1848 // ctpop(x) u< 2 -> (x & (x - 1)) == 0
1849 // ctpop(x) u> 1 -> (x & (x - 1)) != 0
1850 IRBuilder<> Builder(Cmp);
1851 Value *Sub = Builder.CreateAdd(X, Constant::getAllOnesValue(OpTy));
1852 Value *And = Builder.CreateAnd(X, Sub);
1853 CmpInst::Predicate NewPred =
1854 (Pred == CmpInst::ICMP_ULT || Pred == CmpInst::ICMP_EQ)
1856 : CmpInst::ICMP_NE;
1857 NewCmp = Builder.CreateICmp(NewPred, And, ConstantInt::getNullValue(OpTy));
1858 } else {
1859 // ctpop(x) == 1 -> (x ^ (x - 1)) u> (x - 1)
1860 // ctpop(x) != 1 -> (x ^ (x - 1)) u<= (x - 1)
1861 IRBuilder<> Builder(Cmp);
1862 Value *Sub = Builder.CreateAdd(X, Constant::getAllOnesValue(OpTy));
1863 Value *Xor = Builder.CreateXor(X, Sub);
1864 CmpInst::Predicate NewPred =
1866 NewCmp = Builder.CreateICmp(NewPred, Xor, Sub);
1867 }
1868
1869 Cmp->replaceAllUsesWith(NewCmp);
1871 return true;
1872}
1873
1874/// Sink the given CmpInst into user blocks to reduce the number of virtual
1875/// registers that must be created and coalesced. This is a clear win except on
1876/// targets with multiple condition code registers (PowerPC), where it might
1877/// lose; some adjustment may be wanted there.
1878///
1879/// Return true if any changes are made.
1880static bool sinkCmpExpression(CmpInst *Cmp, const TargetLowering &TLI,
1881 const DataLayout &DL) {
1882 if (TLI.hasMultipleConditionRegisters(EVT::getEVT(Cmp->getType())))
1883 return false;
1884
1885 // Avoid sinking soft-FP comparisons, since this can move them into a loop.
1886 if (TLI.useSoftFloat() && isa<FCmpInst>(Cmp))
1887 return false;
1888
1889 bool UsedInPhiOrCurrentBlock = any_of(Cmp->users(), [Cmp](User *U) {
1890 return isa<PHINode>(U) ||
1891 cast<Instruction>(U)->getParent() == Cmp->getParent();
1892 });
1893
1894 // Avoid sinking larger than legal integer comparisons unless its ONLY used in
1895 // another BB.
1896 if (UsedInPhiOrCurrentBlock && Cmp->getOperand(0)->getType()->isIntegerTy() &&
1897 Cmp->getOperand(0)->getType()->getScalarSizeInBits() >
1898 DL.getLargestLegalIntTypeSizeInBits())
1899 return false;
1900
1901 // Only insert a cmp in each block once.
1903
1904 bool MadeChange = false;
1905 for (Value::user_iterator UI = Cmp->user_begin(), E = Cmp->user_end();
1906 UI != E;) {
1907 Use &TheUse = UI.getUse();
1909
1910 // Preincrement use iterator so we don't invalidate it.
1911 ++UI;
1912
1913 // Don't bother for PHI nodes.
1914 if (isa<PHINode>(User))
1915 continue;
1916
1917 // Figure out which BB this cmp is used in.
1918 BasicBlock *UserBB = User->getParent();
1919 BasicBlock *DefBB = Cmp->getParent();
1920
1921 // If this user is in the same block as the cmp, don't change the cmp.
1922 if (UserBB == DefBB)
1923 continue;
1924
1925 // If we have already inserted a cmp into this block, use it.
1926 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
1927
1928 if (!InsertedCmp) {
1929 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1930 assert(InsertPt != UserBB->end());
1931 InsertedCmp = CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(),
1932 Cmp->getOperand(0), Cmp->getOperand(1), "");
1933 InsertedCmp->insertBefore(*UserBB, InsertPt);
1934 // Propagate the debug info.
1935 InsertedCmp->setDebugLoc(Cmp->getDebugLoc());
1936 }
1937
1938 // Replace a use of the cmp with a use of the new cmp.
1939 TheUse = InsertedCmp;
1940 MadeChange = true;
1941 ++NumCmpUses;
1942 }
1943
1944 // If we removed all uses, nuke the cmp.
1945 if (Cmp->use_empty()) {
1946 Cmp->eraseFromParent();
1947 MadeChange = true;
1948 }
1949
1950 return MadeChange;
1951}
1952
1953/// For pattern like:
1954///
1955/// DomCond = icmp sgt/slt CmpOp0, CmpOp1 (might not be in DomBB)
1956/// ...
1957/// DomBB:
1958/// ...
1959/// br DomCond, TrueBB, CmpBB
1960/// CmpBB: (with DomBB being the single predecessor)
1961/// ...
1962/// Cmp = icmp eq CmpOp0, CmpOp1
1963/// ...
1964///
1965/// It would use two comparison on targets that lowering of icmp sgt/slt is
1966/// different from lowering of icmp eq (PowerPC). This function try to convert
1967/// 'Cmp = icmp eq CmpOp0, CmpOp1' to ' Cmp = icmp slt/sgt CmpOp0, CmpOp1'.
1968/// After that, DomCond and Cmp can use the same comparison so reduce one
1969/// comparison.
1970///
1971/// Return true if any changes are made.
1973 const TargetLowering &TLI) {
1975 return false;
1976
1977 ICmpInst::Predicate Pred = Cmp->getPredicate();
1978 if (Pred != ICmpInst::ICMP_EQ)
1979 return false;
1980
1981 // If icmp eq has users other than CondBrInst and SelectInst, converting it to
1982 // icmp slt/sgt would introduce more redundant LLVM IR.
1983 for (User *U : Cmp->users()) {
1984 if (isa<CondBrInst>(U))
1985 continue;
1986 if (isa<SelectInst>(U) && cast<SelectInst>(U)->getCondition() == Cmp)
1987 continue;
1988 return false;
1989 }
1990
1991 // This is a cheap/incomplete check for dominance - just match a single
1992 // predecessor with a conditional branch.
1993 BasicBlock *CmpBB = Cmp->getParent();
1994 BasicBlock *DomBB = CmpBB->getSinglePredecessor();
1995 if (!DomBB)
1996 return false;
1997
1998 // We want to ensure that the only way control gets to the comparison of
1999 // interest is that a less/greater than comparison on the same operands is
2000 // false.
2001 Value *DomCond;
2002 BasicBlock *TrueBB, *FalseBB;
2003 if (!match(DomBB->getTerminator(), m_Br(m_Value(DomCond), TrueBB, FalseBB)))
2004 return false;
2005 if (CmpBB != FalseBB)
2006 return false;
2007
2008 Value *CmpOp0 = Cmp->getOperand(0), *CmpOp1 = Cmp->getOperand(1);
2009 CmpPredicate DomPred;
2010 if (!match(DomCond, m_ICmp(DomPred, m_Specific(CmpOp0), m_Specific(CmpOp1))))
2011 return false;
2012 if (DomPred != ICmpInst::ICMP_SGT && DomPred != ICmpInst::ICMP_SLT)
2013 return false;
2014
2015 // Convert the equality comparison to the opposite of the dominating
2016 // comparison and swap the direction for all branch/select users.
2017 // We have conceptually converted:
2018 // Res = (a < b) ? <LT_RES> : (a == b) ? <EQ_RES> : <GT_RES>;
2019 // to
2020 // Res = (a < b) ? <LT_RES> : (a > b) ? <GT_RES> : <EQ_RES>;
2021 // And similarly for branches.
2022 for (User *U : Cmp->users()) {
2023 if (auto *BI = dyn_cast<CondBrInst>(U)) {
2024 BI->swapSuccessors();
2025 continue;
2026 }
2027 if (auto *SI = dyn_cast<SelectInst>(U)) {
2028 // Swap operands
2029 SI->swapValues();
2030 SI->swapProfMetadata();
2031 continue;
2032 }
2033 llvm_unreachable("Must be a branch or a select");
2034 }
2035 Cmp->setPredicate(CmpInst::getSwappedPredicate(DomPred));
2036 return true;
2037}
2038
2039/// Many architectures use the same instruction for both subtract and cmp. Try
2040/// to swap cmp operands to match subtract operations to allow for CSE.
2042 Value *Op0 = Cmp->getOperand(0);
2043 Value *Op1 = Cmp->getOperand(1);
2044 if (!Op0->getType()->isIntegerTy() || isa<Constant>(Op0) ||
2045 isa<Constant>(Op1) || Op0 == Op1)
2046 return false;
2047
2048 // If a subtract already has the same operands as a compare, swapping would be
2049 // bad. If a subtract has the same operands as a compare but in reverse order,
2050 // then swapping is good.
2051 int GoodToSwap = 0;
2052 unsigned NumInspected = 0;
2053 for (const User *U : Op0->users()) {
2054 // Avoid walking many users.
2055 if (++NumInspected > 128)
2056 return false;
2057 if (match(U, m_Sub(m_Specific(Op1), m_Specific(Op0))))
2058 GoodToSwap++;
2059 else if (match(U, m_Sub(m_Specific(Op0), m_Specific(Op1))))
2060 GoodToSwap--;
2061 }
2062
2063 if (GoodToSwap > 0) {
2064 Cmp->swapOperands();
2065 return true;
2066 }
2067 return false;
2068}
2069
2070static bool foldFCmpToFPClassTest(CmpInst *Cmp, const TargetLowering &TLI,
2071 const DataLayout &DL) {
2072 FCmpInst *FCmp = dyn_cast<FCmpInst>(Cmp);
2073 if (!FCmp)
2074 return false;
2075
2076 // Don't fold if the target offers free fabs and the predicate is legal.
2077 EVT VT = TLI.getValueType(DL, Cmp->getOperand(0)->getType());
2078 if (TLI.isFAbsFree(VT) &&
2080 VT.getSimpleVT()))
2081 return false;
2082
2083 // Reverse the canonicalization if it is a FP class test
2084 auto ShouldReverseTransform = [](FPClassTest ClassTest) {
2085 return ClassTest == fcInf || ClassTest == (fcInf | fcNan);
2086 };
2087 auto [ClassVal, ClassTest] =
2088 fcmpToClassTest(FCmp->getPredicate(), *FCmp->getParent()->getParent(),
2089 FCmp->getOperand(0), FCmp->getOperand(1));
2090 if (!ClassVal)
2091 return false;
2092
2093 if (!ShouldReverseTransform(ClassTest) && !ShouldReverseTransform(~ClassTest))
2094 return false;
2095
2096 IRBuilder<> Builder(Cmp);
2097 Value *IsFPClass = Builder.createIsFPClass(ClassVal, ClassTest);
2098 Cmp->replaceAllUsesWith(IsFPClass);
2100 return true;
2101}
2102
2104 Instruction *Rem, const LoopInfo *LI, Value *&RemAmtOut, Value *&AddInstOut,
2105 Value *&AddOffsetOut, PHINode *&LoopIncrPNOut) {
2106 Value *Incr, *RemAmt;
2107 // NB: If RemAmt is a power of 2 it *should* have been transformed by now.
2108 if (!match(Rem, m_URem(m_Value(Incr), m_Value(RemAmt))))
2109 return false;
2110
2111 Value *AddInst, *AddOffset;
2112 // Find out loop increment PHI.
2113 PHINode *PN = dyn_cast<PHINode>(Incr);
2114 if (PN != nullptr) {
2115 AddInst = nullptr;
2116 AddOffset = nullptr;
2117 } else {
2118 // Search through a NUW add on top of the loop increment.
2119 if (!match(Incr, m_c_NUWAdd(m_Phi(PN), m_Value(AddOffset))))
2120 return false;
2121 AddInst = Incr;
2122 }
2123
2124 if (!PN)
2125 return false;
2126
2127 // This isn't strictly necessary, what we really need is one increment and any
2128 // amount of initial values all being the same.
2129 if (PN->getNumIncomingValues() != 2)
2130 return false;
2131
2132 // Only trivially analyzable loops.
2133 Loop *L = LI->getLoopFor(PN->getParent());
2134 if (!L || !L->getLoopPreheader() || !L->getLoopLatch())
2135 return false;
2136
2137 // Req that the remainder is in the loop
2138 if (!L->contains(Rem))
2139 return false;
2140
2141 // Only works if the remainder amount is a loop invaraint
2142 if (!L->isLoopInvariant(RemAmt))
2143 return false;
2144
2145 // Only works if the AddOffset is a loop invaraint
2146 if (AddOffset && !L->isLoopInvariant(AddOffset))
2147 return false;
2148
2149 // Is the PHI a loop increment?
2150 auto LoopIncrInfo = getIVIncrement(PN, LI);
2151 if (!LoopIncrInfo)
2152 return false;
2153
2154 // We need remainder_amount % increment_amount to be zero. Increment of one
2155 // satisfies that without any special logic and is overwhelmingly the common
2156 // case.
2157 if (!match(LoopIncrInfo->second, m_One()))
2158 return false;
2159
2160 // Need the increment to not overflow.
2161 if (!match(LoopIncrInfo->first, m_c_NUWAdd(m_Specific(PN), m_Value())))
2162 return false;
2163
2164 // Set output variables.
2165 RemAmtOut = RemAmt;
2166 LoopIncrPNOut = PN;
2167 AddInstOut = AddInst;
2168 AddOffsetOut = AddOffset;
2169
2170 return true;
2171}
2172
2173// Try to transform:
2174//
2175// for(i = Start; i < End; ++i)
2176// Rem = (i nuw+ IncrLoopInvariant) u% RemAmtLoopInvariant;
2177//
2178// ->
2179//
2180// Rem = (Start nuw+ IncrLoopInvariant) % RemAmtLoopInvariant;
2181// for(i = Start; i < End; ++i, ++rem)
2182// Rem = rem == RemAmtLoopInvariant ? 0 : Rem;
2184 const LoopInfo *LI,
2186 bool IsHuge) {
2187 Value *AddOffset, *RemAmt, *AddInst;
2188 PHINode *LoopIncrPN;
2189 if (!isRemOfLoopIncrementWithLoopInvariant(Rem, LI, RemAmt, AddInst,
2190 AddOffset, LoopIncrPN))
2191 return false;
2192
2193 // Only non-constant remainder as the extra IV is probably not profitable
2194 // in that case.
2195 //
2196 // Potential TODO(1): `urem` of a const ends up as `mul` + `shift` + `add`. If
2197 // we can rule out register pressure and ensure this `urem` is executed each
2198 // iteration, its probably profitable to handle the const case as well.
2199 //
2200 // Potential TODO(2): Should we have a check for how "nested" this remainder
2201 // operation is? The new code runs every iteration so if the remainder is
2202 // guarded behind unlikely conditions this might not be worth it.
2203 if (match(RemAmt, m_ImmConstant()))
2204 return false;
2205
2206 Loop *L = LI->getLoopFor(LoopIncrPN->getParent());
2207 Value *Start = LoopIncrPN->getIncomingValueForBlock(L->getLoopPreheader());
2208 // If we have add create initial value for remainder.
2209 // The logic here is:
2210 // (urem (add nuw Start, IncrLoopInvariant), RemAmtLoopInvariant
2211 //
2212 // Only proceed if the expression simplifies (otherwise we can't fully
2213 // optimize out the urem).
2214 if (AddInst) {
2215 assert(AddOffset && "We found an add but missing values");
2216 // Without dom-condition/assumption cache we aren't likely to get much out
2217 // of a context instruction.
2218 Start = simplifyAddInst(Start, AddOffset,
2219 match(AddInst, m_NSWAdd(m_Value(), m_Value())),
2220 /*IsNUW=*/true, *DL);
2221 if (!Start)
2222 return false;
2223 }
2224
2225 // If we can't fully optimize out the `rem`, skip this transform.
2226 Start = simplifyURemInst(Start, RemAmt, *DL);
2227 if (!Start)
2228 return false;
2229
2230 // Create new remainder with induction variable.
2231 Type *Ty = Rem->getType();
2232 IRBuilder<> Builder(Rem->getContext());
2233
2234 Builder.SetInsertPoint(LoopIncrPN);
2235 PHINode *NewRem = Builder.CreatePHI(Ty, 2);
2236
2237 Builder.SetInsertPoint(cast<Instruction>(
2238 LoopIncrPN->getIncomingValueForBlock(L->getLoopLatch())));
2239 // `(add (urem x, y), 1)` is always nuw.
2240 Value *RemAdd = Builder.CreateNUWAdd(NewRem, ConstantInt::get(Ty, 1));
2241 Value *RemCmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, RemAdd, RemAmt);
2242 Value *RemSel =
2243 Builder.CreateSelect(RemCmp, Constant::getNullValue(Ty), RemAdd);
2244
2245 NewRem->addIncoming(Start, L->getLoopPreheader());
2246 NewRem->addIncoming(RemSel, L->getLoopLatch());
2247
2248 // Insert all touched BBs.
2249 FreshBBs.insert(LoopIncrPN->getParent());
2250 FreshBBs.insert(L->getLoopLatch());
2251 FreshBBs.insert(Rem->getParent());
2252 if (AddInst)
2253 FreshBBs.insert(cast<Instruction>(AddInst)->getParent());
2254 replaceAllUsesWith(Rem, NewRem, FreshBBs, IsHuge);
2255 Rem->eraseFromParent();
2256 if (AddInst && AddInst->use_empty())
2257 cast<Instruction>(AddInst)->eraseFromParent();
2258 return true;
2259}
2260
2261bool CodeGenPrepare::optimizeURem(Instruction *Rem) {
2262 if (foldURemOfLoopIncrement(Rem, DL, LI, FreshBBs, IsHugeFunc))
2263 return true;
2264 return false;
2265}
2266
2267bool CodeGenPrepare::optimizeCmp(CmpInst *Cmp, ModifyDT &ModifiedDT) {
2268 if (sinkCmpExpression(Cmp, *TLI, *DL))
2269 return true;
2270
2271 if (combineToUAddWithOverflow(Cmp, ModifiedDT))
2272 return true;
2273
2274 if (combineToUSubWithOverflow(Cmp, ModifiedDT))
2275 return true;
2276
2277 if (unfoldPowerOf2Test(Cmp))
2278 return true;
2279
2280 if (foldICmpWithDominatingICmp(Cmp, *TLI))
2281 return true;
2282
2284 return true;
2285
2286 if (foldFCmpToFPClassTest(Cmp, *TLI, *DL))
2287 return true;
2288
2289 return false;
2290}
2291
2292/// Duplicate and sink the given 'and' instruction into user blocks where it is
2293/// used in a compare to allow isel to generate better code for targets where
2294/// this operation can be combined.
2295///
2296/// Return true if any changes are made.
2298 SetOfInstrs &InsertedInsts) {
2299 // Double-check that we're not trying to optimize an instruction that was
2300 // already optimized by some other part of this pass.
2301 assert(!InsertedInsts.count(AndI) &&
2302 "Attempting to optimize already optimized and instruction");
2303 (void)InsertedInsts;
2304
2305 // Nothing to do for single use in same basic block.
2306 if (AndI->hasOneUse() &&
2307 AndI->getParent() == cast<Instruction>(*AndI->user_begin())->getParent())
2308 return false;
2309
2310 // Try to avoid cases where sinking/duplicating is likely to increase register
2311 // pressure.
2312 if (!isa<ConstantInt>(AndI->getOperand(0)) &&
2313 !isa<ConstantInt>(AndI->getOperand(1)) &&
2314 AndI->getOperand(0)->hasOneUse() && AndI->getOperand(1)->hasOneUse())
2315 return false;
2316
2317 for (auto *U : AndI->users()) {
2319
2320 // Only sink 'and' feeding icmp with 0.
2321 if (!isa<ICmpInst>(User))
2322 return false;
2323
2324 auto *CmpC = dyn_cast<ConstantInt>(User->getOperand(1));
2325 if (!CmpC || !CmpC->isZero())
2326 return false;
2327 }
2328
2329 if (!TLI.isMaskAndCmp0FoldingBeneficial(*AndI))
2330 return false;
2331
2332 LLVM_DEBUG(dbgs() << "found 'and' feeding only icmp 0;\n");
2333 LLVM_DEBUG(AndI->getParent()->dump());
2334
2335 // Push the 'and' into the same block as the icmp 0. There should only be
2336 // one (icmp (and, 0)) in each block, since CSE/GVN should have removed any
2337 // others, so we don't need to keep track of which BBs we insert into.
2338 for (Value::user_iterator UI = AndI->user_begin(), E = AndI->user_end();
2339 UI != E;) {
2340 Use &TheUse = UI.getUse();
2342
2343 // Preincrement use iterator so we don't invalidate it.
2344 ++UI;
2345
2346 LLVM_DEBUG(dbgs() << "sinking 'and' use: " << *User << "\n");
2347
2348 // Keep the 'and' in the same place if the use is already in the same block.
2349 Instruction *InsertPt =
2350 User->getParent() == AndI->getParent() ? AndI : User;
2351 Instruction *InsertedAnd = BinaryOperator::Create(
2352 Instruction::And, AndI->getOperand(0), AndI->getOperand(1), "",
2353 InsertPt->getIterator());
2354 // Propagate the debug info.
2355 InsertedAnd->setDebugLoc(AndI->getDebugLoc());
2356
2357 // Replace a use of the 'and' with a use of the new 'and'.
2358 TheUse = InsertedAnd;
2359 ++NumAndUses;
2360 LLVM_DEBUG(User->getParent()->dump());
2361 }
2362
2363 // We removed all uses, nuke the and.
2364 AndI->eraseFromParent();
2365 return true;
2366}
2367
2368/// Check if the candidates could be combined with a shift instruction, which
2369/// includes:
2370/// 1. Truncate instruction
2371/// 2. And instruction and the imm is a mask of the low bits:
2372/// imm & (imm+1) == 0
2374 if (!isa<TruncInst>(User)) {
2375 if (User->getOpcode() != Instruction::And ||
2377 return false;
2378
2379 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
2380
2381 if ((Cimm & (Cimm + 1)).getBoolValue())
2382 return false;
2383 }
2384 return true;
2385}
2386
2387/// Sink both shift and truncate instruction to the use of truncate's BB.
2388static bool
2391 const TargetLowering &TLI, const DataLayout &DL) {
2392 BasicBlock *UserBB = User->getParent();
2394 auto *TruncI = cast<TruncInst>(User);
2395 bool MadeChange = false;
2396
2397 for (Value::user_iterator TruncUI = TruncI->user_begin(),
2398 TruncE = TruncI->user_end();
2399 TruncUI != TruncE;) {
2400
2401 Use &TruncTheUse = TruncUI.getUse();
2402 Instruction *TruncUser = cast<Instruction>(*TruncUI);
2403 // Preincrement use iterator so we don't invalidate it.
2404
2405 ++TruncUI;
2406
2407 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
2408 if (!ISDOpcode)
2409 continue;
2410
2411 // If the use is actually a legal node, there will not be an
2412 // implicit truncate.
2413 // FIXME: always querying the result type is just an
2414 // approximation; some nodes' legality is determined by the
2415 // operand or other means. There's no good way to find out though.
2417 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
2418 continue;
2419
2420 // Don't bother for PHI nodes.
2421 if (isa<PHINode>(TruncUser))
2422 continue;
2423
2424 BasicBlock *TruncUserBB = TruncUser->getParent();
2425
2426 if (UserBB == TruncUserBB)
2427 continue;
2428
2429 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
2430 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
2431
2432 if (!InsertedShift && !InsertedTrunc) {
2433 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
2434 assert(InsertPt != TruncUserBB->end());
2435 // Sink the shift
2436 if (ShiftI->getOpcode() == Instruction::AShr)
2437 InsertedShift =
2438 BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "");
2439 else
2440 InsertedShift =
2441 BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "");
2442 InsertedShift->setDebugLoc(ShiftI->getDebugLoc());
2443 InsertedShift->insertBefore(*TruncUserBB, InsertPt);
2444
2445 // Sink the trunc
2446 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
2447 TruncInsertPt++;
2448 // It will go ahead of any debug-info.
2449 TruncInsertPt.setHeadBit(true);
2450 assert(TruncInsertPt != TruncUserBB->end());
2451
2452 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
2453 TruncI->getType(), "");
2454 InsertedTrunc->insertBefore(*TruncUserBB, TruncInsertPt);
2455 InsertedTrunc->setDebugLoc(TruncI->getDebugLoc());
2456
2457 MadeChange = true;
2458
2459 TruncTheUse = InsertedTrunc;
2460 }
2461 }
2462 return MadeChange;
2463}
2464
2465/// Sink the shift *right* instruction into user blocks if the uses could
2466/// potentially be combined with this shift instruction and generate BitExtract
2467/// instruction. It will only be applied if the architecture supports BitExtract
2468/// instruction. Here is an example:
2469/// BB1:
2470/// %x.extract.shift = lshr i64 %arg1, 32
2471/// BB2:
2472/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
2473/// ==>
2474///
2475/// BB2:
2476/// %x.extract.shift.1 = lshr i64 %arg1, 32
2477/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
2478///
2479/// CodeGen will recognize the pattern in BB2 and generate BitExtract
2480/// instruction.
2481/// Return true if any changes are made.
2483 const TargetLowering &TLI,
2484 const DataLayout &DL) {
2485 BasicBlock *DefBB = ShiftI->getParent();
2486
2487 /// Only insert instructions in each block once.
2489
2490 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
2491
2492 bool MadeChange = false;
2493 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
2494 UI != E;) {
2495 Use &TheUse = UI.getUse();
2497 // Preincrement use iterator so we don't invalidate it.
2498 ++UI;
2499
2500 // Don't bother for PHI nodes.
2501 if (isa<PHINode>(User))
2502 continue;
2503
2505 continue;
2506
2507 BasicBlock *UserBB = User->getParent();
2508
2509 if (UserBB == DefBB) {
2510 // If the shift and truncate instruction are in the same BB. The use of
2511 // the truncate(TruncUse) may still introduce another truncate if not
2512 // legal. In this case, we would like to sink both shift and truncate
2513 // instruction to the BB of TruncUse.
2514 // for example:
2515 // BB1:
2516 // i64 shift.result = lshr i64 opnd, imm
2517 // trunc.result = trunc shift.result to i16
2518 //
2519 // BB2:
2520 // ----> We will have an implicit truncate here if the architecture does
2521 // not have i16 compare.
2522 // cmp i16 trunc.result, opnd2
2523 //
2524 if (isa<TruncInst>(User) &&
2525 shiftIsLegal
2526 // If the type of the truncate is legal, no truncate will be
2527 // introduced in other basic blocks.
2528 && (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
2529 MadeChange =
2530 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
2531
2532 continue;
2533 }
2534 // If we have already inserted a shift into this block, use it.
2535 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
2536
2537 if (!InsertedShift) {
2538 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
2539 assert(InsertPt != UserBB->end());
2540
2541 if (ShiftI->getOpcode() == Instruction::AShr)
2542 InsertedShift =
2543 BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "");
2544 else
2545 InsertedShift =
2546 BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "");
2547 InsertedShift->insertBefore(*UserBB, InsertPt);
2548 InsertedShift->setDebugLoc(ShiftI->getDebugLoc());
2549
2550 MadeChange = true;
2551 }
2552
2553 // Replace a use of the shift with a use of the new shift.
2554 TheUse = InsertedShift;
2555 }
2556
2557 // If we removed all uses, or there are none, nuke the shift.
2558 if (ShiftI->use_empty()) {
2559 salvageDebugInfo(*ShiftI);
2560 ShiftI->eraseFromParent();
2561 MadeChange = true;
2562 }
2563
2564 return MadeChange;
2565}
2566
2567/// If counting leading or trailing zeros is an expensive operation and a zero
2568/// input is defined, add a check for zero to avoid calling the intrinsic.
2569///
2570/// We want to transform:
2571/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
2572///
2573/// into:
2574/// entry:
2575/// %cmpz = icmp eq i64 %A, 0
2576/// br i1 %cmpz, label %cond.end, label %cond.false
2577/// cond.false:
2578/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
2579/// br label %cond.end
2580/// cond.end:
2581/// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
2582///
2583/// If the transform is performed, return true and set ModifiedDT to true.
2584static bool despeculateCountZeros(IntrinsicInst *CountZeros,
2585 DomTreeUpdater *DTU, LoopInfo *LI,
2586 const TargetLowering *TLI,
2587 const DataLayout *DL, ModifyDT &ModifiedDT,
2589 bool IsHugeFunc) {
2590 // If a zero input is undefined, it doesn't make sense to despeculate that.
2591 if (match(CountZeros->getOperand(1), m_One()))
2592 return false;
2593
2594 // If it's cheap to speculate, there's nothing to do.
2595 Type *Ty = CountZeros->getType();
2596 auto IntrinsicID = CountZeros->getIntrinsicID();
2597 if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz(Ty)) ||
2598 (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz(Ty)))
2599 return false;
2600
2601 // Only handle scalar cases. Anything else requires too much work.
2602 unsigned SizeInBits = Ty->getScalarSizeInBits();
2603 if (Ty->isVectorTy())
2604 return false;
2605
2606 // Bail if the value is never zero.
2607 Use &Op = CountZeros->getOperandUse(0);
2608 if (isKnownNonZero(Op, *DL))
2609 return false;
2610
2611 // The intrinsic will be sunk behind a compare against zero and branch.
2612 BasicBlock *StartBlock = CountZeros->getParent();
2613 BasicBlock *CallBlock = SplitBlock(StartBlock, CountZeros, DTU, LI,
2614 /* MSSAU */ nullptr, "cond.false");
2615 if (IsHugeFunc)
2616 FreshBBs.insert(CallBlock);
2617
2618 // Create another block after the count zero intrinsic. A PHI will be added
2619 // in this block to select the result of the intrinsic or the bit-width
2620 // constant if the input to the intrinsic is zero.
2621 BasicBlock::iterator SplitPt = std::next(BasicBlock::iterator(CountZeros));
2622 // Any debug-info after CountZeros should not be included.
2623 SplitPt.setHeadBit(true);
2624 BasicBlock *EndBlock = SplitBlock(CallBlock, &*SplitPt, DTU, LI,
2625 /* MSSAU */ nullptr, "cond.end");
2626 if (IsHugeFunc)
2627 FreshBBs.insert(EndBlock);
2628
2629 // Set up a builder to create a compare, conditional branch, and PHI.
2630 IRBuilder<> Builder(CountZeros->getContext());
2631 Builder.SetInsertPoint(StartBlock->getTerminator());
2632 Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
2633
2634 // Replace the unconditional branch that was created by the first split with
2635 // a compare against zero and a conditional branch.
2636 Value *Zero = Constant::getNullValue(Ty);
2637 // Avoid introducing branch on poison. This also replaces the ctz operand.
2639 Op = Builder.CreateFreeze(Op, Op->getName() + ".fr");
2640 Value *Cmp = Builder.CreateICmpEQ(Op, Zero, "cmpz");
2641 Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
2642 StartBlock->getTerminator()->eraseFromParent();
2643 DTU->applyUpdates({{DominatorTree::Insert, StartBlock, EndBlock}});
2644
2645 // Create a PHI in the end block to select either the output of the intrinsic
2646 // or the bit width of the operand.
2647 Builder.SetInsertPoint(EndBlock, EndBlock->begin());
2648 PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
2649 replaceAllUsesWith(CountZeros, PN, FreshBBs, IsHugeFunc);
2650 Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
2651 PN->addIncoming(BitWidth, StartBlock);
2652 PN->addIncoming(CountZeros, CallBlock);
2653
2654 // We are explicitly handling the zero case, so we can set the intrinsic's
2655 // undefined zero argument to 'true'. This will also prevent reprocessing the
2656 // intrinsic; we only despeculate when a zero input is defined.
2657 CountZeros->setArgOperand(1, Builder.getTrue());
2658 ModifiedDT = ModifyDT::ModifyBBDT;
2659 return true;
2660}
2661
2662bool CodeGenPrepare::optimizeCallInst(CallInst *CI, ModifyDT &ModifiedDT) {
2663 BasicBlock *BB = CI->getParent();
2664
2665 // Sink address computing for memory operands into the block.
2666 if (CI->isInlineAsm() && optimizeInlineAsmInst(CI))
2667 return true;
2668
2669 // Align the pointer arguments to this call if the target thinks it's a good
2670 // idea
2671 unsigned MinSize;
2672 Align PrefAlign;
2673 if (TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
2674 for (auto &Arg : CI->args()) {
2675 // We want to align both objects whose address is used directly and
2676 // objects whose address is used in casts and GEPs, though it only makes
2677 // sense for GEPs if the offset is a multiple of the desired alignment and
2678 // if size - offset meets the size threshold.
2679 if (!Arg->getType()->isPointerTy())
2680 continue;
2681 APInt Offset(DL->getIndexSizeInBits(
2682 cast<PointerType>(Arg->getType())->getAddressSpace()),
2683 0);
2684 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
2685 uint64_t Offset2 = Offset.getLimitedValue();
2686 if (!isAligned(PrefAlign, Offset2))
2687 continue;
2688 AllocaInst *AI;
2689 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlign() < PrefAlign) {
2690 std::optional<TypeSize> AllocaSize = AI->getAllocationSize(*DL);
2691 if (AllocaSize && AllocaSize->getKnownMinValue() >= MinSize + Offset2)
2692 AI->setAlignment(PrefAlign);
2693 }
2694 // Global variables can only be aligned if they are defined in this
2695 // object (i.e. they are uniquely initialized in this object), and
2696 // over-aligning global variables that have an explicit section is
2697 // forbidden.
2698 GlobalVariable *GV;
2699 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
2700 GV->getPointerAlignment(*DL) < PrefAlign &&
2701 GV->getGlobalSize(*DL) >= MinSize + Offset2)
2702 GV->setAlignment(PrefAlign);
2703 }
2704 }
2705 // If this is a memcpy (or similar) then we may be able to improve the
2706 // alignment.
2707 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
2708 Align DestAlign = getKnownAlignment(MI->getDest(), *DL);
2709 MaybeAlign MIDestAlign = MI->getDestAlign();
2710 if (!MIDestAlign || DestAlign > *MIDestAlign)
2711 MI->setDestAlignment(DestAlign);
2712 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
2713 MaybeAlign MTISrcAlign = MTI->getSourceAlign();
2714 Align SrcAlign = getKnownAlignment(MTI->getSource(), *DL);
2715 if (!MTISrcAlign || SrcAlign > *MTISrcAlign)
2716 MTI->setSourceAlignment(SrcAlign);
2717 }
2718 }
2719
2720 // If we have a cold call site, try to sink addressing computation into the
2721 // cold block. This interacts with our handling for loads and stores to
2722 // ensure that we can fold all uses of a potential addressing computation
2723 // into their uses. TODO: generalize this to work over profiling data
2724 if (CI->hasFnAttr(Attribute::Cold) &&
2725 !llvm::shouldOptimizeForSize(BB, PSI, BFI))
2726 for (auto &Arg : CI->args()) {
2727 if (!Arg->getType()->isPointerTy())
2728 continue;
2729 unsigned AS = Arg->getType()->getPointerAddressSpace();
2730 if (optimizeMemoryInst(CI, Arg, Arg->getType(), AS))
2731 return true;
2732 }
2733
2734 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
2735 if (II) {
2736 switch (II->getIntrinsicID()) {
2737 default:
2738 break;
2739 case Intrinsic::assume:
2740 llvm_unreachable("llvm.assume should have been removed already");
2741 case Intrinsic::allow_runtime_check:
2742 case Intrinsic::allow_ubsan_check:
2743 case Intrinsic::experimental_widenable_condition: {
2744 // Give up on future widening opportunities so that we can fold away dead
2745 // paths and merge blocks before going into block-local instruction
2746 // selection.
2747 if (II->use_empty()) {
2748 II->eraseFromParent();
2749 return true;
2750 }
2751 Constant *RetVal = ConstantInt::getTrue(II->getContext());
2752 resetIteratorIfInvalidatedWhileCalling(BB, [&]() {
2753 replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
2754 });
2755 return true;
2756 }
2757 case Intrinsic::objectsize:
2758 llvm_unreachable("llvm.objectsize.* should have been lowered already");
2759 case Intrinsic::is_constant:
2760 llvm_unreachable("llvm.is.constant.* should have been lowered already");
2761 case Intrinsic::aarch64_stlxr:
2762 case Intrinsic::aarch64_stxr: {
2763 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
2764 if (!ExtVal || !ExtVal->hasOneUse() ||
2765 ExtVal->getParent() == CI->getParent())
2766 return false;
2767 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
2768 ExtVal->moveBefore(CI->getIterator());
2769 // Mark this instruction as "inserted by CGP", so that other
2770 // optimizations don't touch it.
2771 InsertedInsts.insert(ExtVal);
2772 return true;
2773 }
2774
2775 case Intrinsic::launder_invariant_group:
2776 case Intrinsic::strip_invariant_group: {
2777 Value *ArgVal = II->getArgOperand(0);
2778 auto it = LargeOffsetGEPMap.find(II);
2779 if (it != LargeOffsetGEPMap.end()) {
2780 // Merge entries in LargeOffsetGEPMap to reflect the RAUW.
2781 // Make sure not to have to deal with iterator invalidation
2782 // after possibly adding ArgVal to LargeOffsetGEPMap.
2783 auto GEPs = std::move(it->second);
2784 LargeOffsetGEPMap[ArgVal].append(GEPs.begin(), GEPs.end());
2785 LargeOffsetGEPMap.erase(II);
2786 }
2787
2788 replaceAllUsesWith(II, ArgVal, FreshBBs, IsHugeFunc);
2789 II->eraseFromParent();
2790 return true;
2791 }
2792 case Intrinsic::cttz:
2793 case Intrinsic::ctlz:
2794 // If counting zeros is expensive, try to avoid it.
2795 return despeculateCountZeros(II, DTU, LI, TLI, DL, ModifiedDT, FreshBBs,
2796 IsHugeFunc);
2797 case Intrinsic::fshl:
2798 case Intrinsic::fshr:
2799 return optimizeFunnelShift(II);
2800 case Intrinsic::masked_gather:
2801 return optimizeGatherScatterInst(II, II->getArgOperand(0));
2802 case Intrinsic::masked_scatter:
2803 return optimizeGatherScatterInst(II, II->getArgOperand(1));
2804 case Intrinsic::masked_load:
2805 // Treat v1X masked load as load X type.
2806 if (auto *VT = dyn_cast<FixedVectorType>(II->getType())) {
2807 if (VT->getNumElements() == 1) {
2808 Value *PtrVal = II->getArgOperand(0);
2809 unsigned AS = PtrVal->getType()->getPointerAddressSpace();
2810 if (optimizeMemoryInst(II, PtrVal, VT->getElementType(), AS))
2811 return true;
2812 }
2813 }
2814 return false;
2815 case Intrinsic::masked_store:
2816 // Treat v1X masked store as store X type.
2817 if (auto *VT =
2818 dyn_cast<FixedVectorType>(II->getArgOperand(0)->getType())) {
2819 if (VT->getNumElements() == 1) {
2820 Value *PtrVal = II->getArgOperand(1);
2821 unsigned AS = PtrVal->getType()->getPointerAddressSpace();
2822 if (optimizeMemoryInst(II, PtrVal, VT->getElementType(), AS))
2823 return true;
2824 }
2825 }
2826 return false;
2827 case Intrinsic::umul_with_overflow:
2828 return optimizeMulWithOverflow(II, /*IsSigned=*/false, ModifiedDT);
2829 case Intrinsic::smul_with_overflow:
2830 return optimizeMulWithOverflow(II, /*IsSigned=*/true, ModifiedDT);
2831 }
2832
2833 SmallVector<Value *, 2> PtrOps;
2834 Type *AccessTy;
2835 if (TLI->getAddrModeArguments(II, PtrOps, AccessTy))
2836 while (!PtrOps.empty()) {
2837 Value *PtrVal = PtrOps.pop_back_val();
2838 unsigned AS = PtrVal->getType()->getPointerAddressSpace();
2839 if (optimizeMemoryInst(II, PtrVal, AccessTy, AS))
2840 return true;
2841 }
2842 }
2843
2844 // From here on out we're working with named functions.
2845 auto *Callee = CI->getCalledFunction();
2846 if (!Callee)
2847 return false;
2848
2849 // Lower all default uses of _chk calls. This is very similar
2850 // to what InstCombineCalls does, but here we are only lowering calls
2851 // to fortified library functions (e.g. __memcpy_chk) that have the default
2852 // "don't know" as the objectsize. Anything else should be left alone.
2853 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
2854 IRBuilder<> Builder(CI);
2855 if (Value *V = Simplifier.optimizeCall(CI, Builder)) {
2856 replaceAllUsesWith(CI, V, FreshBBs, IsHugeFunc);
2857 CI->eraseFromParent();
2858 return true;
2859 }
2860
2861 // SCCP may have propagated, among other things, C++ static variables across
2862 // calls. If this happens to be the case, we may want to undo it in order to
2863 // avoid redundant pointer computation of the constant, as the function method
2864 // returning the constant needs to be executed anyways.
2865 auto GetUniformReturnValue = [](const Function *F) -> GlobalVariable * {
2866 if (!F->getReturnType()->isPointerTy())
2867 return nullptr;
2868
2869 GlobalVariable *UniformValue = nullptr;
2870 for (auto &BB : *F) {
2871 if (auto *RI = dyn_cast<ReturnInst>(BB.getTerminator())) {
2872 if (auto *V = dyn_cast<GlobalVariable>(RI->getReturnValue())) {
2873 if (!UniformValue)
2874 UniformValue = V;
2875 else if (V != UniformValue)
2876 return nullptr;
2877 } else {
2878 return nullptr;
2879 }
2880 }
2881 }
2882
2883 return UniformValue;
2884 };
2885
2886 if (Callee->hasExactDefinition()) {
2887 if (GlobalVariable *RV = GetUniformReturnValue(Callee)) {
2888 bool MadeChange = false;
2889 for (Use &U : make_early_inc_range(RV->uses())) {
2890 auto *I = dyn_cast<Instruction>(U.getUser());
2891 if (!I || I->getParent() != CI->getParent()) {
2892 // Limit to the same basic block to avoid extending the call-site live
2893 // range, which otherwise could increase register pressure.
2894 continue;
2895 }
2896 if (CI->comesBefore(I)) {
2897 U.set(CI);
2898 MadeChange = true;
2899 }
2900 }
2901
2902 return MadeChange;
2903 }
2904 }
2905
2906 return false;
2907}
2908
2910 const CallInst *CI) {
2911 assert(CI && CI->use_empty());
2912
2913 if (const auto *II = dyn_cast<IntrinsicInst>(CI))
2914 switch (II->getIntrinsicID()) {
2915 case Intrinsic::memset:
2916 case Intrinsic::memcpy:
2917 case Intrinsic::memmove:
2918 return true;
2919 default:
2920 return false;
2921 }
2922
2923 Function *Callee = CI->getCalledFunction();
2924 if (Callee && TLInfo)
2925 switch (TLInfo->getLibFunc(*Callee)) {
2926 case LibFunc_strcpy:
2927 case LibFunc_strncpy:
2928 case LibFunc_strcat:
2929 case LibFunc_strncat:
2930 return true;
2931 default:
2932 return false;
2933 }
2934
2935 return false;
2936}
2937
2938/// Look for opportunities to duplicate return instructions to the predecessor
2939/// to enable tail call optimizations. The case it is currently looking for is
2940/// the following one. Known intrinsics or library function that may be tail
2941/// called are taken into account as well.
2942/// @code
2943/// bb0:
2944/// %tmp0 = tail call i32 @f0()
2945/// br label %return
2946/// bb1:
2947/// %tmp1 = tail call i32 @f1()
2948/// br label %return
2949/// bb2:
2950/// %tmp2 = tail call i32 @f2()
2951/// br label %return
2952/// return:
2953/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
2954/// ret i32 %retval
2955/// @endcode
2956///
2957/// =>
2958///
2959/// @code
2960/// bb0:
2961/// %tmp0 = tail call i32 @f0()
2962/// ret i32 %tmp0
2963/// bb1:
2964/// %tmp1 = tail call i32 @f1()
2965/// ret i32 %tmp1
2966/// bb2:
2967/// %tmp2 = tail call i32 @f2()
2968/// ret i32 %tmp2
2969/// @endcode
2970bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB,
2971 ModifyDT &ModifiedDT) {
2972 if (!BB->getTerminator())
2973 return false;
2974
2975 ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator());
2976 if (!RetI)
2977 return false;
2978
2979 assert(LI->getLoopFor(BB) == nullptr && "A return block cannot be in a loop");
2980
2981 PHINode *PN = nullptr;
2982 ExtractValueInst *EVI = nullptr;
2983 BitCastInst *BCI = nullptr;
2984 Value *V = RetI->getReturnValue();
2985 if (V) {
2986 BCI = dyn_cast<BitCastInst>(V);
2987 if (BCI)
2988 V = BCI->getOperand(0);
2989
2991 if (EVI) {
2992 V = EVI->getOperand(0);
2993 if (!llvm::all_of(EVI->indices(), equal_to(0)))
2994 return false;
2995 }
2996
2997 PN = dyn_cast<PHINode>(V);
2998 }
2999
3000 if (PN && PN->getParent() != BB)
3001 return false;
3002
3003 auto isLifetimeEndOrBitCastFor = [](const Instruction *Inst) {
3004 const BitCastInst *BC = dyn_cast<BitCastInst>(Inst);
3005 if (BC && BC->hasOneUse())
3006 Inst = BC->user_back();
3007
3008 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst))
3009 return II->getIntrinsicID() == Intrinsic::lifetime_end;
3010 return false;
3011 };
3012
3014
3015 auto isFakeUse = [&FakeUses](const Instruction *Inst) {
3016 if (auto *II = dyn_cast<IntrinsicInst>(Inst);
3017 II && II->getIntrinsicID() == Intrinsic::fake_use) {
3018 // Record the instruction so it can be preserved when the exit block is
3019 // removed. Do not preserve the fake use that uses the result of the
3020 // PHI instruction.
3021 // Do not copy fake uses that use the result of a PHI node.
3022 // FIXME: If we do want to copy the fake use into the return blocks, we
3023 // have to figure out which of the PHI node operands to use for each
3024 // copy.
3025 if (!isa<PHINode>(II->getOperand(0))) {
3026 FakeUses.push_back(II);
3027 }
3028 return true;
3029 }
3030
3031 return false;
3032 };
3033
3034 // Make sure there are no instructions between the first instruction
3035 // and return.
3037 // Skip over pseudo-probes and the bitcast.
3038 while (&*BI == BCI || &*BI == EVI || isa<PseudoProbeInst>(BI) ||
3039 isLifetimeEndOrBitCastFor(&*BI) || isFakeUse(&*BI))
3040 BI = std::next(BI);
3041 if (&*BI != RetI)
3042 return false;
3043
3044 // Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
3045 // call.
3046 auto MayBePermittedAsTailCall = [&](const auto *CI) {
3047 return TLI->mayBeEmittedAsTailCall(CI) &&
3048 attributesPermitTailCall(BB->getParent(), CI, RetI, *TLI);
3049 };
3050
3051 SmallVector<BasicBlock *, 4> TailCallBBs;
3052 // Record the call instructions so we can insert any fake uses
3053 // that need to be preserved before them.
3055 if (PN) {
3056 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
3057 // Look through bitcasts.
3058 Value *IncomingVal = PN->getIncomingValue(I)->stripPointerCasts();
3059 CallInst *CI = dyn_cast<CallInst>(IncomingVal);
3060 BasicBlock *PredBB = PN->getIncomingBlock(I);
3061 // Make sure the phi value is indeed produced by the tail call.
3062 if (CI && CI->hasOneUse() && CI->getParent() == PredBB &&
3063 MayBePermittedAsTailCall(CI)) {
3064 TailCallBBs.push_back(PredBB);
3065 CallInsts.push_back(CI);
3066 } else {
3067 // Consider the cases in which the phi value is indirectly produced by
3068 // the tail call, for example when encountering memset(), memmove(),
3069 // strcpy(), whose return value may have been optimized out. In such
3070 // cases, the value needs to be the first function argument.
3071 //
3072 // bb0:
3073 // tail call void @llvm.memset.p0.i64(ptr %0, i8 0, i64 %1)
3074 // br label %return
3075 // return:
3076 // %phi = phi ptr [ %0, %bb0 ], [ %2, %entry ]
3077 if (PredBB && PredBB->getSingleSuccessor() == BB)
3079 PredBB->getTerminator()->getPrevNode());
3080
3081 if (CI && CI->use_empty() &&
3082 isIntrinsicOrLFToBeTailCalled(TLInfo, CI) &&
3083 IncomingVal == CI->getArgOperand(0) &&
3084 MayBePermittedAsTailCall(CI)) {
3085 TailCallBBs.push_back(PredBB);
3086 CallInsts.push_back(CI);
3087 }
3088 }
3089 }
3090 } else {
3091 SmallPtrSet<BasicBlock *, 4> VisitedBBs;
3092 for (BasicBlock *Pred : predecessors(BB)) {
3093 if (!VisitedBBs.insert(Pred).second)
3094 continue;
3095 if (Instruction *I = Pred->rbegin()->getPrevNode()) {
3096 CallInst *CI = dyn_cast<CallInst>(I);
3097 if (CI && CI->use_empty() && MayBePermittedAsTailCall(CI)) {
3098 // Either we return void or the return value must be the first
3099 // argument of a known intrinsic or library function.
3100 if (!V || isa<UndefValue>(V) ||
3101 (isIntrinsicOrLFToBeTailCalled(TLInfo, CI) &&
3102 V == CI->getArgOperand(0))) {
3103 TailCallBBs.push_back(Pred);
3104 CallInsts.push_back(CI);
3105 }
3106 }
3107 }
3108 }
3109 }
3110
3111 bool Changed = false;
3112 for (auto const &TailCallBB : TailCallBBs) {
3113 // Make sure the call instruction is followed by an unconditional branch to
3114 // the return block.
3115 UncondBrInst *BI = dyn_cast<UncondBrInst>(TailCallBB->getTerminator());
3116 if (!BI || BI->getSuccessor() != BB)
3117 continue;
3118
3119 // Duplicate the return into TailCallBB.
3120 (void)FoldReturnIntoUncondBranch(RetI, BB, TailCallBB, DTU);
3122 BFI->getBlockFreq(BB) >= BFI->getBlockFreq(TailCallBB));
3123 BFI->setBlockFreq(BB,
3124 (BFI->getBlockFreq(BB) - BFI->getBlockFreq(TailCallBB)));
3125 ModifiedDT = ModifyDT::ModifyBBDT;
3126 Changed = true;
3127 ++NumRetsDup;
3128 }
3129
3130 // If we eliminated all predecessors of the block, delete the block now.
3131 if (Changed && !BB->hasAddressTaken() && pred_empty(BB)) {
3132 // Copy the fake uses found in the original return block to all blocks
3133 // that contain tail calls.
3134 for (auto *CI : CallInsts) {
3135 for (auto const *FakeUse : FakeUses) {
3136 auto *ClonedInst = FakeUse->clone();
3137 ClonedInst->insertBefore(CI->getIterator());
3138 }
3139 }
3140 DTU->deleteBB(BB);
3141 }
3142
3143 return Changed;
3144}
3145
3146//===----------------------------------------------------------------------===//
3147// Memory Optimization
3148//===----------------------------------------------------------------------===//
3149
3150namespace {
3151
3152/// This is an extended version of TargetLowering::AddrMode
3153/// which holds actual Value*'s for register values.
3154struct ExtAddrMode : public TargetLowering::AddrMode {
3155 Value *BaseReg = nullptr;
3156 Value *ScaledReg = nullptr;
3157 Value *OriginalValue = nullptr;
3158 bool InBounds = true;
3159
3160 enum FieldName {
3161 NoField = 0x00,
3162 BaseRegField = 0x01,
3163 BaseGVField = 0x02,
3164 BaseOffsField = 0x04,
3165 ScaledRegField = 0x08,
3166 ScaleField = 0x10,
3167 MultipleFields = 0xff
3168 };
3169
3170 ExtAddrMode() = default;
3171
3172 void print(raw_ostream &OS) const;
3173 void dump() const;
3174
3175 // Replace From in ExtAddrMode with To.
3176 // E.g., SExt insts may be promoted and deleted. We should replace them with
3177 // the promoted values.
3178 void replaceWith(Value *From, Value *To) {
3179 if (ScaledReg == From)
3180 ScaledReg = To;
3181 }
3182
3183 FieldName compare(const ExtAddrMode &other) {
3184 // First check that the types are the same on each field, as differing types
3185 // is something we can't cope with later on.
3186 if (BaseReg && other.BaseReg &&
3187 BaseReg->getType() != other.BaseReg->getType())
3188 return MultipleFields;
3189 if (BaseGV && other.BaseGV && BaseGV->getType() != other.BaseGV->getType())
3190 return MultipleFields;
3191 if (ScaledReg && other.ScaledReg &&
3192 ScaledReg->getType() != other.ScaledReg->getType())
3193 return MultipleFields;
3194
3195 // Conservatively reject 'inbounds' mismatches.
3196 if (InBounds != other.InBounds)
3197 return MultipleFields;
3198
3199 // Check each field to see if it differs.
3200 unsigned Result = NoField;
3201 if (BaseReg != other.BaseReg)
3202 Result |= BaseRegField;
3203 if (BaseGV != other.BaseGV)
3204 Result |= BaseGVField;
3205 if (BaseOffs != other.BaseOffs)
3206 Result |= BaseOffsField;
3207 if (ScaledReg != other.ScaledReg)
3208 Result |= ScaledRegField;
3209 // Don't count 0 as being a different scale, because that actually means
3210 // unscaled (which will already be counted by having no ScaledReg).
3211 if (Scale && other.Scale && Scale != other.Scale)
3212 Result |= ScaleField;
3213
3214 if (llvm::popcount(Result) > 1)
3215 return MultipleFields;
3216 else
3217 return static_cast<FieldName>(Result);
3218 }
3219
3220 // An AddrMode is trivial if it involves no calculation i.e. it is just a base
3221 // with no offset.
3222 bool isTrivial() {
3223 // An AddrMode is (BaseGV + BaseReg + BaseOffs + ScaleReg * Scale) so it is
3224 // trivial if at most one of these terms is nonzero, except that BaseGV and
3225 // BaseReg both being zero actually means a null pointer value, which we
3226 // consider to be 'non-zero' here.
3227 return !BaseOffs && !Scale && !(BaseGV && BaseReg);
3228 }
3229
3230 Value *GetFieldAsValue(FieldName Field, Type *IntPtrTy) {
3231 switch (Field) {
3232 default:
3233 return nullptr;
3234 case BaseRegField:
3235 return BaseReg;
3236 case BaseGVField:
3237 return BaseGV;
3238 case ScaledRegField:
3239 return ScaledReg;
3240 case BaseOffsField:
3241 return ConstantInt::getSigned(IntPtrTy, BaseOffs);
3242 }
3243 }
3244
3245 void SetCombinedField(FieldName Field, Value *V,
3246 const SmallVectorImpl<ExtAddrMode> &AddrModes) {
3247 switch (Field) {
3248 default:
3249 llvm_unreachable("Unhandled fields are expected to be rejected earlier");
3250 break;
3251 case ExtAddrMode::BaseRegField:
3252 BaseReg = V;
3253 break;
3254 case ExtAddrMode::BaseGVField:
3255 // A combined BaseGV is an Instruction, not a GlobalValue, so it goes
3256 // in the BaseReg field.
3257 assert(BaseReg == nullptr);
3258 BaseReg = V;
3259 BaseGV = nullptr;
3260 break;
3261 case ExtAddrMode::ScaledRegField:
3262 ScaledReg = V;
3263 // If we have a mix of scaled and unscaled addrmodes then we want scale
3264 // to be the scale and not zero.
3265 if (!Scale)
3266 for (const ExtAddrMode &AM : AddrModes)
3267 if (AM.Scale) {
3268 Scale = AM.Scale;
3269 break;
3270 }
3271 break;
3272 case ExtAddrMode::BaseOffsField:
3273 // The offset is no longer a constant, so it goes in ScaledReg with a
3274 // scale of 1.
3275 assert(ScaledReg == nullptr);
3276 ScaledReg = V;
3277 Scale = 1;
3278 BaseOffs = 0;
3279 break;
3280 }
3281 }
3282};
3283
3284#ifndef NDEBUG
3285static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
3286 AM.print(OS);
3287 return OS;
3288}
3289#endif
3290
3291#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3292void ExtAddrMode::print(raw_ostream &OS) const {
3293 bool NeedPlus = false;
3294 OS << "[";
3295 if (InBounds)
3296 OS << "inbounds ";
3297 if (BaseGV) {
3298 OS << "GV:";
3299 BaseGV->printAsOperand(OS, /*PrintType=*/false);
3300 NeedPlus = true;
3301 }
3302
3303 if (BaseOffs) {
3304 OS << (NeedPlus ? " + " : "") << BaseOffs;
3305 NeedPlus = true;
3306 }
3307
3308 if (BaseReg) {
3309 OS << (NeedPlus ? " + " : "") << "Base:";
3310 BaseReg->printAsOperand(OS, /*PrintType=*/false);
3311 NeedPlus = true;
3312 }
3313 if (Scale) {
3314 OS << (NeedPlus ? " + " : "") << Scale << "*";
3315 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
3316 }
3317
3318 OS << ']';
3319}
3320
3321LLVM_DUMP_METHOD void ExtAddrMode::dump() const {
3322 print(dbgs());
3323 dbgs() << '\n';
3324}
3325#endif
3326
3327} // end anonymous namespace
3328
3329namespace {
3330
3331/// This class provides transaction based operation on the IR.
3332/// Every change made through this class is recorded in the internal state and
3333/// can be undone (rollback) until commit is called.
3334/// CGP does not check if instructions could be speculatively executed when
3335/// moved. Preserving the original location would pessimize the debugging
3336/// experience, as well as negatively impact the quality of sample PGO.
3337class TypePromotionTransaction {
3338 /// This represents the common interface of the individual transaction.
3339 /// Each class implements the logic for doing one specific modification on
3340 /// the IR via the TypePromotionTransaction.
3341 class TypePromotionAction {
3342 protected:
3343 /// The Instruction modified.
3344 Instruction *Inst;
3345
3346 public:
3347 /// Constructor of the action.
3348 /// The constructor performs the related action on the IR.
3349 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
3350
3351 virtual ~TypePromotionAction() = default;
3352
3353 /// Undo the modification done by this action.
3354 /// When this method is called, the IR must be in the same state as it was
3355 /// before this action was applied.
3356 /// \pre Undoing the action works if and only if the IR is in the exact same
3357 /// state as it was directly after this action was applied.
3358 virtual void undo() = 0;
3359
3360 /// Advocate every change made by this action.
3361 /// When the results on the IR of the action are to be kept, it is important
3362 /// to call this function, otherwise hidden information may be kept forever.
3363 virtual void commit() {
3364 // Nothing to be done, this action is not doing anything.
3365 }
3366 };
3367
3368 /// Utility to remember the position of an instruction.
3369 class InsertionHandler {
3370 /// Position of an instruction.
3371 /// Either an instruction:
3372 /// - Is the first in a basic block: BB is used.
3373 /// - Has a previous instruction: PrevInst is used.
3374 struct {
3375 BasicBlock::iterator PrevInst;
3376 BasicBlock *BB;
3377 } Point;
3378 std::optional<DbgRecord::self_iterator> BeforeDbgRecord = std::nullopt;
3379
3380 /// Remember whether or not the instruction had a previous instruction.
3381 bool HasPrevInstruction;
3382
3383 public:
3384 /// Record the position of \p Inst.
3385 InsertionHandler(Instruction *Inst) {
3386 HasPrevInstruction = (Inst != &*(Inst->getParent()->begin()));
3387 BasicBlock *BB = Inst->getParent();
3388
3389 // Record where we would have to re-insert the instruction in the sequence
3390 // of DbgRecords, if we ended up reinserting.
3391 BeforeDbgRecord = Inst->getDbgReinsertionPosition();
3392
3393 if (HasPrevInstruction) {
3394 Point.PrevInst = std::prev(Inst->getIterator());
3395 } else {
3396 Point.BB = BB;
3397 }
3398 }
3399
3400 /// Insert \p Inst at the recorded position.
3401 void insert(Instruction *Inst) {
3402 if (HasPrevInstruction) {
3403 if (Inst->getParent())
3404 Inst->removeFromParent();
3405 Inst->insertAfter(Point.PrevInst);
3406 } else {
3407 BasicBlock::iterator Position = Point.BB->getFirstInsertionPt();
3408 if (Inst->getParent())
3409 Inst->moveBefore(*Point.BB, Position);
3410 else
3411 Inst->insertBefore(*Point.BB, Position);
3412 }
3413
3414 Inst->getParent()->reinsertInstInDbgRecords(Inst, BeforeDbgRecord);
3415 }
3416 };
3417
3418 /// Move an instruction before another.
3419 class InstructionMoveBefore : public TypePromotionAction {
3420 /// Original position of the instruction.
3421 InsertionHandler Position;
3422
3423 public:
3424 /// Move \p Inst before \p Before.
3425 InstructionMoveBefore(Instruction *Inst, BasicBlock::iterator Before)
3426 : TypePromotionAction(Inst), Position(Inst) {
3427 LLVM_DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before
3428 << "\n");
3429 Inst->moveBefore(Before);
3430 }
3431
3432 /// Move the instruction back to its original position.
3433 void undo() override {
3434 LLVM_DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
3435 Position.insert(Inst);
3436 }
3437 };
3438
3439 /// Set the operand of an instruction with a new value.
3440 class OperandSetter : public TypePromotionAction {
3441 /// Original operand of the instruction.
3442 Value *Origin;
3443
3444 /// Index of the modified instruction.
3445 unsigned Idx;
3446
3447 public:
3448 /// Set \p Idx operand of \p Inst with \p NewVal.
3449 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
3450 : TypePromotionAction(Inst), Idx(Idx) {
3451 LLVM_DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
3452 << "for:" << *Inst << "\n"
3453 << "with:" << *NewVal << "\n");
3454 Origin = Inst->getOperand(Idx);
3455 Inst->setOperand(Idx, NewVal);
3456 }
3457
3458 /// Restore the original value of the instruction.
3459 void undo() override {
3460 LLVM_DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
3461 << "for: " << *Inst << "\n"
3462 << "with: " << *Origin << "\n");
3463 Inst->setOperand(Idx, Origin);
3464 }
3465 };
3466
3467 /// Hide the operands of an instruction.
3468 /// Do as if this instruction was not using any of its operands.
3469 class OperandsHider : public TypePromotionAction {
3470 /// The list of original operands.
3471 SmallVector<Value *, 4> OriginalValues;
3472
3473 public:
3474 /// Remove \p Inst from the uses of the operands of \p Inst.
3475 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
3476 LLVM_DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
3477 unsigned NumOpnds = Inst->getNumOperands();
3478 OriginalValues.reserve(NumOpnds);
3479 for (unsigned It = 0; It < NumOpnds; ++It) {
3480 // Save the current operand.
3481 Value *Val = Inst->getOperand(It);
3482 OriginalValues.push_back(Val);
3483 // Set a dummy one.
3484 // We could use OperandSetter here, but that would imply an overhead
3485 // that we are not willing to pay.
3486 Inst->setOperand(It, PoisonValue::get(Val->getType()));
3487 }
3488 }
3489
3490 /// Restore the original list of uses.
3491 void undo() override {
3492 LLVM_DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
3493 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
3494 Inst->setOperand(It, OriginalValues[It]);
3495 }
3496 };
3497
3498 /// Build a truncate instruction.
3499 class TruncBuilder : public TypePromotionAction {
3500 Value *Val;
3501
3502 public:
3503 /// Build a truncate instruction of \p Opnd producing a \p Ty
3504 /// result.
3505 /// trunc Opnd to Ty.
3506 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
3507 IRBuilder<> Builder(Opnd);
3508 Builder.SetCurrentDebugLocation(DebugLoc());
3509 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
3510 LLVM_DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
3511 }
3512
3513 /// Get the built value.
3514 Value *getBuiltValue() { return Val; }
3515
3516 /// Remove the built instruction.
3517 void undo() override {
3518 LLVM_DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
3519 if (Instruction *IVal = dyn_cast<Instruction>(Val))
3520 IVal->eraseFromParent();
3521 }
3522 };
3523
3524 /// Build a sign extension instruction.
3525 class SExtBuilder : public TypePromotionAction {
3526 Value *Val;
3527
3528 public:
3529 /// Build a sign extension instruction of \p Opnd producing a \p Ty
3530 /// result.
3531 /// sext Opnd to Ty.
3532 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
3533 : TypePromotionAction(InsertPt) {
3534 IRBuilder<> Builder(InsertPt);
3535 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
3536 LLVM_DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
3537 }
3538
3539 /// Get the built value.
3540 Value *getBuiltValue() { return Val; }
3541
3542 /// Remove the built instruction.
3543 void undo() override {
3544 LLVM_DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
3545 if (Instruction *IVal = dyn_cast<Instruction>(Val))
3546 IVal->eraseFromParent();
3547 }
3548 };
3549
3550 /// Build a zero extension instruction.
3551 class ZExtBuilder : public TypePromotionAction {
3552 Value *Val;
3553
3554 public:
3555 /// Build a zero extension instruction of \p Opnd producing a \p Ty
3556 /// result.
3557 /// zext Opnd to Ty.
3558 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
3559 : TypePromotionAction(InsertPt) {
3560 IRBuilder<> Builder(InsertPt);
3561 Builder.SetCurrentDebugLocation(DebugLoc());
3562 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
3563 LLVM_DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
3564 }
3565
3566 /// Get the built value.
3567 Value *getBuiltValue() { return Val; }
3568
3569 /// Remove the built instruction.
3570 void undo() override {
3571 LLVM_DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
3572 if (Instruction *IVal = dyn_cast<Instruction>(Val))
3573 IVal->eraseFromParent();
3574 }
3575 };
3576
3577 /// Mutate an instruction to another type.
3578 class TypeMutator : public TypePromotionAction {
3579 /// Record the original type.
3580 Type *OrigTy;
3581
3582 public:
3583 /// Mutate the type of \p Inst into \p NewTy.
3584 TypeMutator(Instruction *Inst, Type *NewTy)
3585 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
3586 LLVM_DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
3587 << "\n");
3588 Inst->mutateType(NewTy);
3589 }
3590
3591 /// Mutate the instruction back to its original type.
3592 void undo() override {
3593 LLVM_DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
3594 << "\n");
3595 Inst->mutateType(OrigTy);
3596 }
3597 };
3598
3599 /// Replace the uses of an instruction by another instruction.
3600 class UsesReplacer : public TypePromotionAction {
3601 /// Helper structure to keep track of the replaced uses.
3602 struct InstructionAndIdx {
3603 /// The instruction using the instruction.
3604 Instruction *Inst;
3605
3606 /// The index where this instruction is used for Inst.
3607 unsigned Idx;
3608
3609 InstructionAndIdx(Instruction *Inst, unsigned Idx)
3610 : Inst(Inst), Idx(Idx) {}
3611 };
3612
3613 /// Keep track of the original uses (pair Instruction, Index).
3615 /// Keep track of the debug users.
3616 SmallVector<DbgVariableRecord *, 1> DbgVariableRecords;
3617
3618 /// Keep track of the new value so that we can undo it by replacing
3619 /// instances of the new value with the original value.
3620 Value *New;
3621
3623
3624 public:
3625 /// Replace all the use of \p Inst by \p New.
3626 UsesReplacer(Instruction *Inst, Value *New)
3627 : TypePromotionAction(Inst), New(New) {
3628 LLVM_DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
3629 << "\n");
3630 // Record the original uses.
3631 for (Use &U : Inst->uses()) {
3632 Instruction *UserI = cast<Instruction>(U.getUser());
3633 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
3634 }
3635 // Record the debug uses separately. They are not in the instruction's
3636 // use list, but they are replaced by RAUW.
3637 findDbgValues(Inst, DbgVariableRecords);
3638
3639 // Now, we can replace the uses.
3640 Inst->replaceAllUsesWith(New);
3641 }
3642
3643 /// Reassign the original uses of Inst to Inst.
3644 void undo() override {
3645 LLVM_DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
3646 for (InstructionAndIdx &Use : OriginalUses)
3647 Use.Inst->setOperand(Use.Idx, Inst);
3648 // RAUW has replaced all original uses with references to the new value,
3649 // including the debug uses. Since we are undoing the replacements,
3650 // the original debug uses must also be reinstated to maintain the
3651 // correctness and utility of debug value records.
3652 for (DbgVariableRecord *DVR : DbgVariableRecords)
3653 DVR->replaceVariableLocationOp(New, Inst);
3654 }
3655 };
3656
3657 /// Remove an instruction from the IR.
3658 class InstructionRemover : public TypePromotionAction {
3659 /// Original position of the instruction.
3660 InsertionHandler Inserter;
3661
3662 /// Helper structure to hide all the link to the instruction. In other
3663 /// words, this helps to do as if the instruction was removed.
3664 OperandsHider Hider;
3665
3666 /// Keep track of the uses replaced, if any.
3667 UsesReplacer *Replacer = nullptr;
3668
3669 /// Keep track of instructions removed.
3670 SetOfInstrs &RemovedInsts;
3671
3672 public:
3673 /// Remove all reference of \p Inst and optionally replace all its
3674 /// uses with New.
3675 /// \p RemovedInsts Keep track of the instructions removed by this Action.
3676 /// \pre If !Inst->use_empty(), then New != nullptr
3677 InstructionRemover(Instruction *Inst, SetOfInstrs &RemovedInsts,
3678 Value *New = nullptr)
3679 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
3680 RemovedInsts(RemovedInsts) {
3681 if (New)
3682 Replacer = new UsesReplacer(Inst, New);
3683 LLVM_DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
3684 RemovedInsts.insert(Inst);
3685 /// The instructions removed here will be freed after completing
3686 /// optimizeBlock() for all blocks as we need to keep track of the
3687 /// removed instructions during promotion.
3688 Inst->removeFromParent();
3689 }
3690
3691 ~InstructionRemover() override { delete Replacer; }
3692
3693 InstructionRemover &operator=(const InstructionRemover &other) = delete;
3694 InstructionRemover(const InstructionRemover &other) = delete;
3695
3696 /// Resurrect the instruction and reassign it to the proper uses if
3697 /// new value was provided when build this action.
3698 void undo() override {
3699 LLVM_DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
3700 Inserter.insert(Inst);
3701 if (Replacer)
3702 Replacer->undo();
3703 Hider.undo();
3704 RemovedInsts.erase(Inst);
3705 }
3706 };
3707
3708public:
3709 /// Restoration point.
3710 /// The restoration point is a pointer to an action instead of an iterator
3711 /// because the iterator may be invalidated but not the pointer.
3712 using ConstRestorationPt = const TypePromotionAction *;
3713
3714 TypePromotionTransaction(SetOfInstrs &RemovedInsts)
3715 : RemovedInsts(RemovedInsts) {}
3716
3717 /// Advocate every changes made in that transaction. Return true if any change
3718 /// happen.
3719 bool commit();
3720
3721 /// Undo all the changes made after the given point.
3722 void rollback(ConstRestorationPt Point);
3723
3724 /// Get the current restoration point.
3725 ConstRestorationPt getRestorationPoint() const;
3726
3727 /// \name API for IR modification with state keeping to support rollback.
3728 /// @{
3729 /// Same as Instruction::setOperand.
3730 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
3731
3732 /// Same as Instruction::eraseFromParent.
3733 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
3734
3735 /// Same as Value::replaceAllUsesWith.
3736 void replaceAllUsesWith(Instruction *Inst, Value *New);
3737
3738 /// Same as Value::mutateType.
3739 void mutateType(Instruction *Inst, Type *NewTy);
3740
3741 /// Same as IRBuilder::createTrunc.
3742 Value *createTrunc(Instruction *Opnd, Type *Ty);
3743
3744 /// Same as IRBuilder::createSExt.
3745 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
3746
3747 /// Same as IRBuilder::createZExt.
3748 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
3749
3750private:
3751 /// The ordered list of actions made so far.
3753
3754 using CommitPt =
3755 SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator;
3756
3757 SetOfInstrs &RemovedInsts;
3758};
3759
3760} // end anonymous namespace
3761
3762void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
3763 Value *NewVal) {
3764 Actions.push_back(std::make_unique<TypePromotionTransaction::OperandSetter>(
3765 Inst, Idx, NewVal));
3766}
3767
3768void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
3769 Value *NewVal) {
3770 Actions.push_back(
3771 std::make_unique<TypePromotionTransaction::InstructionRemover>(
3772 Inst, RemovedInsts, NewVal));
3773}
3774
3775void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
3776 Value *New) {
3777 Actions.push_back(
3778 std::make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
3779}
3780
3781void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
3782 Actions.push_back(
3783 std::make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
3784}
3785
3786Value *TypePromotionTransaction::createTrunc(Instruction *Opnd, Type *Ty) {
3787 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
3788 Value *Val = Ptr->getBuiltValue();
3789 Actions.push_back(std::move(Ptr));
3790 return Val;
3791}
3792
3793Value *TypePromotionTransaction::createSExt(Instruction *Inst, Value *Opnd,
3794 Type *Ty) {
3795 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
3796 Value *Val = Ptr->getBuiltValue();
3797 Actions.push_back(std::move(Ptr));
3798 return Val;
3799}
3800
3801Value *TypePromotionTransaction::createZExt(Instruction *Inst, Value *Opnd,
3802 Type *Ty) {
3803 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
3804 Value *Val = Ptr->getBuiltValue();
3805 Actions.push_back(std::move(Ptr));
3806 return Val;
3807}
3808
3809TypePromotionTransaction::ConstRestorationPt
3810TypePromotionTransaction::getRestorationPoint() const {
3811 return !Actions.empty() ? Actions.back().get() : nullptr;
3812}
3813
3814bool TypePromotionTransaction::commit() {
3815 for (std::unique_ptr<TypePromotionAction> &Action : Actions)
3816 Action->commit();
3817 bool Modified = !Actions.empty();
3818 Actions.clear();
3819 return Modified;
3820}
3821
3822void TypePromotionTransaction::rollback(
3823 TypePromotionTransaction::ConstRestorationPt Point) {
3824 while (!Actions.empty() && Point != Actions.back().get()) {
3825 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
3826 Curr->undo();
3827 }
3828}
3829
3830namespace {
3831
3832/// A helper class for matching addressing modes.
3833///
3834/// This encapsulates the logic for matching the target-legal addressing modes.
3835class AddressingModeMatcher {
3836 SmallVectorImpl<Instruction *> &AddrModeInsts;
3837 const TargetLowering &TLI;
3838 const TargetRegisterInfo &TRI;
3839 const DataLayout &DL;
3840 const LoopInfo &LI;
3841 const std::function<const DominatorTree &()> getDTFn;
3842
3843 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
3844 /// the memory instruction that we're computing this address for.
3845 Type *AccessTy;
3846 unsigned AddrSpace;
3847 Instruction *MemoryInst;
3848
3849 /// This is the addressing mode that we're building up. This is
3850 /// part of the return value of this addressing mode matching stuff.
3851 ExtAddrMode &AddrMode;
3852
3853 /// The instructions inserted by other CodeGenPrepare optimizations.
3854 const SetOfInstrs &InsertedInsts;
3855
3856 /// A map from the instructions to their type before promotion.
3857 InstrToOrigTy &PromotedInsts;
3858
3859 /// The ongoing transaction where every action should be registered.
3860 TypePromotionTransaction &TPT;
3861
3862 // A GEP which has too large offset to be folded into the addressing mode.
3863 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP;
3864
3865 /// This is set to true when we should not do profitability checks.
3866 /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
3867 bool IgnoreProfitability;
3868
3869 /// True if we are optimizing for size.
3870 bool OptSize = false;
3871
3872 ProfileSummaryInfo *PSI;
3873 BlockFrequencyInfo *BFI;
3874
3875 AddressingModeMatcher(
3876 SmallVectorImpl<Instruction *> &AMI, const TargetLowering &TLI,
3877 const TargetRegisterInfo &TRI, const LoopInfo &LI,
3878 const std::function<const DominatorTree &()> getDTFn, Type *AT,
3879 unsigned AS, Instruction *MI, ExtAddrMode &AM,
3880 const SetOfInstrs &InsertedInsts, InstrToOrigTy &PromotedInsts,
3881 TypePromotionTransaction &TPT,
3882 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP,
3883 bool OptSize, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI)
3884 : AddrModeInsts(AMI), TLI(TLI), TRI(TRI),
3885 DL(MI->getDataLayout()), LI(LI), getDTFn(getDTFn),
3886 AccessTy(AT), AddrSpace(AS), MemoryInst(MI), AddrMode(AM),
3887 InsertedInsts(InsertedInsts), PromotedInsts(PromotedInsts), TPT(TPT),
3888 LargeOffsetGEP(LargeOffsetGEP), OptSize(OptSize), PSI(PSI), BFI(BFI) {
3889 IgnoreProfitability = false;
3890 }
3891
3892public:
3893 /// Find the maximal addressing mode that a load/store of V can fold,
3894 /// give an access type of AccessTy. This returns a list of involved
3895 /// instructions in AddrModeInsts.
3896 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
3897 /// optimizations.
3898 /// \p PromotedInsts maps the instructions to their type before promotion.
3899 /// \p The ongoing transaction where every action should be registered.
3900 static ExtAddrMode
3901 Match(Value *V, Type *AccessTy, unsigned AS, Instruction *MemoryInst,
3902 SmallVectorImpl<Instruction *> &AddrModeInsts,
3903 const TargetLowering &TLI, const LoopInfo &LI,
3904 const std::function<const DominatorTree &()> getDTFn,
3905 const TargetRegisterInfo &TRI, const SetOfInstrs &InsertedInsts,
3906 InstrToOrigTy &PromotedInsts, TypePromotionTransaction &TPT,
3907 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP,
3908 bool OptSize, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI) {
3909 ExtAddrMode Result;
3910
3911 bool Success = AddressingModeMatcher(AddrModeInsts, TLI, TRI, LI, getDTFn,
3912 AccessTy, AS, MemoryInst, Result,
3913 InsertedInsts, PromotedInsts, TPT,
3914 LargeOffsetGEP, OptSize, PSI, BFI)
3915 .matchAddr(V, 0);
3916 (void)Success;
3917 assert(Success && "Couldn't select *anything*?");
3918 return Result;
3919 }
3920
3921private:
3922 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
3923 bool matchAddr(Value *Addr, unsigned Depth);
3924 bool matchOperationAddr(User *AddrInst, unsigned Opcode, unsigned Depth,
3925 bool *MovedAway = nullptr);
3926 bool isProfitableToFoldIntoAddressingMode(Instruction *I,
3927 ExtAddrMode &AMBefore,
3928 ExtAddrMode &AMAfter);
3929 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
3930 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
3931 Value *PromotedOperand) const;
3932};
3933
3934class PhiNodeSet;
3935
3936/// An iterator for PhiNodeSet.
3937class PhiNodeSetIterator {
3938 PhiNodeSet *const Set;
3939 size_t CurrentIndex = 0;
3940
3941public:
3942 /// The constructor. Start should point to either a valid element, or be equal
3943 /// to the size of the underlying SmallVector of the PhiNodeSet.
3944 PhiNodeSetIterator(PhiNodeSet *const Set, size_t Start);
3945 PHINode *operator*() const;
3946 PhiNodeSetIterator &operator++();
3947 bool operator==(const PhiNodeSetIterator &RHS) const;
3948 bool operator!=(const PhiNodeSetIterator &RHS) const;
3949};
3950
3951/// Keeps a set of PHINodes.
3952///
3953/// This is a minimal set implementation for a specific use case:
3954/// It is very fast when there are very few elements, but also provides good
3955/// performance when there are many. It is similar to SmallPtrSet, but also
3956/// provides iteration by insertion order, which is deterministic and stable
3957/// across runs. It is also similar to SmallSetVector, but provides removing
3958/// elements in O(1) time. This is achieved by not actually removing the element
3959/// from the underlying vector, so comes at the cost of using more memory, but
3960/// that is fine, since PhiNodeSets are used as short lived objects.
3961class PhiNodeSet {
3962 friend class PhiNodeSetIterator;
3963
3964 using MapType = SmallDenseMap<PHINode *, size_t, 32>;
3965 using iterator = PhiNodeSetIterator;
3966
3967 /// Keeps the elements in the order of their insertion in the underlying
3968 /// vector. To achieve constant time removal, it never deletes any element.
3970
3971 /// Keeps the elements in the underlying set implementation. This (and not the
3972 /// NodeList defined above) is the source of truth on whether an element
3973 /// is actually in the collection.
3974 MapType NodeMap;
3975
3976 /// Points to the first valid (not deleted) element when the set is not empty
3977 /// and the value is not zero. Equals to the size of the underlying vector
3978 /// when the set is empty. When the value is 0, as in the beginning, the
3979 /// first element may or may not be valid.
3980 size_t FirstValidElement = 0;
3981
3982public:
3983 /// Inserts a new element to the collection.
3984 /// \returns true if the element is actually added, i.e. was not in the
3985 /// collection before the operation.
3986 bool insert(PHINode *Ptr) {
3987 if (NodeMap.insert(std::make_pair(Ptr, NodeList.size())).second) {
3988 NodeList.push_back(Ptr);
3989 return true;
3990 }
3991 return false;
3992 }
3993
3994 /// Removes the element from the collection.
3995 /// \returns whether the element is actually removed, i.e. was in the
3996 /// collection before the operation.
3997 bool erase(PHINode *Ptr) {
3998 if (NodeMap.erase(Ptr)) {
3999 SkipRemovedElements(FirstValidElement);
4000 return true;
4001 }
4002 return false;
4003 }
4004
4005 /// Removes all elements and clears the collection.
4006 void clear() {
4007 NodeMap.clear();
4008 NodeList.clear();
4009 FirstValidElement = 0;
4010 }
4011
4012 /// \returns an iterator that will iterate the elements in the order of
4013 /// insertion.
4014 iterator begin() {
4015 if (FirstValidElement == 0)
4016 SkipRemovedElements(FirstValidElement);
4017 return PhiNodeSetIterator(this, FirstValidElement);
4018 }
4019
4020 /// \returns an iterator that points to the end of the collection.
4021 iterator end() { return PhiNodeSetIterator(this, NodeList.size()); }
4022
4023 /// Returns the number of elements in the collection.
4024 size_t size() const { return NodeMap.size(); }
4025
4026 /// \returns 1 if the given element is in the collection, and 0 if otherwise.
4027 size_t count(PHINode *Ptr) const { return NodeMap.count(Ptr); }
4028
4029private:
4030 /// Updates the CurrentIndex so that it will point to a valid element.
4031 ///
4032 /// If the element of NodeList at CurrentIndex is valid, it does not
4033 /// change it. If there are no more valid elements, it updates CurrentIndex
4034 /// to point to the end of the NodeList.
4035 void SkipRemovedElements(size_t &CurrentIndex) {
4036 while (CurrentIndex < NodeList.size()) {
4037 auto it = NodeMap.find(NodeList[CurrentIndex]);
4038 // If the element has been deleted and added again later, NodeMap will
4039 // point to a different index, so CurrentIndex will still be invalid.
4040 if (it != NodeMap.end() && it->second == CurrentIndex)
4041 break;
4042 ++CurrentIndex;
4043 }
4044 }
4045};
4046
4047PhiNodeSetIterator::PhiNodeSetIterator(PhiNodeSet *const Set, size_t Start)
4048 : Set(Set), CurrentIndex(Start) {}
4049
4050PHINode *PhiNodeSetIterator::operator*() const {
4051 assert(CurrentIndex < Set->NodeList.size() &&
4052 "PhiNodeSet access out of range");
4053 return Set->NodeList[CurrentIndex];
4054}
4055
4056PhiNodeSetIterator &PhiNodeSetIterator::operator++() {
4057 assert(CurrentIndex < Set->NodeList.size() &&
4058 "PhiNodeSet access out of range");
4059 ++CurrentIndex;
4060 Set->SkipRemovedElements(CurrentIndex);
4061 return *this;
4062}
4063
4064bool PhiNodeSetIterator::operator==(const PhiNodeSetIterator &RHS) const {
4065 return CurrentIndex == RHS.CurrentIndex;
4066}
4067
4068bool PhiNodeSetIterator::operator!=(const PhiNodeSetIterator &RHS) const {
4069 return !((*this) == RHS);
4070}
4071
4072/// Keep track of simplification of Phi nodes.
4073/// Accept the set of all phi nodes and erase phi node from this set
4074/// if it is simplified.
4075class SimplificationTracker {
4076 DenseMap<Value *, Value *> Storage;
4077 // Tracks newly created Phi nodes. The elements are iterated by insertion
4078 // order.
4079 PhiNodeSet AllPhiNodes;
4080 // Tracks newly created Select nodes.
4081 SmallPtrSet<SelectInst *, 32> AllSelectNodes;
4082
4083public:
4084 Value *Get(Value *V) {
4085 do {
4086 auto SV = Storage.find(V);
4087 if (SV == Storage.end())
4088 return V;
4089 V = SV->second;
4090 } while (true);
4091 }
4092
4093 void Put(Value *From, Value *To) { Storage.insert({From, To}); }
4094
4095 void ReplacePhi(PHINode *From, PHINode *To) {
4096 Value *OldReplacement = Get(From);
4097 while (OldReplacement != From) {
4098 From = To;
4099 To = dyn_cast<PHINode>(OldReplacement);
4100 OldReplacement = Get(From);
4101 }
4102 assert(To && Get(To) == To && "Replacement PHI node is already replaced.");
4103 Put(From, To);
4104 From->replaceAllUsesWith(To);
4105 AllPhiNodes.erase(From);
4106 From->eraseFromParent();
4107 }
4108
4109 PhiNodeSet &newPhiNodes() { return AllPhiNodes; }
4110
4111 void insertNewPhi(PHINode *PN) { AllPhiNodes.insert(PN); }
4112
4113 void insertNewSelect(SelectInst *SI) { AllSelectNodes.insert(SI); }
4114
4115 unsigned countNewPhiNodes() const { return AllPhiNodes.size(); }
4116
4117 unsigned countNewSelectNodes() const { return AllSelectNodes.size(); }
4118
4119 void destroyNewNodes(Type *CommonType) {
4120 // For safe erasing, replace the uses with dummy value first.
4121 auto *Dummy = PoisonValue::get(CommonType);
4122 for (auto *I : AllPhiNodes) {
4123 I->replaceAllUsesWith(Dummy);
4124 I->eraseFromParent();
4125 }
4126 AllPhiNodes.clear();
4127 for (auto *I : AllSelectNodes) {
4128 I->replaceAllUsesWith(Dummy);
4129 I->eraseFromParent();
4130 }
4131 AllSelectNodes.clear();
4132 }
4133};
4134
4135/// A helper class for combining addressing modes.
4136class AddressingModeCombiner {
4137 typedef DenseMap<Value *, Value *> FoldAddrToValueMapping;
4138 typedef std::pair<PHINode *, PHINode *> PHIPair;
4139
4140private:
4141 /// The addressing modes we've collected.
4143
4144 /// The field in which the AddrModes differ, when we have more than one.
4145 ExtAddrMode::FieldName DifferentField = ExtAddrMode::NoField;
4146
4147 /// Are the AddrModes that we have all just equal to their original values?
4148 bool AllAddrModesTrivial = true;
4149
4150 /// Common Type for all different fields in addressing modes.
4151 Type *CommonType = nullptr;
4152
4153 const DataLayout &DL;
4154
4155 /// Original Address.
4156 Value *Original;
4157
4158 /// Common value among addresses
4159 Value *CommonValue = nullptr;
4160
4161public:
4162 AddressingModeCombiner(const DataLayout &DL, Value *OriginalValue)
4163 : DL(DL), Original(OriginalValue) {}
4164
4165 ~AddressingModeCombiner() { eraseCommonValueIfDead(); }
4166
4167 /// Get the combined AddrMode
4168 const ExtAddrMode &getAddrMode() const { return AddrModes[0]; }
4169
4170 /// Add a new AddrMode if it's compatible with the AddrModes we already
4171 /// have.
4172 /// \return True iff we succeeded in doing so.
4173 bool addNewAddrMode(ExtAddrMode &NewAddrMode) {
4174 // Take note of if we have any non-trivial AddrModes, as we need to detect
4175 // when all AddrModes are trivial as then we would introduce a phi or select
4176 // which just duplicates what's already there.
4177 AllAddrModesTrivial = AllAddrModesTrivial && NewAddrMode.isTrivial();
4178
4179 // If this is the first addrmode then everything is fine.
4180 if (AddrModes.empty()) {
4181 AddrModes.emplace_back(NewAddrMode);
4182 return true;
4183 }
4184
4185 // Figure out how different this is from the other address modes, which we
4186 // can do just by comparing against the first one given that we only care
4187 // about the cumulative difference.
4188 ExtAddrMode::FieldName ThisDifferentField =
4189 AddrModes[0].compare(NewAddrMode);
4190 if (DifferentField == ExtAddrMode::NoField)
4191 DifferentField = ThisDifferentField;
4192 else if (DifferentField != ThisDifferentField)
4193 DifferentField = ExtAddrMode::MultipleFields;
4194
4195 // If NewAddrMode differs in more than one dimension we cannot handle it.
4196 bool CanHandle = DifferentField != ExtAddrMode::MultipleFields;
4197
4198 // If Scale Field is different then we reject.
4199 CanHandle = CanHandle && DifferentField != ExtAddrMode::ScaleField;
4200
4201 // We also must reject the case when base offset is different and
4202 // scale reg is not null, we cannot handle this case due to merge of
4203 // different offsets will be used as ScaleReg.
4204 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseOffsField ||
4205 !NewAddrMode.ScaledReg);
4206
4207 // We also must reject the case when GV is different and BaseReg installed
4208 // due to we want to use base reg as a merge of GV values.
4209 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseGVField ||
4210 !NewAddrMode.HasBaseReg);
4211
4212 // Even if NewAddMode is the same we still need to collect it due to
4213 // original value is different. And later we will need all original values
4214 // as anchors during finding the common Phi node.
4215 if (CanHandle)
4216 AddrModes.emplace_back(NewAddrMode);
4217 else
4218 AddrModes.clear();
4219
4220 return CanHandle;
4221 }
4222
4223 /// Combine the addressing modes we've collected into a single
4224 /// addressing mode.
4225 /// \return True iff we successfully combined them or we only had one so
4226 /// didn't need to combine them anyway.
4227 bool combineAddrModes() {
4228 // If we have no AddrModes then they can't be combined.
4229 if (AddrModes.size() == 0)
4230 return false;
4231
4232 // A single AddrMode can trivially be combined.
4233 if (AddrModes.size() == 1 || DifferentField == ExtAddrMode::NoField)
4234 return true;
4235
4236 // If the AddrModes we collected are all just equal to the value they are
4237 // derived from then combining them wouldn't do anything useful.
4238 if (AllAddrModesTrivial)
4239 return false;
4240
4241 if (!addrModeCombiningAllowed())
4242 return false;
4243
4244 // Build a map between <original value, basic block where we saw it> to
4245 // value of base register.
4246 // Bail out if there is no common type.
4247 FoldAddrToValueMapping Map;
4248 if (!initializeMap(Map))
4249 return false;
4250
4251 CommonValue = findCommon(Map);
4252 if (CommonValue)
4253 AddrModes[0].SetCombinedField(DifferentField, CommonValue, AddrModes);
4254 return CommonValue != nullptr;
4255 }
4256
4257private:
4258 /// `CommonValue` may be a placeholder inserted by us.
4259 /// If the placeholder is not used, we should remove this dead instruction.
4260 void eraseCommonValueIfDead() {
4261 if (CommonValue && CommonValue->use_empty())
4262 if (Instruction *CommonInst = dyn_cast<Instruction>(CommonValue))
4263 CommonInst->eraseFromParent();
4264 }
4265
4266 /// Initialize Map with anchor values. For address seen
4267 /// we set the value of different field saw in this address.
4268 /// At the same time we find a common type for different field we will
4269 /// use to create new Phi/Select nodes. Keep it in CommonType field.
4270 /// Return false if there is no common type found.
4271 bool initializeMap(FoldAddrToValueMapping &Map) {
4272 // Keep track of keys where the value is null. We will need to replace it
4273 // with constant null when we know the common type.
4274 SmallVector<Value *, 2> NullValue;
4275 Type *IntPtrTy = DL.getIntPtrType(AddrModes[0].OriginalValue->getType());
4276 for (auto &AM : AddrModes) {
4277 Value *DV = AM.GetFieldAsValue(DifferentField, IntPtrTy);
4278 if (DV) {
4279 auto *Type = DV->getType();
4280 if (CommonType && CommonType != Type)
4281 return false;
4282 CommonType = Type;
4283 Map[AM.OriginalValue] = DV;
4284 } else {
4285 NullValue.push_back(AM.OriginalValue);
4286 }
4287 }
4288 assert(CommonType && "At least one non-null value must be!");
4289 for (auto *V : NullValue)
4290 Map[V] = Constant::getNullValue(CommonType);
4291 return true;
4292 }
4293
4294 /// We have mapping between value A and other value B where B was a field in
4295 /// addressing mode represented by A. Also we have an original value C
4296 /// representing an address we start with. Traversing from C through phi and
4297 /// selects we ended up with A's in a map. This utility function tries to find
4298 /// a value V which is a field in addressing mode C and traversing through phi
4299 /// nodes and selects we will end up in corresponded values B in a map.
4300 /// The utility will create a new Phi/Selects if needed.
4301 // The simple example looks as follows:
4302 // BB1:
4303 // p1 = b1 + 40
4304 // br cond BB2, BB3
4305 // BB2:
4306 // p2 = b2 + 40
4307 // br BB3
4308 // BB3:
4309 // p = phi [p1, BB1], [p2, BB2]
4310 // v = load p
4311 // Map is
4312 // p1 -> b1
4313 // p2 -> b2
4314 // Request is
4315 // p -> ?
4316 // The function tries to find or build phi [b1, BB1], [b2, BB2] in BB3.
4317 Value *findCommon(FoldAddrToValueMapping &Map) {
4318 // Tracks the simplification of newly created phi nodes. The reason we use
4319 // this mapping is because we will add new created Phi nodes in AddrToBase.
4320 // Simplification of Phi nodes is recursive, so some Phi node may
4321 // be simplified after we added it to AddrToBase. In reality this
4322 // simplification is possible only if original phi/selects were not
4323 // simplified yet.
4324 // Using this mapping we can find the current value in AddrToBase.
4325 SimplificationTracker ST;
4326
4327 // First step, DFS to create PHI nodes for all intermediate blocks.
4328 // Also fill traverse order for the second step.
4329 SmallVector<Value *, 32> TraverseOrder;
4330 InsertPlaceholders(Map, TraverseOrder, ST);
4331
4332 // Second Step, fill new nodes by merged values and simplify if possible.
4333 FillPlaceholders(Map, TraverseOrder, ST);
4334
4335 if (!AddrSinkNewSelects && ST.countNewSelectNodes() > 0) {
4336 ST.destroyNewNodes(CommonType);
4337 return nullptr;
4338 }
4339
4340 // Now we'd like to match New Phi nodes to existed ones.
4341 unsigned PhiNotMatchedCount = 0;
4342 if (!MatchPhiSet(ST, AddrSinkNewPhis, PhiNotMatchedCount)) {
4343 ST.destroyNewNodes(CommonType);
4344 return nullptr;
4345 }
4346
4347 auto *Result = ST.Get(Map.find(Original)->second);
4348 if (Result) {
4349 NumMemoryInstsPhiCreated += ST.countNewPhiNodes() + PhiNotMatchedCount;
4350 NumMemoryInstsSelectCreated += ST.countNewSelectNodes();
4351 }
4352 return Result;
4353 }
4354
4355 /// Try to match PHI node to Candidate.
4356 /// Matcher tracks the matched Phi nodes.
4357 bool MatchPhiNode(PHINode *PHI, PHINode *Candidate,
4358 SmallSetVector<PHIPair, 8> &Matcher,
4359 PhiNodeSet &PhiNodesToMatch) {
4360 SmallVector<PHIPair, 8> WorkList;
4361 Matcher.insert({PHI, Candidate});
4362 SmallPtrSet<PHINode *, 8> MatchedPHIs;
4363 MatchedPHIs.insert(PHI);
4364 WorkList.push_back({PHI, Candidate});
4365 SmallSet<PHIPair, 8> Visited;
4366 while (!WorkList.empty()) {
4367 auto Item = WorkList.pop_back_val();
4368 if (!Visited.insert(Item).second)
4369 continue;
4370 // We iterate over all incoming values to Phi to compare them.
4371 // If values are different and both of them Phi and the first one is a
4372 // Phi we added (subject to match) and both of them is in the same basic
4373 // block then we can match our pair if values match. So we state that
4374 // these values match and add it to work list to verify that.
4375 for (auto *B : Item.first->blocks()) {
4376 Value *FirstValue = Item.first->getIncomingValueForBlock(B);
4377 Value *SecondValue = Item.second->getIncomingValueForBlock(B);
4378 if (FirstValue == SecondValue)
4379 continue;
4380
4381 PHINode *FirstPhi = dyn_cast<PHINode>(FirstValue);
4382 PHINode *SecondPhi = dyn_cast<PHINode>(SecondValue);
4383
4384 // One of them is not Phi or
4385 // The first one is not Phi node from the set we'd like to match or
4386 // Phi nodes from different basic blocks then
4387 // we will not be able to match.
4388 if (!FirstPhi || !SecondPhi || !PhiNodesToMatch.count(FirstPhi) ||
4389 FirstPhi->getParent() != SecondPhi->getParent())
4390 return false;
4391
4392 // If we already matched them then continue.
4393 if (Matcher.count({FirstPhi, SecondPhi}))
4394 continue;
4395 // So the values are different and does not match. So we need them to
4396 // match. (But we register no more than one match per PHI node, so that
4397 // we won't later try to replace them twice.)
4398 if (MatchedPHIs.insert(FirstPhi).second)
4399 Matcher.insert({FirstPhi, SecondPhi});
4400 // But me must check it.
4401 WorkList.push_back({FirstPhi, SecondPhi});
4402 }
4403 }
4404 return true;
4405 }
4406
4407 /// For the given set of PHI nodes (in the SimplificationTracker) try
4408 /// to find their equivalents.
4409 /// Returns false if this matching fails and creation of new Phi is disabled.
4410 bool MatchPhiSet(SimplificationTracker &ST, bool AllowNewPhiNodes,
4411 unsigned &PhiNotMatchedCount) {
4412 // Matched and PhiNodesToMatch iterate their elements in a deterministic
4413 // order, so the replacements (ReplacePhi) are also done in a deterministic
4414 // order.
4415 SmallSetVector<PHIPair, 8> Matched;
4416 SmallPtrSet<PHINode *, 8> WillNotMatch;
4417 PhiNodeSet &PhiNodesToMatch = ST.newPhiNodes();
4418 while (PhiNodesToMatch.size()) {
4419 PHINode *PHI = *PhiNodesToMatch.begin();
4420
4421 // Add us, if no Phi nodes in the basic block we do not match.
4422 WillNotMatch.clear();
4423 WillNotMatch.insert(PHI);
4424
4425 // Traverse all Phis until we found equivalent or fail to do that.
4426 bool IsMatched = false;
4427 for (auto &P : PHI->getParent()->phis()) {
4428 // Skip new Phi nodes.
4429 if (PhiNodesToMatch.count(&P))
4430 continue;
4431 if ((IsMatched = MatchPhiNode(PHI, &P, Matched, PhiNodesToMatch)))
4432 break;
4433 // If it does not match, collect all Phi nodes from matcher.
4434 // if we end up with no match, them all these Phi nodes will not match
4435 // later.
4436 WillNotMatch.insert_range(llvm::make_first_range(Matched));
4437 Matched.clear();
4438 }
4439 if (IsMatched) {
4440 // Replace all matched values and erase them.
4441 for (auto MV : Matched)
4442 ST.ReplacePhi(MV.first, MV.second);
4443 Matched.clear();
4444 continue;
4445 }
4446 // If we are not allowed to create new nodes then bail out.
4447 if (!AllowNewPhiNodes)
4448 return false;
4449 // Just remove all seen values in matcher. They will not match anything.
4450 PhiNotMatchedCount += WillNotMatch.size();
4451 for (auto *P : WillNotMatch)
4452 PhiNodesToMatch.erase(P);
4453 }
4454 return true;
4455 }
4456 /// Fill the placeholders with values from predecessors and simplify them.
4457 void FillPlaceholders(FoldAddrToValueMapping &Map,
4458 SmallVectorImpl<Value *> &TraverseOrder,
4459 SimplificationTracker &ST) {
4460 while (!TraverseOrder.empty()) {
4461 Value *Current = TraverseOrder.pop_back_val();
4462 assert(Map.contains(Current) && "No node to fill!!!");
4463 Value *V = Map[Current];
4464
4465 if (SelectInst *Select = dyn_cast<SelectInst>(V)) {
4466 // CurrentValue also must be Select.
4467 auto *CurrentSelect = cast<SelectInst>(Current);
4468 auto *TrueValue = CurrentSelect->getTrueValue();
4469 assert(Map.contains(TrueValue) && "No True Value!");
4470 Select->setTrueValue(ST.Get(Map[TrueValue]));
4471 auto *FalseValue = CurrentSelect->getFalseValue();
4472 assert(Map.contains(FalseValue) && "No False Value!");
4473 Select->setFalseValue(ST.Get(Map[FalseValue]));
4474 } else {
4475 // Must be a Phi node then.
4476 auto *PHI = cast<PHINode>(V);
4477 // Fill the Phi node with values from predecessors.
4478 for (auto *B : predecessors(PHI->getParent())) {
4479 Value *PV = cast<PHINode>(Current)->getIncomingValueForBlock(B);
4480 assert(Map.contains(PV) && "No predecessor Value!");
4481 PHI->addIncoming(ST.Get(Map[PV]), B);
4482 }
4483 }
4484 }
4485 }
4486
4487 /// Starting from original value recursively iterates over def-use chain up to
4488 /// known ending values represented in a map. For each traversed phi/select
4489 /// inserts a placeholder Phi or Select.
4490 /// Reports all new created Phi/Select nodes by adding them to set.
4491 /// Also reports and order in what values have been traversed.
4492 void InsertPlaceholders(FoldAddrToValueMapping &Map,
4493 SmallVectorImpl<Value *> &TraverseOrder,
4494 SimplificationTracker &ST) {
4495 SmallVector<Value *, 32> Worklist;
4496 assert((isa<PHINode>(Original) || isa<SelectInst>(Original)) &&
4497 "Address must be a Phi or Select node");
4498 auto *Dummy = PoisonValue::get(CommonType);
4499 Worklist.push_back(Original);
4500 while (!Worklist.empty()) {
4501 Value *Current = Worklist.pop_back_val();
4502 // if it is already visited or it is an ending value then skip it.
4503 if (Map.contains(Current))
4504 continue;
4505 TraverseOrder.push_back(Current);
4506
4507 // CurrentValue must be a Phi node or select. All others must be covered
4508 // by anchors.
4509 if (SelectInst *CurrentSelect = dyn_cast<SelectInst>(Current)) {
4510 // Is it OK to get metadata from OrigSelect?!
4511 // Create a Select placeholder with dummy value.
4512 SelectInst *Select =
4513 SelectInst::Create(CurrentSelect->getCondition(), Dummy, Dummy,
4514 CurrentSelect->getName(),
4515 CurrentSelect->getIterator(), CurrentSelect);
4516 Map[Current] = Select;
4517 ST.insertNewSelect(Select);
4518 // We are interested in True and False values.
4519 Worklist.push_back(CurrentSelect->getTrueValue());
4520 Worklist.push_back(CurrentSelect->getFalseValue());
4521 } else {
4522 // It must be a Phi node then.
4523 PHINode *CurrentPhi = cast<PHINode>(Current);
4524 unsigned PredCount = CurrentPhi->getNumIncomingValues();
4525 PHINode *PHI =
4526 PHINode::Create(CommonType, PredCount, "sunk_phi", CurrentPhi->getIterator());
4527 Map[Current] = PHI;
4528 ST.insertNewPhi(PHI);
4529 append_range(Worklist, CurrentPhi->incoming_values());
4530 }
4531 }
4532 }
4533
4534 bool addrModeCombiningAllowed() {
4536 return false;
4537 switch (DifferentField) {
4538 default:
4539 return false;
4540 case ExtAddrMode::BaseRegField:
4542 case ExtAddrMode::BaseGVField:
4543 return AddrSinkCombineBaseGV;
4544 case ExtAddrMode::BaseOffsField:
4546 case ExtAddrMode::ScaledRegField:
4548 }
4549 }
4550};
4551} // end anonymous namespace
4552
4553/// Try adding ScaleReg*Scale to the current addressing mode.
4554/// Return true and update AddrMode if this addr mode is legal for the target,
4555/// false if not.
4556bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
4557 unsigned Depth) {
4558 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
4559 // mode. Just process that directly.
4560 if (Scale == 1)
4561 return matchAddr(ScaleReg, Depth);
4562
4563 // If the scale is 0, it takes nothing to add this.
4564 if (Scale == 0)
4565 return true;
4566
4567 // If we already have a scale of this value, we can add to it, otherwise, we
4568 // need an available scale field.
4569 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
4570 return false;
4571
4572 ExtAddrMode TestAddrMode = AddrMode;
4573
4574 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
4575 // [A+B + A*7] -> [B+A*8].
4576 TestAddrMode.Scale += Scale;
4577 TestAddrMode.ScaledReg = ScaleReg;
4578
4579 // If the new address isn't legal, bail out.
4580 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
4581 return false;
4582
4583 // It was legal, so commit it.
4584 AddrMode = TestAddrMode;
4585
4586 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
4587 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
4588 // X*Scale + C*Scale to addr mode. If we found available IV increment, do not
4589 // go any further: we can reuse it and cannot eliminate it.
4590 ConstantInt *CI = nullptr;
4591 Value *AddLHS = nullptr;
4592 if (isa<Instruction>(ScaleReg) && // not a constant expr.
4593 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI))) &&
4594 !isIVIncrement(ScaleReg, &LI) && CI->getValue().isSignedIntN(64)) {
4595 TestAddrMode.InBounds = false;
4596 TestAddrMode.ScaledReg = AddLHS;
4597 TestAddrMode.BaseOffs += CI->getSExtValue() * TestAddrMode.Scale;
4598
4599 // If this addressing mode is legal, commit it and remember that we folded
4600 // this instruction.
4601 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
4602 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
4603 AddrMode = TestAddrMode;
4604 return true;
4605 }
4606 // Restore status quo.
4607 TestAddrMode = AddrMode;
4608 }
4609
4610 // If this is an add recurrence with a constant step, return the increment
4611 // instruction and the canonicalized step.
4612 auto GetConstantStep =
4613 [this](const Value *V) -> std::optional<std::pair<Instruction *, APInt>> {
4614 auto *PN = dyn_cast<PHINode>(V);
4615 if (!PN)
4616 return std::nullopt;
4617 auto IVInc = getIVIncrement(PN, &LI);
4618 if (!IVInc)
4619 return std::nullopt;
4620 // TODO: The result of the intrinsics above is two-complement. However when
4621 // IV inc is expressed as add or sub, iv.next is potentially a poison value.
4622 // If it has nuw or nsw flags, we need to make sure that these flags are
4623 // inferrable at the point of memory instruction. Otherwise we are replacing
4624 // well-defined two-complement computation with poison. Currently, to avoid
4625 // potentially complex analysis needed to prove this, we reject such cases.
4626 if (auto *OIVInc = dyn_cast<OverflowingBinaryOperator>(IVInc->first))
4627 if (OIVInc->hasNoSignedWrap() || OIVInc->hasNoUnsignedWrap())
4628 return std::nullopt;
4629 if (auto *ConstantStep = dyn_cast<ConstantInt>(IVInc->second))
4630 return std::make_pair(IVInc->first, ConstantStep->getValue());
4631 return std::nullopt;
4632 };
4633
4634 // Try to account for the following special case:
4635 // 1. ScaleReg is an inductive variable;
4636 // 2. We use it with non-zero offset;
4637 // 3. IV's increment is available at the point of memory instruction.
4638 //
4639 // In this case, we may reuse the IV increment instead of the IV Phi to
4640 // achieve the following advantages:
4641 // 1. If IV step matches the offset, we will have no need in the offset;
4642 // 2. Even if they don't match, we will reduce the overlap of living IV
4643 // and IV increment, that will potentially lead to better register
4644 // assignment.
4645 if (AddrMode.BaseOffs) {
4646 if (auto IVStep = GetConstantStep(ScaleReg)) {
4647 Instruction *IVInc = IVStep->first;
4648 // The following assert is important to ensure a lack of infinite loops.
4649 // This transforms is (intentionally) the inverse of the one just above.
4650 // If they don't agree on the definition of an increment, we'd alternate
4651 // back and forth indefinitely.
4652 assert(isIVIncrement(IVInc, &LI) && "implied by GetConstantStep");
4653 APInt Step = IVStep->second;
4654 APInt Offset = Step * AddrMode.Scale;
4655 if (Offset.isSignedIntN(64)) {
4656 TestAddrMode.InBounds = false;
4657 TestAddrMode.ScaledReg = IVInc;
4658 TestAddrMode.BaseOffs -= Offset.getLimitedValue();
4659 // If this addressing mode is legal, commit it..
4660 // (Note that we defer the (expensive) domtree base legality check
4661 // to the very last possible point.)
4662 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace) &&
4663 getDTFn().dominates(IVInc, MemoryInst)) {
4664 AddrModeInsts.push_back(cast<Instruction>(IVInc));
4665 AddrMode = TestAddrMode;
4666 return true;
4667 }
4668 // Restore status quo.
4669 TestAddrMode = AddrMode;
4670 }
4671 }
4672 }
4673
4674 // Otherwise, just return what we have.
4675 return true;
4676}
4677
4678/// This is a little filter, which returns true if an addressing computation
4679/// involving I might be folded into a load/store accessing it.
4680/// This doesn't need to be perfect, but needs to accept at least
4681/// the set of instructions that MatchOperationAddr can.
4683 switch (I->getOpcode()) {
4684 case Instruction::BitCast:
4685 case Instruction::AddrSpaceCast:
4686 // Don't touch identity bitcasts.
4687 if (I->getType() == I->getOperand(0)->getType())
4688 return false;
4689 return I->getType()->isIntOrPtrTy();
4690 case Instruction::PtrToInt:
4691 // PtrToInt is always a noop, as we know that the int type is pointer sized.
4692 return true;
4693 case Instruction::IntToPtr:
4694 // We know the input is intptr_t, so this is foldable.
4695 return true;
4696 case Instruction::Add:
4697 return true;
4698 case Instruction::Mul:
4699 case Instruction::Shl:
4700 // Can only handle X*C and X << C.
4701 return isa<ConstantInt>(I->getOperand(1));
4702 case Instruction::GetElementPtr:
4703 return true;
4704 default:
4705 return false;
4706 }
4707}
4708
4709/// Check whether or not \p Val is a legal instruction for \p TLI.
4710/// \note \p Val is assumed to be the product of some type promotion.
4711/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
4712/// to be legal, as the non-promoted value would have had the same state.
4714 const DataLayout &DL, Value *Val) {
4715 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
4716 if (!PromotedInst)
4717 return false;
4718 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
4719 // If the ISDOpcode is undefined, it was undefined before the promotion.
4720 if (!ISDOpcode)
4721 return true;
4722 // Otherwise, check if the promoted instruction is legal or not.
4723 return TLI.isOperationLegalOrCustom(
4724 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
4725}
4726
4727namespace {
4728
4729/// Hepler class to perform type promotion.
4730class TypePromotionHelper {
4731 /// Utility function to add a promoted instruction \p ExtOpnd to
4732 /// \p PromotedInsts and record the type of extension we have seen.
4733 static void addPromotedInst(InstrToOrigTy &PromotedInsts,
4734 Instruction *ExtOpnd, bool IsSExt) {
4735 ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension;
4736 auto [It, Inserted] = PromotedInsts.try_emplace(ExtOpnd);
4737 if (!Inserted) {
4738 // If the new extension is same as original, the information in
4739 // PromotedInsts[ExtOpnd] is still correct.
4740 if (It->second.getInt() == ExtTy)
4741 return;
4742
4743 // Now the new extension is different from old extension, we make
4744 // the type information invalid by setting extension type to
4745 // BothExtension.
4746 ExtTy = BothExtension;
4747 }
4748 It->second = TypeIsSExt(ExtOpnd->getType(), ExtTy);
4749 }
4750
4751 /// Utility function to query the original type of instruction \p Opnd
4752 /// with a matched extension type. If the extension doesn't match, we
4753 /// cannot use the information we had on the original type.
4754 /// BothExtension doesn't match any extension type.
4755 static const Type *getOrigType(const InstrToOrigTy &PromotedInsts,
4756 Instruction *Opnd, bool IsSExt) {
4757 ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension;
4758 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
4759 if (It != PromotedInsts.end() && It->second.getInt() == ExtTy)
4760 return It->second.getPointer();
4761 return nullptr;
4762 }
4763
4764 /// Utility function to check whether or not a sign or zero extension
4765 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
4766 /// either using the operands of \p Inst or promoting \p Inst.
4767 /// The type of the extension is defined by \p IsSExt.
4768 /// In other words, check if:
4769 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
4770 /// #1 Promotion applies:
4771 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
4772 /// #2 Operand reuses:
4773 /// ext opnd1 to ConsideredExtType.
4774 /// \p PromotedInsts maps the instructions to their type before promotion.
4775 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
4776 const InstrToOrigTy &PromotedInsts, bool IsSExt);
4777
4778 /// Utility function to determine if \p OpIdx should be promoted when
4779 /// promoting \p Inst.
4780 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
4781 return !(isa<SelectInst>(Inst) && OpIdx == 0);
4782 }
4783
4784 /// Utility function to promote the operand of \p Ext when this
4785 /// operand is a promotable trunc or sext or zext.
4786 /// \p PromotedInsts maps the instructions to their type before promotion.
4787 /// \p CreatedInstsCost[out] contains the cost of all instructions
4788 /// created to promote the operand of Ext.
4789 /// Newly added extensions are inserted in \p Exts.
4790 /// Newly added truncates are inserted in \p Truncs.
4791 /// Should never be called directly.
4792 /// \return The promoted value which is used instead of Ext.
4793 static Value *promoteOperandForTruncAndAnyExt(
4794 Instruction *Ext, TypePromotionTransaction &TPT,
4795 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4796 SmallVectorImpl<Instruction *> *Exts,
4797 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
4798
4799 /// Utility function to promote the operand of \p Ext when this
4800 /// operand is promotable and is not a supported trunc or sext.
4801 /// \p PromotedInsts maps the instructions to their type before promotion.
4802 /// \p CreatedInstsCost[out] contains the cost of all the instructions
4803 /// created to promote the operand of Ext.
4804 /// Newly added extensions are inserted in \p Exts.
4805 /// Newly added truncates are inserted in \p Truncs.
4806 /// Should never be called directly.
4807 /// \return The promoted value which is used instead of Ext.
4808 static Value *promoteOperandForOther(Instruction *Ext,
4809 TypePromotionTransaction &TPT,
4810 InstrToOrigTy &PromotedInsts,
4811 unsigned &CreatedInstsCost,
4812 SmallVectorImpl<Instruction *> *Exts,
4813 SmallVectorImpl<Instruction *> *Truncs,
4814 const TargetLowering &TLI, bool IsSExt);
4815
4816 /// \see promoteOperandForOther.
4817 static Value *signExtendOperandForOther(
4818 Instruction *Ext, TypePromotionTransaction &TPT,
4819 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4820 SmallVectorImpl<Instruction *> *Exts,
4821 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
4822 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
4823 Exts, Truncs, TLI, true);
4824 }
4825
4826 /// \see promoteOperandForOther.
4827 static Value *zeroExtendOperandForOther(
4828 Instruction *Ext, TypePromotionTransaction &TPT,
4829 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4830 SmallVectorImpl<Instruction *> *Exts,
4831 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
4832 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
4833 Exts, Truncs, TLI, false);
4834 }
4835
4836public:
4837 /// Type for the utility function that promotes the operand of Ext.
4838 using Action = Value *(*)(Instruction *Ext, TypePromotionTransaction &TPT,
4839 InstrToOrigTy &PromotedInsts,
4840 unsigned &CreatedInstsCost,
4841 SmallVectorImpl<Instruction *> *Exts,
4842 SmallVectorImpl<Instruction *> *Truncs,
4843 const TargetLowering &TLI);
4844
4845 /// Given a sign/zero extend instruction \p Ext, return the appropriate
4846 /// action to promote the operand of \p Ext instead of using Ext.
4847 /// \return NULL if no promotable action is possible with the current
4848 /// sign extension.
4849 /// \p InsertedInsts keeps track of all the instructions inserted by the
4850 /// other CodeGenPrepare optimizations. This information is important
4851 /// because we do not want to promote these instructions as CodeGenPrepare
4852 /// will reinsert them later. Thus creating an infinite loop: create/remove.
4853 /// \p PromotedInsts maps the instructions to their type before promotion.
4854 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
4855 const TargetLowering &TLI,
4856 const InstrToOrigTy &PromotedInsts);
4857};
4858
4859} // end anonymous namespace
4860
4861bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
4862 Type *ConsideredExtType,
4863 const InstrToOrigTy &PromotedInsts,
4864 bool IsSExt) {
4865 // The promotion helper does not know how to deal with vector types yet.
4866 // To be able to fix that, we would need to fix the places where we
4867 // statically extend, e.g., constants and such.
4868 if (Inst->getType()->isVectorTy())
4869 return false;
4870
4871 // We can always get through zext.
4872 if (isa<ZExtInst>(Inst))
4873 return true;
4874
4875 // sext(sext) is ok too.
4876 if (IsSExt && isa<SExtInst>(Inst))
4877 return true;
4878
4879 // We can get through binary operator, if it is legal. In other words, the
4880 // binary operator must have a nuw or nsw flag.
4881 if (const auto *BinOp = dyn_cast<BinaryOperator>(Inst))
4882 if (isa<OverflowingBinaryOperator>(BinOp) &&
4883 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
4884 (IsSExt && BinOp->hasNoSignedWrap())))
4885 return true;
4886
4887 // ext(and(opnd, cst)) --> and(ext(opnd), ext(cst))
4888 if ((Inst->getOpcode() == Instruction::And ||
4889 Inst->getOpcode() == Instruction::Or))
4890 return true;
4891
4892 // ext(xor(opnd, cst)) --> xor(ext(opnd), ext(cst))
4893 if (Inst->getOpcode() == Instruction::Xor) {
4894 // Make sure it is not a NOT.
4895 if (const auto *Cst = dyn_cast<ConstantInt>(Inst->getOperand(1)))
4896 if (!Cst->getValue().isAllOnes())
4897 return true;
4898 }
4899
4900 // zext(shrl(opnd, cst)) --> shrl(zext(opnd), zext(cst))
4901 // It may change a poisoned value into a regular value, like
4902 // zext i32 (shrl i8 %val, 12) --> shrl i32 (zext i8 %val), 12
4903 // poisoned value regular value
4904 // It should be OK since undef covers valid value.
4905 if (Inst->getOpcode() == Instruction::LShr && !IsSExt)
4906 return true;
4907
4908 // and(ext(shl(opnd, cst)), cst) --> and(shl(ext(opnd), ext(cst)), cst)
4909 // It may change a poisoned value into a regular value, like
4910 // zext i32 (shl i8 %val, 12) --> shl i32 (zext i8 %val), 12
4911 // poisoned value regular value
4912 // It should be OK since undef covers valid value.
4913 if (Inst->getOpcode() == Instruction::Shl && Inst->hasOneUse()) {
4914 const auto *ExtInst = cast<const Instruction>(*Inst->user_begin());
4915 if (ExtInst->hasOneUse()) {
4916 const auto *AndInst = dyn_cast<const Instruction>(*ExtInst->user_begin());
4917 if (AndInst && AndInst->getOpcode() == Instruction::And) {
4918 const auto *Cst = dyn_cast<ConstantInt>(AndInst->getOperand(1));
4919 if (Cst &&
4920 Cst->getValue().isIntN(Inst->getType()->getIntegerBitWidth()))
4921 return true;
4922 }
4923 }
4924 }
4925
4926 // Check if we can do the following simplification.
4927 // ext(trunc(opnd)) --> ext(opnd)
4928 if (!isa<TruncInst>(Inst))
4929 return false;
4930
4931 Value *OpndVal = Inst->getOperand(0);
4932 // Check if we can use this operand in the extension.
4933 // If the type is larger than the result type of the extension, we cannot.
4934 if (!OpndVal->getType()->isIntegerTy() ||
4935 OpndVal->getType()->getIntegerBitWidth() >
4936 ConsideredExtType->getIntegerBitWidth())
4937 return false;
4938
4939 // If the operand of the truncate is not an instruction, we will not have
4940 // any information on the dropped bits.
4941 // (Actually we could for constant but it is not worth the extra logic).
4942 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
4943 if (!Opnd)
4944 return false;
4945
4946 // Check if the source of the type is narrow enough.
4947 // I.e., check that trunc just drops extended bits of the same kind of
4948 // the extension.
4949 // #1 get the type of the operand and check the kind of the extended bits.
4950 const Type *OpndType = getOrigType(PromotedInsts, Opnd, IsSExt);
4951 if (OpndType)
4952 ;
4953 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
4954 OpndType = Opnd->getOperand(0)->getType();
4955 else
4956 return false;
4957
4958 // #2 check that the truncate just drops extended bits.
4959 return Inst->getType()->getIntegerBitWidth() >=
4960 OpndType->getIntegerBitWidth();
4961}
4962
4963TypePromotionHelper::Action TypePromotionHelper::getAction(
4964 Instruction *Ext, const SetOfInstrs &InsertedInsts,
4965 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
4966 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
4967 "Unexpected instruction type");
4968 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
4969 Type *ExtTy = Ext->getType();
4970 bool IsSExt = isa<SExtInst>(Ext);
4971 // If the operand of the extension is not an instruction, we cannot
4972 // get through.
4973 // If it, check we can get through.
4974 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
4975 return nullptr;
4976
4977 // Do not promote if the operand has been added by codegenprepare.
4978 // Otherwise, it means we are undoing an optimization that is likely to be
4979 // redone, thus causing potential infinite loop.
4980 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
4981 return nullptr;
4982
4983 // SExt or Trunc instructions.
4984 // Return the related handler.
4985 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
4986 isa<ZExtInst>(ExtOpnd))
4987 return promoteOperandForTruncAndAnyExt;
4988
4989 // Regular instruction.
4990 // Abort early if we will have to insert non-free instructions.
4991 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
4992 return nullptr;
4993 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
4994}
4995
4996Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
4997 Instruction *SExt, TypePromotionTransaction &TPT,
4998 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4999 SmallVectorImpl<Instruction *> *Exts,
5000 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
5001 // By construction, the operand of SExt is an instruction. Otherwise we cannot
5002 // get through it and this method should not be called.
5003 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
5004 Value *ExtVal = SExt;
5005 bool HasMergedNonFreeExt = false;
5006 if (isa<ZExtInst>(SExtOpnd)) {
5007 // Replace s|zext(zext(opnd))
5008 // => zext(opnd).
5009 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
5010 Value *ZExt =
5011 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
5012 TPT.replaceAllUsesWith(SExt, ZExt);
5013 TPT.eraseInstruction(SExt);
5014 ExtVal = ZExt;
5015 } else {
5016 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
5017 // => z|sext(opnd).
5018 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
5019 }
5020 CreatedInstsCost = 0;
5021
5022 // Remove dead code.
5023 if (SExtOpnd->use_empty())
5024 TPT.eraseInstruction(SExtOpnd);
5025
5026 // Check if the extension is still needed.
5027 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
5028 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
5029 if (ExtInst) {
5030 if (Exts)
5031 Exts->push_back(ExtInst);
5032 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
5033 }
5034 return ExtVal;
5035 }
5036
5037 // At this point we have: ext ty opnd to ty.
5038 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
5039 Value *NextVal = ExtInst->getOperand(0);
5040 TPT.eraseInstruction(ExtInst, NextVal);
5041 return NextVal;
5042}
5043
5044Value *TypePromotionHelper::promoteOperandForOther(
5045 Instruction *Ext, TypePromotionTransaction &TPT,
5046 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
5047 SmallVectorImpl<Instruction *> *Exts,
5048 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
5049 bool IsSExt) {
5050 // By construction, the operand of Ext is an instruction. Otherwise we cannot
5051 // get through it and this method should not be called.
5052 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
5053 CreatedInstsCost = 0;
5054 if (!ExtOpnd->hasOneUse()) {
5055 // ExtOpnd will be promoted.
5056 // All its uses, but Ext, will need to use a truncated value of the
5057 // promoted version.
5058 // Create the truncate now.
5059 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
5060 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
5061 // Insert it just after the definition.
5062 ITrunc->moveAfter(ExtOpnd);
5063 if (Truncs)
5064 Truncs->push_back(ITrunc);
5065 }
5066
5067 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
5068 // Restore the operand of Ext (which has been replaced by the previous call
5069 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
5070 TPT.setOperand(Ext, 0, ExtOpnd);
5071 }
5072
5073 // Get through the Instruction:
5074 // 1. Update its type.
5075 // 2. Replace the uses of Ext by Inst.
5076 // 3. Extend each operand that needs to be extended.
5077
5078 // Remember the original type of the instruction before promotion.
5079 // This is useful to know that the high bits are sign extended bits.
5080 addPromotedInst(PromotedInsts, ExtOpnd, IsSExt);
5081 // Step #1.
5082 TPT.mutateType(ExtOpnd, Ext->getType());
5083 // Step #2.
5084 TPT.replaceAllUsesWith(Ext, ExtOpnd);
5085 // Step #3.
5086 LLVM_DEBUG(dbgs() << "Propagate Ext to operands\n");
5087 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
5088 ++OpIdx) {
5089 LLVM_DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
5090 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
5091 !shouldExtOperand(ExtOpnd, OpIdx)) {
5092 LLVM_DEBUG(dbgs() << "No need to propagate\n");
5093 continue;
5094 }
5095 // Check if we can statically extend the operand.
5096 Value *Opnd = ExtOpnd->getOperand(OpIdx);
5097 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
5098 LLVM_DEBUG(dbgs() << "Statically extend\n");
5099 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
5100 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
5101 : Cst->getValue().zext(BitWidth);
5102 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
5103 continue;
5104 }
5105 // UndefValue are typed, so we have to statically sign extend them.
5106 if (isa<UndefValue>(Opnd)) {
5107 LLVM_DEBUG(dbgs() << "Statically extend\n");
5108 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
5109 continue;
5110 }
5111
5112 // Otherwise we have to explicitly sign extend the operand.
5113 Value *ValForExtOpnd = IsSExt
5114 ? TPT.createSExt(ExtOpnd, Opnd, Ext->getType())
5115 : TPT.createZExt(ExtOpnd, Opnd, Ext->getType());
5116 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
5117 Instruction *InstForExtOpnd = dyn_cast<Instruction>(ValForExtOpnd);
5118 if (!InstForExtOpnd)
5119 continue;
5120
5121 if (Exts)
5122 Exts->push_back(InstForExtOpnd);
5123
5124 CreatedInstsCost += !TLI.isExtFree(InstForExtOpnd);
5125 }
5126 LLVM_DEBUG(dbgs() << "Extension is useless now\n");
5127 TPT.eraseInstruction(Ext);
5128 return ExtOpnd;
5129}
5130
5131/// Check whether or not promoting an instruction to a wider type is profitable.
5132/// \p NewCost gives the cost of extension instructions created by the
5133/// promotion.
5134/// \p OldCost gives the cost of extension instructions before the promotion
5135/// plus the number of instructions that have been
5136/// matched in the addressing mode the promotion.
5137/// \p PromotedOperand is the value that has been promoted.
5138/// \return True if the promotion is profitable, false otherwise.
5139bool AddressingModeMatcher::isPromotionProfitable(
5140 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
5141 LLVM_DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost
5142 << '\n');
5143 // The cost of the new extensions is greater than the cost of the
5144 // old extension plus what we folded.
5145 // This is not profitable.
5146 if (NewCost > OldCost)
5147 return false;
5148 if (NewCost < OldCost)
5149 return true;
5150 // The promotion is neutral but it may help folding the sign extension in
5151 // loads for instance.
5152 // Check that we did not create an illegal instruction.
5153 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
5154}
5155
5156/// Given an instruction or constant expr, see if we can fold the operation
5157/// into the addressing mode. If so, update the addressing mode and return
5158/// true, otherwise return false without modifying AddrMode.
5159/// If \p MovedAway is not NULL, it contains the information of whether or
5160/// not AddrInst has to be folded into the addressing mode on success.
5161/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
5162/// because it has been moved away.
5163/// Thus AddrInst must not be added in the matched instructions.
5164/// This state can happen when AddrInst is a sext, since it may be moved away.
5165/// Therefore, AddrInst may not be valid when MovedAway is true and it must
5166/// not be referenced anymore.
5167bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
5168 unsigned Depth,
5169 bool *MovedAway) {
5170 // Avoid exponential behavior on extremely deep expression trees.
5171 if (Depth >= 5)
5172 return false;
5173
5174 // By default, all matched instructions stay in place.
5175 if (MovedAway)
5176 *MovedAway = false;
5177
5178 switch (Opcode) {
5179 case Instruction::PtrToInt:
5180 // PtrToInt is always a noop, as we know that the int type is pointer sized.
5181 return matchAddr(AddrInst->getOperand(0), Depth);
5182 case Instruction::IntToPtr: {
5183 auto AS = AddrInst->getType()->getPointerAddressSpace();
5184 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
5185 // This inttoptr is a no-op if the integer type is pointer sized.
5186 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
5187 return matchAddr(AddrInst->getOperand(0), Depth);
5188 return false;
5189 }
5190 case Instruction::BitCast:
5191 // BitCast is always a noop, and we can handle it as long as it is
5192 // int->int or pointer->pointer (we don't want int<->fp or something).
5193 if (AddrInst->getOperand(0)->getType()->isIntOrPtrTy() &&
5194 // Don't touch identity bitcasts. These were probably put here by LSR,
5195 // and we don't want to mess around with them. Assume it knows what it
5196 // is doing.
5197 AddrInst->getOperand(0)->getType() != AddrInst->getType())
5198 return matchAddr(AddrInst->getOperand(0), Depth);
5199 return false;
5200 case Instruction::AddrSpaceCast: {
5201 unsigned SrcAS =
5202 AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
5203 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
5204 if (TLI.getTargetMachine().isNoopAddrSpaceCast(SrcAS, DestAS))
5205 return matchAddr(AddrInst->getOperand(0), Depth);
5206 return false;
5207 }
5208 case Instruction::Add: {
5209 // Check to see if we can merge in one operand, then the other. If so, we
5210 // win.
5211 ExtAddrMode BackupAddrMode = AddrMode;
5212 unsigned OldSize = AddrModeInsts.size();
5213 // Start a transaction at this point.
5214 // The LHS may match but not the RHS.
5215 // Therefore, we need a higher level restoration point to undo partially
5216 // matched operation.
5217 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5218 TPT.getRestorationPoint();
5219
5220 // Try to match an integer constant second to increase its chance of ending
5221 // up in `BaseOffs`, resp. decrease its chance of ending up in `BaseReg`.
5222 int First = 0, Second = 1;
5223 if (isa<ConstantInt>(AddrInst->getOperand(First))
5224 && !isa<ConstantInt>(AddrInst->getOperand(Second)))
5225 std::swap(First, Second);
5226 AddrMode.InBounds = false;
5227 if (matchAddr(AddrInst->getOperand(First), Depth + 1) &&
5228 matchAddr(AddrInst->getOperand(Second), Depth + 1))
5229 return true;
5230
5231 // Restore the old addr mode info.
5232 AddrMode = BackupAddrMode;
5233 AddrModeInsts.resize(OldSize);
5234 TPT.rollback(LastKnownGood);
5235
5236 // Otherwise this was over-aggressive. Try merging operands in the opposite
5237 // order.
5238 if (matchAddr(AddrInst->getOperand(Second), Depth + 1) &&
5239 matchAddr(AddrInst->getOperand(First), Depth + 1))
5240 return true;
5241
5242 // Otherwise we definitely can't merge the ADD in.
5243 AddrMode = BackupAddrMode;
5244 AddrModeInsts.resize(OldSize);
5245 TPT.rollback(LastKnownGood);
5246 break;
5247 }
5248 // case Instruction::Or:
5249 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
5250 // break;
5251 case Instruction::Mul:
5252 case Instruction::Shl: {
5253 // Can only handle X*C and X << C.
5254 AddrMode.InBounds = false;
5255 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
5256 if (!RHS || RHS->getBitWidth() > 64)
5257 return false;
5258 int64_t Scale = Opcode == Instruction::Shl
5259 ? 1LL << RHS->getLimitedValue(RHS->getBitWidth() - 1)
5260 : RHS->getSExtValue();
5261
5262 return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
5263 }
5264 case Instruction::GetElementPtr: {
5265 // Scan the GEP. We check it if it contains constant offsets and at most
5266 // one variable offset.
5267 int VariableOperand = -1;
5268 unsigned VariableScale = 0;
5269
5270 int64_t ConstantOffset = 0;
5271 gep_type_iterator GTI = gep_type_begin(AddrInst);
5272 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
5273 if (StructType *STy = GTI.getStructTypeOrNull()) {
5274 const StructLayout *SL = DL.getStructLayout(STy);
5275 unsigned Idx =
5276 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
5277 ConstantOffset += SL->getElementOffset(Idx);
5278 } else {
5279 TypeSize TS = GTI.getSequentialElementStride(DL);
5280 if (TS.isNonZero()) {
5281 // The optimisations below currently only work for fixed offsets.
5282 if (TS.isScalable())
5283 return false;
5284 int64_t TypeSize = TS.getFixedValue();
5285 if (ConstantInt *CI =
5286 dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
5287 const APInt &CVal = CI->getValue();
5288 if (CVal.getSignificantBits() <= 64) {
5289 ConstantOffset += CVal.getSExtValue() * TypeSize;
5290 continue;
5291 }
5292 }
5293 // We only allow one variable index at the moment.
5294 if (VariableOperand != -1)
5295 return false;
5296
5297 // Remember the variable index.
5298 VariableOperand = i;
5299 VariableScale = TypeSize;
5300 }
5301 }
5302 }
5303
5304 // A common case is for the GEP to only do a constant offset. In this case,
5305 // just add it to the disp field and check validity.
5306 if (VariableOperand == -1) {
5307 AddrMode.BaseOffs += ConstantOffset;
5308 if (matchAddr(AddrInst->getOperand(0), Depth + 1)) {
5309 if (!cast<GEPOperator>(AddrInst)->isInBounds())
5310 AddrMode.InBounds = false;
5311 return true;
5312 }
5313 AddrMode.BaseOffs -= ConstantOffset;
5314
5316 TLI.shouldConsiderGEPOffsetSplit() && Depth == 0 &&
5317 ConstantOffset > 0) {
5318 // Record GEPs with non-zero offsets as candidates for splitting in
5319 // the event that the offset cannot fit into the r+i addressing mode.
5320 // Simple and common case that only one GEP is used in calculating the
5321 // address for the memory access.
5322 Value *Base = AddrInst->getOperand(0);
5323 auto *BaseI = dyn_cast<Instruction>(Base);
5324 auto *GEP = cast<GetElementPtrInst>(AddrInst);
5326 (BaseI && !isa<CastInst>(BaseI) &&
5327 !isa<GetElementPtrInst>(BaseI))) {
5328 // Make sure the parent block allows inserting non-PHI instructions
5329 // before the terminator.
5330 BasicBlock *Parent = BaseI ? BaseI->getParent()
5331 : &GEP->getFunction()->getEntryBlock();
5332 if (!Parent->getTerminator()->isEHPad())
5333 LargeOffsetGEP = std::make_pair(GEP, ConstantOffset);
5334 }
5335 }
5336
5337 return false;
5338 }
5339
5340 // Save the valid addressing mode in case we can't match.
5341 ExtAddrMode BackupAddrMode = AddrMode;
5342 unsigned OldSize = AddrModeInsts.size();
5343
5344 // See if the scale and offset amount is valid for this target.
5345 AddrMode.BaseOffs += ConstantOffset;
5346 if (!cast<GEPOperator>(AddrInst)->isInBounds())
5347 AddrMode.InBounds = false;
5348
5349 // Match the base operand of the GEP.
5350 if (!matchAddr(AddrInst->getOperand(0), Depth + 1)) {
5351 // If it couldn't be matched, just stuff the value in a register.
5352 if (AddrMode.HasBaseReg) {
5353 AddrMode = BackupAddrMode;
5354 AddrModeInsts.resize(OldSize);
5355 return false;
5356 }
5357 AddrMode.HasBaseReg = true;
5358 AddrMode.BaseReg = AddrInst->getOperand(0);
5359 }
5360
5361 // Match the remaining variable portion of the GEP.
5362 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
5363 Depth)) {
5364 // If it couldn't be matched, try stuffing the base into a register
5365 // instead of matching it, and retrying the match of the scale.
5366 AddrMode = BackupAddrMode;
5367 AddrModeInsts.resize(OldSize);
5368 if (AddrMode.HasBaseReg)
5369 return false;
5370 AddrMode.HasBaseReg = true;
5371 AddrMode.BaseReg = AddrInst->getOperand(0);
5372 AddrMode.BaseOffs += ConstantOffset;
5373 if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
5374 VariableScale, Depth)) {
5375 // If even that didn't work, bail.
5376 AddrMode = BackupAddrMode;
5377 AddrModeInsts.resize(OldSize);
5378 return false;
5379 }
5380 }
5381
5382 return true;
5383 }
5384 case Instruction::SExt:
5385 case Instruction::ZExt: {
5386 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
5387 if (!Ext)
5388 return false;
5389
5390 // Try to move this ext out of the way of the addressing mode.
5391 // Ask for a method for doing so.
5392 TypePromotionHelper::Action TPH =
5393 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
5394 if (!TPH)
5395 return false;
5396
5397 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5398 TPT.getRestorationPoint();
5399 unsigned CreatedInstsCost = 0;
5400 unsigned ExtCost = !TLI.isExtFree(Ext);
5401 Value *PromotedOperand =
5402 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
5403 // SExt has been moved away.
5404 // Thus either it will be rematched later in the recursive calls or it is
5405 // gone. Anyway, we must not fold it into the addressing mode at this point.
5406 // E.g.,
5407 // op = add opnd, 1
5408 // idx = ext op
5409 // addr = gep base, idx
5410 // is now:
5411 // promotedOpnd = ext opnd <- no match here
5412 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
5413 // addr = gep base, op <- match
5414 if (MovedAway)
5415 *MovedAway = true;
5416
5417 assert(PromotedOperand &&
5418 "TypePromotionHelper should have filtered out those cases");
5419
5420 ExtAddrMode BackupAddrMode = AddrMode;
5421 unsigned OldSize = AddrModeInsts.size();
5422
5423 if (!matchAddr(PromotedOperand, Depth) ||
5424 // The total of the new cost is equal to the cost of the created
5425 // instructions.
5426 // The total of the old cost is equal to the cost of the extension plus
5427 // what we have saved in the addressing mode.
5428 !isPromotionProfitable(CreatedInstsCost,
5429 ExtCost + (AddrModeInsts.size() - OldSize),
5430 PromotedOperand)) {
5431 AddrMode = BackupAddrMode;
5432 AddrModeInsts.resize(OldSize);
5433 LLVM_DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
5434 TPT.rollback(LastKnownGood);
5435 return false;
5436 }
5437
5438 // SExt has been deleted. Make sure it is not referenced by the AddrMode.
5439 AddrMode.replaceWith(Ext, PromotedOperand);
5440 return true;
5441 }
5442 case Instruction::Call:
5443 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(AddrInst)) {
5444 if (II->getIntrinsicID() == Intrinsic::threadlocal_address) {
5445 GlobalValue &GV = cast<GlobalValue>(*II->getArgOperand(0));
5446 if (TLI.addressingModeSupportsTLS(GV))
5447 return matchAddr(AddrInst->getOperand(0), Depth);
5448 }
5449 }
5450 break;
5451 }
5452 return false;
5453}
5454
5455/// If we can, try to add the value of 'Addr' into the current addressing mode.
5456/// If Addr can't be added to AddrMode this returns false and leaves AddrMode
5457/// unmodified. This assumes that Addr is either a pointer type or intptr_t
5458/// for the target.
5459///
5460bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
5461 // Start a transaction at this point that we will rollback if the matching
5462 // fails.
5463 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5464 TPT.getRestorationPoint();
5465 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
5466 if (CI->getValue().isSignedIntN(64)) {
5467 // Check if the addition would result in a signed overflow.
5468 int64_t Result;
5469 bool Overflow =
5470 AddOverflow(AddrMode.BaseOffs, CI->getSExtValue(), Result);
5471 if (!Overflow) {
5472 // Fold in immediates if legal for the target.
5473 AddrMode.BaseOffs = Result;
5474 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
5475 return true;
5476 AddrMode.BaseOffs -= CI->getSExtValue();
5477 }
5478 }
5479 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
5480 // If this is a global variable, try to fold it into the addressing mode.
5481 if (!AddrMode.BaseGV) {
5482 AddrMode.BaseGV = GV;
5483 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
5484 return true;
5485 AddrMode.BaseGV = nullptr;
5486 }
5487 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
5488 ExtAddrMode BackupAddrMode = AddrMode;
5489 unsigned OldSize = AddrModeInsts.size();
5490
5491 // Check to see if it is possible to fold this operation.
5492 bool MovedAway = false;
5493 if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
5494 // This instruction may have been moved away. If so, there is nothing
5495 // to check here.
5496 if (MovedAway)
5497 return true;
5498 // Okay, it's possible to fold this. Check to see if it is actually
5499 // *profitable* to do so. We use a simple cost model to avoid increasing
5500 // register pressure too much.
5501 if (I->hasOneUse() ||
5502 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
5503 AddrModeInsts.push_back(I);
5504 return true;
5505 }
5506
5507 // It isn't profitable to do this, roll back.
5508 AddrMode = BackupAddrMode;
5509 AddrModeInsts.resize(OldSize);
5510 TPT.rollback(LastKnownGood);
5511 }
5512 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
5513 if (matchOperationAddr(CE, CE->getOpcode(), Depth))
5514 return true;
5515 TPT.rollback(LastKnownGood);
5516 } else if (isa<ConstantPointerNull>(Addr)) {
5517 // Null pointer gets folded without affecting the addressing mode.
5518 return true;
5519 }
5520
5521 // Worse case, the target should support [reg] addressing modes. :)
5522 if (!AddrMode.HasBaseReg) {
5523 AddrMode.HasBaseReg = true;
5524 AddrMode.BaseReg = Addr;
5525 // Still check for legality in case the target supports [imm] but not [i+r].
5526 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
5527 return true;
5528 AddrMode.HasBaseReg = false;
5529 AddrMode.BaseReg = nullptr;
5530 }
5531
5532 // If the base register is already taken, see if we can do [r+r].
5533 if (AddrMode.Scale == 0) {
5534 AddrMode.Scale = 1;
5535 AddrMode.ScaledReg = Addr;
5536 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
5537 return true;
5538 AddrMode.Scale = 0;
5539 AddrMode.ScaledReg = nullptr;
5540 }
5541 // Couldn't match.
5542 TPT.rollback(LastKnownGood);
5543 return false;
5544}
5545
5546/// Check to see if all uses of OpVal by the specified inline asm call are due
5547/// to memory operands. If so, return true, otherwise return false.
5549 const TargetLowering &TLI,
5550 const TargetRegisterInfo &TRI) {
5551 const Function *F = CI->getFunction();
5552 TargetLowering::AsmOperandInfoVector TargetConstraints =
5553 TLI.ParseConstraints(F->getDataLayout(), &TRI, *CI);
5554
5555 for (TargetLowering::AsmOperandInfo &OpInfo : TargetConstraints) {
5556 // Compute the constraint code and ConstraintType to use.
5557 TLI.ComputeConstraintToUse(OpInfo, SDValue());
5558
5559 // If this asm operand is our Value*, and if it isn't an indirect memory
5560 // operand, we can't fold it! TODO: Also handle C_Address?
5561 if (OpInfo.CallOperandVal == OpVal &&
5562 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
5563 !OpInfo.isIndirect))
5564 return false;
5565 }
5566
5567 return true;
5568}
5569
5570/// Recursively walk all the uses of I until we find a memory use.
5571/// If we find an obviously non-foldable instruction, return true.
5572/// Add accessed addresses and types to MemoryUses.
5574 Instruction *I, SmallVectorImpl<std::pair<Use *, Type *>> &MemoryUses,
5575 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetLowering &TLI,
5576 const TargetRegisterInfo &TRI, bool OptSize, ProfileSummaryInfo *PSI,
5577 BlockFrequencyInfo *BFI, unsigned &SeenInsts) {
5578 // If we already considered this instruction, we're done.
5579 if (!ConsideredInsts.insert(I).second)
5580 return false;
5581
5582 // If this is an obviously unfoldable instruction, bail out.
5583 if (!MightBeFoldableInst(I))
5584 return true;
5585
5586 // Loop over all the uses, recursively processing them.
5587 for (Use &U : I->uses()) {
5588 // Conservatively return true if we're seeing a large number or a deep chain
5589 // of users. This avoids excessive compilation times in pathological cases.
5590 if (SeenInsts++ >= MaxAddressUsersToScan)
5591 return true;
5592
5593 Instruction *UserI = cast<Instruction>(U.getUser());
5594 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
5595 MemoryUses.push_back({&U, LI->getType()});
5596 continue;
5597 }
5598
5599 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
5600 if (U.getOperandNo() != StoreInst::getPointerOperandIndex())
5601 return true; // Storing addr, not into addr.
5602 MemoryUses.push_back({&U, SI->getValueOperand()->getType()});
5603 continue;
5604 }
5605
5606 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UserI)) {
5607 if (U.getOperandNo() != AtomicRMWInst::getPointerOperandIndex())
5608 return true; // Storing addr, not into addr.
5609 MemoryUses.push_back({&U, RMW->getValOperand()->getType()});
5610 continue;
5611 }
5612
5614 if (U.getOperandNo() != AtomicCmpXchgInst::getPointerOperandIndex())
5615 return true; // Storing addr, not into addr.
5616 MemoryUses.push_back({&U, CmpX->getCompareOperand()->getType()});
5617 continue;
5618 }
5619
5622 Type *AccessTy;
5623 if (!TLI.getAddrModeArguments(II, PtrOps, AccessTy))
5624 return true;
5625
5626 if (!find(PtrOps, U.get()))
5627 return true;
5628
5629 MemoryUses.push_back({&U, AccessTy});
5630 continue;
5631 }
5632
5633 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
5634 if (CI->hasFnAttr(Attribute::Cold)) {
5635 // If this is a cold call, we can sink the addressing calculation into
5636 // the cold path. See optimizeCallInst
5637 if (!llvm::shouldOptimizeForSize(CI->getParent(), PSI, BFI))
5638 continue;
5639 }
5640
5641 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledOperand());
5642 if (!IA)
5643 return true;
5644
5645 // If this is a memory operand, we're cool, otherwise bail out.
5646 if (!IsOperandAMemoryOperand(CI, IA, I, TLI, TRI))
5647 return true;
5648 continue;
5649 }
5650
5651 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI, TRI, OptSize,
5652 PSI, BFI, SeenInsts))
5653 return true;
5654 }
5655
5656 return false;
5657}
5658
5660 Instruction *I, SmallVectorImpl<std::pair<Use *, Type *>> &MemoryUses,
5661 const TargetLowering &TLI, const TargetRegisterInfo &TRI, bool OptSize,
5663 unsigned SeenInsts = 0;
5664 SmallPtrSet<Instruction *, 16> ConsideredInsts;
5665 return FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI, TRI, OptSize,
5666 PSI, BFI, SeenInsts);
5667}
5668
5669
5670/// Return true if Val is already known to be live at the use site that we're
5671/// folding it into. If so, there is no cost to include it in the addressing
5672/// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
5673/// instruction already.
5674bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,
5675 Value *KnownLive1,
5676 Value *KnownLive2) {
5677 // If Val is either of the known-live values, we know it is live!
5678 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
5679 return true;
5680
5681 // All values other than instructions and arguments (e.g. constants) are live.
5682 if (!isa<Instruction>(Val) && !isa<Argument>(Val))
5683 return true;
5684
5685 // If Val is a constant sized alloca in the entry block, it is live, this is
5686 // true because it is just a reference to the stack/frame pointer, which is
5687 // live for the whole function.
5688 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
5689 if (AI->isStaticAlloca())
5690 return true;
5691
5692 // Check to see if this value is already used in the memory instruction's
5693 // block. If so, it's already live into the block at the very least, so we
5694 // can reasonably fold it.
5695 return Val->isUsedInBasicBlock(MemoryInst->getParent());
5696}
5697
5698/// It is possible for the addressing mode of the machine to fold the specified
5699/// instruction into a load or store that ultimately uses it.
5700/// However, the specified instruction has multiple uses.
5701/// Given this, it may actually increase register pressure to fold it
5702/// into the load. For example, consider this code:
5703///
5704/// X = ...
5705/// Y = X+1
5706/// use(Y) -> nonload/store
5707/// Z = Y+1
5708/// load Z
5709///
5710/// In this case, Y has multiple uses, and can be folded into the load of Z
5711/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
5712/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
5713/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
5714/// number of computations either.
5715///
5716/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
5717/// X was live across 'load Z' for other reasons, we actually *would* want to
5718/// fold the addressing mode in the Z case. This would make Y die earlier.
5719bool AddressingModeMatcher::isProfitableToFoldIntoAddressingMode(
5720 Instruction *I, ExtAddrMode &AMBefore, ExtAddrMode &AMAfter) {
5721 if (IgnoreProfitability)
5722 return true;
5723
5724 // AMBefore is the addressing mode before this instruction was folded into it,
5725 // and AMAfter is the addressing mode after the instruction was folded. Get
5726 // the set of registers referenced by AMAfter and subtract out those
5727 // referenced by AMBefore: this is the set of values which folding in this
5728 // address extends the lifetime of.
5729 //
5730 // Note that there are only two potential values being referenced here,
5731 // BaseReg and ScaleReg (global addresses are always available, as are any
5732 // folded immediates).
5733 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
5734
5735 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
5736 // lifetime wasn't extended by adding this instruction.
5737 if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
5738 BaseReg = nullptr;
5739 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
5740 ScaledReg = nullptr;
5741
5742 // If folding this instruction (and it's subexprs) didn't extend any live
5743 // ranges, we're ok with it.
5744 if (!BaseReg && !ScaledReg)
5745 return true;
5746
5747 // If all uses of this instruction can have the address mode sunk into them,
5748 // we can remove the addressing mode and effectively trade one live register
5749 // for another (at worst.) In this context, folding an addressing mode into
5750 // the use is just a particularly nice way of sinking it.
5752 if (FindAllMemoryUses(I, MemoryUses, TLI, TRI, OptSize, PSI, BFI))
5753 return false; // Has a non-memory, non-foldable use!
5754
5755 // Now that we know that all uses of this instruction are part of a chain of
5756 // computation involving only operations that could theoretically be folded
5757 // into a memory use, loop over each of these memory operation uses and see
5758 // if they could *actually* fold the instruction. The assumption is that
5759 // addressing modes are cheap and that duplicating the computation involved
5760 // many times is worthwhile, even on a fastpath. For sinking candidates
5761 // (i.e. cold call sites), this serves as a way to prevent excessive code
5762 // growth since most architectures have some reasonable small and fast way to
5763 // compute an effective address. (i.e LEA on x86)
5764 SmallVector<Instruction *, 32> MatchedAddrModeInsts;
5765 for (const std::pair<Use *, Type *> &Pair : MemoryUses) {
5766 Value *Address = Pair.first->get();
5767 Instruction *UserI = cast<Instruction>(Pair.first->getUser());
5768 Type *AddressAccessTy = Pair.second;
5769 unsigned AS = Address->getType()->getPointerAddressSpace();
5770
5771 // Do a match against the root of this address, ignoring profitability. This
5772 // will tell us if the addressing mode for the memory operation will
5773 // *actually* cover the shared instruction.
5774 ExtAddrMode Result;
5775 std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr,
5776 0);
5777 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5778 TPT.getRestorationPoint();
5779 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, TRI, LI, getDTFn,
5780 AddressAccessTy, AS, UserI, Result,
5781 InsertedInsts, PromotedInsts, TPT,
5782 LargeOffsetGEP, OptSize, PSI, BFI);
5783 Matcher.IgnoreProfitability = true;
5784 bool Success = Matcher.matchAddr(Address, 0);
5785 (void)Success;
5786 assert(Success && "Couldn't select *anything*?");
5787
5788 // The match was to check the profitability, the changes made are not
5789 // part of the original matcher. Therefore, they should be dropped
5790 // otherwise the original matcher will not present the right state.
5791 TPT.rollback(LastKnownGood);
5792
5793 // If the match didn't cover I, then it won't be shared by it.
5794 if (!is_contained(MatchedAddrModeInsts, I))
5795 return false;
5796
5797 MatchedAddrModeInsts.clear();
5798 }
5799
5800 return true;
5801}
5802
5803/// Return true if the specified values are defined in a
5804/// different basic block than BB.
5805static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
5807 return I->getParent() != BB;
5808 return false;
5809}
5810
5811// Find an insert position of Addr for MemoryInst. We can't guarantee MemoryInst
5812// is the first instruction that will use Addr. So we need to find the first
5813// user of Addr in current BB.
5815 Value *SunkAddr) {
5816 if (Addr->hasOneUse())
5817 return MemoryInst->getIterator();
5818
5819 // We already have a SunkAddr in current BB, but we may need to insert cast
5820 // instruction after it.
5821 if (SunkAddr) {
5822 if (Instruction *AddrInst = dyn_cast<Instruction>(SunkAddr))
5823 return std::next(AddrInst->getIterator());
5824 }
5825
5826 // Find the first user of Addr in current BB.
5827 Instruction *Earliest = MemoryInst;
5828 for (User *U : Addr->users()) {
5829 Instruction *UserInst = dyn_cast<Instruction>(U);
5830 if (UserInst && UserInst->getParent() == MemoryInst->getParent()) {
5831 if (isa<PHINode>(UserInst) || UserInst->isDebugOrPseudoInst())
5832 continue;
5833 if (UserInst->comesBefore(Earliest))
5834 Earliest = UserInst;
5835 }
5836 }
5837 return Earliest->getIterator();
5838}
5839
5840/// Sink addressing mode computation immediate before MemoryInst if doing so
5841/// can be done without increasing register pressure. The need for the
5842/// register pressure constraint means this can end up being an all or nothing
5843/// decision for all uses of the same addressing computation.
5844///
5845/// Load and Store Instructions often have addressing modes that can do
5846/// significant amounts of computation. As such, instruction selection will try
5847/// to get the load or store to do as much computation as possible for the
5848/// program. The problem is that isel can only see within a single block. As
5849/// such, we sink as much legal addressing mode work into the block as possible.
5850///
5851/// This method is used to optimize both load/store and inline asms with memory
5852/// operands. It's also used to sink addressing computations feeding into cold
5853/// call sites into their (cold) basic block.
5854///
5855/// The motivation for handling sinking into cold blocks is that doing so can
5856/// both enable other address mode sinking (by satisfying the register pressure
5857/// constraint above), and reduce register pressure globally (by removing the
5858/// addressing mode computation from the fast path entirely.).
5859bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
5860 Type *AccessTy, unsigned AddrSpace) {
5861 Value *Repl = Addr;
5862
5863 // Try to collapse single-value PHI nodes. This is necessary to undo
5864 // unprofitable PRE transformations.
5865 SmallVector<Value *, 8> worklist;
5866 SmallPtrSet<Value *, 16> Visited;
5867 worklist.push_back(Addr);
5868
5869 // Use a worklist to iteratively look through PHI and select nodes, and
5870 // ensure that the addressing mode obtained from the non-PHI/select roots of
5871 // the graph are compatible.
5872 bool PhiOrSelectSeen = false;
5873 SmallVector<Instruction *, 16> AddrModeInsts;
5874 AddressingModeCombiner AddrModes(*DL, Addr);
5875 TypePromotionTransaction TPT(RemovedInsts);
5876 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5877 TPT.getRestorationPoint();
5878 while (!worklist.empty()) {
5879 Value *V = worklist.pop_back_val();
5880
5881 // We allow traversing cyclic Phi nodes.
5882 // In case of success after this loop we ensure that traversing through
5883 // Phi nodes ends up with all cases to compute address of the form
5884 // BaseGV + Base + Scale * Index + Offset
5885 // where Scale and Offset are constans and BaseGV, Base and Index
5886 // are exactly the same Values in all cases.
5887 // It means that BaseGV, Scale and Offset dominate our memory instruction
5888 // and have the same value as they had in address computation represented
5889 // as Phi. So we can safely sink address computation to memory instruction.
5890 if (!Visited.insert(V).second)
5891 continue;
5892
5893 // For a PHI node, push all of its incoming values.
5894 if (PHINode *P = dyn_cast<PHINode>(V)) {
5895 append_range(worklist, P->incoming_values());
5896 PhiOrSelectSeen = true;
5897 continue;
5898 }
5899 // Similar for select.
5900 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
5901 worklist.push_back(SI->getFalseValue());
5902 worklist.push_back(SI->getTrueValue());
5903 PhiOrSelectSeen = true;
5904 continue;
5905 }
5906
5907 // For non-PHIs, determine the addressing mode being computed. Note that
5908 // the result may differ depending on what other uses our candidate
5909 // addressing instructions might have.
5910 AddrModeInsts.clear();
5911 std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr,
5912 0);
5913 // Defer the query (and possible computation of) the dom tree to point of
5914 // actual use. It's expected that most address matches don't actually need
5915 // the domtree.
5916 auto getDTFn = [this]() -> const DominatorTree & { return getDT(); };
5917 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
5918 V, AccessTy, AddrSpace, MemoryInst, AddrModeInsts, *TLI, *LI, getDTFn,
5919 *TRI, InsertedInsts, PromotedInsts, TPT, LargeOffsetGEP, OptSize, PSI,
5920 BFI);
5921
5922 GetElementPtrInst *GEP = LargeOffsetGEP.first;
5923 if (GEP && !NewGEPBases.count(GEP)) {
5924 // If splitting the underlying data structure can reduce the offset of a
5925 // GEP, collect the GEP. Skip the GEPs that are the new bases of
5926 // previously split data structures.
5927 LargeOffsetGEPMap[GEP->getPointerOperand()].push_back(LargeOffsetGEP);
5928 LargeOffsetGEPID.insert(std::make_pair(GEP, LargeOffsetGEPID.size()));
5929 }
5930
5931 NewAddrMode.OriginalValue = V;
5932 if (!AddrModes.addNewAddrMode(NewAddrMode))
5933 break;
5934 }
5935
5936 // Try to combine the AddrModes we've collected. If we couldn't collect any,
5937 // or we have multiple but either couldn't combine them or combining them
5938 // wouldn't do anything useful, bail out now.
5939 if (!AddrModes.combineAddrModes()) {
5940 TPT.rollback(LastKnownGood);
5941 return false;
5942 }
5943 bool Modified = TPT.commit();
5944
5945 // Get the combined AddrMode (or the only AddrMode, if we only had one).
5946 ExtAddrMode AddrMode = AddrModes.getAddrMode();
5947
5948 // If all the instructions matched are already in this BB, don't do anything.
5949 // If we saw a Phi node then it is not local definitely, and if we saw a
5950 // select then we want to push the address calculation past it even if it's
5951 // already in this BB.
5952 if (!PhiOrSelectSeen && none_of(AddrModeInsts, [&](Value *V) {
5953 return IsNonLocalValue(V, MemoryInst->getParent());
5954 })) {
5955 LLVM_DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode
5956 << "\n");
5957 return Modified;
5958 }
5959
5960 // Now that we determined the addressing expression we want to use and know
5961 // that we have to sink it into this block. Check to see if we have already
5962 // done this for some other load/store instr in this block. If so, reuse
5963 // the computation. Before attempting reuse, check if the address is valid
5964 // as it may have been erased.
5965
5966 WeakTrackingVH SunkAddrVH = SunkAddrs[Addr];
5967
5968 Value *SunkAddr = SunkAddrVH.pointsToAliveValue() ? SunkAddrVH : nullptr;
5969 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
5970
5971 // The current BB may be optimized multiple times, we can't guarantee the
5972 // reuse of Addr happens later, call findInsertPos to find an appropriate
5973 // insert position.
5974 auto InsertPos = findInsertPos(Addr, MemoryInst, SunkAddr);
5975
5976 // TODO: Adjust insert point considering (Base|Scaled)Reg if possible.
5977 if (!SunkAddr) {
5978 auto &DT = getDT();
5979 if ((AddrMode.BaseReg && !DT.dominates(AddrMode.BaseReg, &*InsertPos)) ||
5980 (AddrMode.ScaledReg && !DT.dominates(AddrMode.ScaledReg, &*InsertPos)))
5981 return Modified;
5982 }
5983
5984 IRBuilder<> Builder(MemoryInst->getParent(), InsertPos);
5985
5986 if (SunkAddr) {
5987 LLVM_DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode
5988 << " for " << *MemoryInst << "\n");
5989 if (SunkAddr->getType() != Addr->getType()) {
5990 if (SunkAddr->getType()->getPointerAddressSpace() !=
5991 Addr->getType()->getPointerAddressSpace() &&
5992 !DL->isNonIntegralPointerType(Addr->getType())) {
5993 // There are two reasons the address spaces might not match: a no-op
5994 // addrspacecast, or a ptrtoint/inttoptr pair. Either way, we emit a
5995 // ptrtoint/inttoptr pair to ensure we match the original semantics.
5996 // TODO: allow bitcast between different address space pointers with the
5997 // same size.
5998 SunkAddr = Builder.CreatePtrToInt(SunkAddr, IntPtrTy, "sunkaddr");
5999 SunkAddr =
6000 Builder.CreateIntToPtr(SunkAddr, Addr->getType(), "sunkaddr");
6001 } else
6002 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
6003 }
6005 SubtargetInfo->addrSinkUsingGEPs())) {
6006 // By default, we use the GEP-based method when AA is used later. This
6007 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
6008 LLVM_DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode
6009 << " for " << *MemoryInst << "\n");
6010 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
6011
6012 // First, find the pointer.
6013 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
6014 ResultPtr = AddrMode.BaseReg;
6015 AddrMode.BaseReg = nullptr;
6016 }
6017
6018 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
6019 // We can't add more than one pointer together, nor can we scale a
6020 // pointer (both of which seem meaningless).
6021 if (ResultPtr || AddrMode.Scale != 1)
6022 return Modified;
6023
6024 ResultPtr = AddrMode.ScaledReg;
6025 AddrMode.Scale = 0;
6026 }
6027
6028 // It is only safe to sign extend the BaseReg if we know that the math
6029 // required to create it did not overflow before we extend it. Since
6030 // the original IR value was tossed in favor of a constant back when
6031 // the AddrMode was created we need to bail out gracefully if widths
6032 // do not match instead of extending it.
6033 //
6034 // (See below for code to add the scale.)
6035 if (AddrMode.Scale) {
6036 Type *ScaledRegTy = AddrMode.ScaledReg->getType();
6038 cast<IntegerType>(ScaledRegTy)->getBitWidth())
6039 return Modified;
6040 }
6041
6042 GlobalValue *BaseGV = AddrMode.BaseGV;
6043 if (BaseGV != nullptr) {
6044 if (ResultPtr)
6045 return Modified;
6046
6047 if (BaseGV->isThreadLocal()) {
6048 ResultPtr = Builder.CreateThreadLocalAddress(BaseGV);
6049 } else {
6050 ResultPtr = BaseGV;
6051 }
6052 }
6053
6054 // If the real base value actually came from an inttoptr, then the matcher
6055 // will look through it and provide only the integer value. In that case,
6056 // use it here.
6057 if (!DL->isNonIntegralPointerType(Addr->getType())) {
6058 if (!ResultPtr && AddrMode.BaseReg) {
6059 ResultPtr = Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(),
6060 "sunkaddr");
6061 AddrMode.BaseReg = nullptr;
6062 } else if (!ResultPtr && AddrMode.Scale == 1) {
6063 ResultPtr = Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(),
6064 "sunkaddr");
6065 AddrMode.Scale = 0;
6066 }
6067 }
6068
6069 if (!ResultPtr && !AddrMode.BaseReg && !AddrMode.Scale &&
6070 !AddrMode.BaseOffs) {
6071 SunkAddr = Constant::getNullValue(Addr->getType());
6072 } else if (!ResultPtr) {
6073 return Modified;
6074 } else {
6075 Type *I8PtrTy =
6076 Builder.getPtrTy(Addr->getType()->getPointerAddressSpace());
6077
6078 // Start with the base register. Do this first so that subsequent address
6079 // matching finds it last, which will prevent it from trying to match it
6080 // as the scaled value in case it happens to be a mul. That would be
6081 // problematic if we've sunk a different mul for the scale, because then
6082 // we'd end up sinking both muls.
6083 if (AddrMode.BaseReg) {
6084 Value *V = AddrMode.BaseReg;
6085 if (V->getType() != IntPtrTy)
6086 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
6087
6088 ResultIndex = V;
6089 }
6090
6091 // Add the scale value.
6092 if (AddrMode.Scale) {
6093 Value *V = AddrMode.ScaledReg;
6094 if (V->getType() == IntPtrTy) {
6095 // done.
6096 } else {
6098 cast<IntegerType>(V->getType())->getBitWidth() &&
6099 "We can't transform if ScaledReg is too narrow");
6100 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
6101 }
6102
6103 if (AddrMode.Scale != 1)
6104 V = Builder.CreateMul(
6105 V, ConstantInt::getSigned(IntPtrTy, AddrMode.Scale), "sunkaddr");
6106 if (ResultIndex)
6107 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
6108 else
6109 ResultIndex = V;
6110 }
6111
6112 // Add in the Base Offset if present.
6113 if (AddrMode.BaseOffs) {
6115 if (ResultIndex) {
6116 // We need to add this separately from the scale above to help with
6117 // SDAG consecutive load/store merging.
6118 if (ResultPtr->getType() != I8PtrTy)
6119 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
6120 ResultPtr = Builder.CreatePtrAdd(ResultPtr, ResultIndex, "sunkaddr",
6121 AddrMode.InBounds);
6122 }
6123
6124 ResultIndex = V;
6125 }
6126
6127 if (!ResultIndex) {
6128 auto PtrInst = dyn_cast<Instruction>(ResultPtr);
6129 // We know that we have a pointer without any offsets. If this pointer
6130 // originates from a different basic block than the current one, we
6131 // must be able to recreate it in the current basic block.
6132 // We do not support the recreation of any instructions yet.
6133 if (PtrInst && PtrInst->getParent() != MemoryInst->getParent())
6134 return Modified;
6135 SunkAddr = ResultPtr;
6136 } else {
6137 if (ResultPtr->getType() != I8PtrTy)
6138 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
6139 SunkAddr = Builder.CreatePtrAdd(ResultPtr, ResultIndex, "sunkaddr",
6140 AddrMode.InBounds);
6141 }
6142
6143 if (SunkAddr->getType() != Addr->getType()) {
6144 if (SunkAddr->getType()->getPointerAddressSpace() !=
6145 Addr->getType()->getPointerAddressSpace() &&
6146 !DL->isNonIntegralPointerType(Addr->getType())) {
6147 // There are two reasons the address spaces might not match: a no-op
6148 // addrspacecast, or a ptrtoint/inttoptr pair. Either way, we emit a
6149 // ptrtoint/inttoptr pair to ensure we match the original semantics.
6150 // TODO: allow bitcast between different address space pointers with
6151 // the same size.
6152 SunkAddr = Builder.CreatePtrToInt(SunkAddr, IntPtrTy, "sunkaddr");
6153 SunkAddr =
6154 Builder.CreateIntToPtr(SunkAddr, Addr->getType(), "sunkaddr");
6155 } else
6156 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
6157 }
6158 }
6159 } else {
6160 // We'd require a ptrtoint/inttoptr down the line, which we can't do for
6161 // non-integral pointers, so in that case bail out now.
6162 Type *BaseTy = AddrMode.BaseReg ? AddrMode.BaseReg->getType() : nullptr;
6163 Type *ScaleTy = AddrMode.Scale ? AddrMode.ScaledReg->getType() : nullptr;
6164 PointerType *BasePtrTy = dyn_cast_or_null<PointerType>(BaseTy);
6165 PointerType *ScalePtrTy = dyn_cast_or_null<PointerType>(ScaleTy);
6166 if (DL->isNonIntegralPointerType(Addr->getType()) ||
6167 (BasePtrTy && DL->isNonIntegralPointerType(BasePtrTy)) ||
6168 (ScalePtrTy && DL->isNonIntegralPointerType(ScalePtrTy)) ||
6169 (AddrMode.BaseGV &&
6170 DL->isNonIntegralPointerType(AddrMode.BaseGV->getType())))
6171 return Modified;
6172
6173 LLVM_DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode
6174 << " for " << *MemoryInst << "\n");
6175 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
6176 Value *Result = nullptr;
6177
6178 // Start with the base register. Do this first so that subsequent address
6179 // matching finds it last, which will prevent it from trying to match it
6180 // as the scaled value in case it happens to be a mul. That would be
6181 // problematic if we've sunk a different mul for the scale, because then
6182 // we'd end up sinking both muls.
6183 if (AddrMode.BaseReg) {
6184 Value *V = AddrMode.BaseReg;
6185 if (V->getType()->isPointerTy())
6186 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
6187 if (V->getType() != IntPtrTy)
6188 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
6189 Result = V;
6190 }
6191
6192 // Add the scale value.
6193 if (AddrMode.Scale) {
6194 Value *V = AddrMode.ScaledReg;
6195 if (V->getType() == IntPtrTy) {
6196 // done.
6197 } else if (V->getType()->isPointerTy()) {
6198 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
6199 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
6200 cast<IntegerType>(V->getType())->getBitWidth()) {
6201 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
6202 } else {
6203 // It is only safe to sign extend the BaseReg if we know that the math
6204 // required to create it did not overflow before we extend it. Since
6205 // the original IR value was tossed in favor of a constant back when
6206 // the AddrMode was created we need to bail out gracefully if widths
6207 // do not match instead of extending it.
6209 if (I && (Result != AddrMode.BaseReg))
6210 I->eraseFromParent();
6211 return Modified;
6212 }
6213 if (AddrMode.Scale != 1)
6214 V = Builder.CreateMul(
6215 V, ConstantInt::getSigned(IntPtrTy, AddrMode.Scale), "sunkaddr");
6216 if (Result)
6217 Result = Builder.CreateAdd(Result, V, "sunkaddr");
6218 else
6219 Result = V;
6220 }
6221
6222 // Add in the BaseGV if present.
6223 GlobalValue *BaseGV = AddrMode.BaseGV;
6224 if (BaseGV != nullptr) {
6225 Value *BaseGVPtr;
6226 if (BaseGV->isThreadLocal()) {
6227 BaseGVPtr = Builder.CreateThreadLocalAddress(BaseGV);
6228 } else {
6229 BaseGVPtr = BaseGV;
6230 }
6231 Value *V = Builder.CreatePtrToInt(BaseGVPtr, IntPtrTy, "sunkaddr");
6232 if (Result)
6233 Result = Builder.CreateAdd(Result, V, "sunkaddr");
6234 else
6235 Result = V;
6236 }
6237
6238 // Add in the Base Offset if present.
6239 if (AddrMode.BaseOffs) {
6241 if (Result)
6242 Result = Builder.CreateAdd(Result, V, "sunkaddr");
6243 else
6244 Result = V;
6245 }
6246
6247 if (!Result)
6248 SunkAddr = Constant::getNullValue(Addr->getType());
6249 else
6250 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
6251 }
6252
6253 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
6254 // Store the newly computed address into the cache. In the case we reused a
6255 // value, this should be idempotent.
6256 SunkAddrs[Addr] = WeakTrackingVH(SunkAddr);
6257
6258 // If we have no uses, recursively delete the value and all dead instructions
6259 // using it.
6260 if (Repl->use_empty()) {
6261 resetIteratorIfInvalidatedWhileCalling(CurInstIterator->getParent(), [&]() {
6262 RecursivelyDeleteTriviallyDeadInstructions(
6263 Repl, TLInfo, nullptr,
6264 [&](Value *V) { removeAllAssertingVHReferences(V); });
6265 });
6266 }
6267 ++NumMemoryInsts;
6268 return true;
6269}
6270
6271/// Rewrite GEP input to gather/scatter to enable SelectionDAGBuilder to find
6272/// a uniform base to use for ISD::MGATHER/MSCATTER. SelectionDAGBuilder can
6273/// only handle a 2 operand GEP in the same basic block or a splat constant
6274/// vector. The 2 operands to the GEP must have a scalar pointer and a vector
6275/// index.
6276///
6277/// If the existing GEP has a vector base pointer that is splat, we can look
6278/// through the splat to find the scalar pointer. If we can't find a scalar
6279/// pointer there's nothing we can do.
6280///
6281/// If we have a GEP with more than 2 indices where the middle indices are all
6282/// zeroes, we can replace it with 2 GEPs where the second has 2 operands.
6283///
6284/// If the final index isn't a vector or is a splat, we can emit a scalar GEP
6285/// followed by a GEP with an all zeroes vector index. This will enable
6286/// SelectionDAGBuilder to use the scalar GEP as the uniform base and have a
6287/// zero index.
6288bool CodeGenPrepare::optimizeGatherScatterInst(Instruction *MemoryInst,
6289 Value *Ptr) {
6290 Value *NewAddr;
6291
6292 if (const auto *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
6293 // Don't optimize GEPs that don't have indices.
6294 if (!GEP->hasIndices())
6295 return false;
6296
6297 // If the GEP and the gather/scatter aren't in the same BB, don't optimize.
6298 // FIXME: We should support this by sinking the GEP.
6299 if (MemoryInst->getParent() != GEP->getParent())
6300 return false;
6301
6302 SmallVector<Value *, 2> Ops(GEP->operands());
6303
6304 bool RewriteGEP = false;
6305
6306 if (Ops[0]->getType()->isVectorTy()) {
6307 Ops[0] = getSplatValue(Ops[0]);
6308 if (!Ops[0])
6309 return false;
6310 RewriteGEP = true;
6311 }
6312
6313 unsigned FinalIndex = Ops.size() - 1;
6314
6315 // Ensure all but the last index is 0.
6316 // FIXME: This isn't strictly required. All that's required is that they are
6317 // all scalars or splats.
6318 for (unsigned i = 1; i < FinalIndex; ++i) {
6319 auto *C = dyn_cast<Constant>(Ops[i]);
6320 if (!C)
6321 return false;
6322 if (isa<VectorType>(C->getType()))
6323 C = C->getSplatValue();
6324 auto *CI = dyn_cast_or_null<ConstantInt>(C);
6325 if (!CI || !CI->isZero())
6326 return false;
6327 // Scalarize the index if needed.
6328 Ops[i] = CI;
6329 }
6330
6331 // Try to scalarize the final index.
6332 if (Ops[FinalIndex]->getType()->isVectorTy()) {
6333 if (Value *V = getSplatValue(Ops[FinalIndex])) {
6334 auto *C = dyn_cast<ConstantInt>(V);
6335 // Don't scalarize all zeros vector.
6336 if (!C || !C->isZero()) {
6337 Ops[FinalIndex] = V;
6338 RewriteGEP = true;
6339 }
6340 }
6341 }
6342
6343 // If we made any changes or the we have extra operands, we need to generate
6344 // new instructions.
6345 if (!RewriteGEP && Ops.size() == 2)
6346 return false;
6347
6348 auto NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
6349
6350 IRBuilder<> Builder(MemoryInst);
6351
6352 Type *SourceTy = GEP->getSourceElementType();
6353 Type *ScalarIndexTy = DL->getIndexType(Ops[0]->getType()->getScalarType());
6354
6355 // If the final index isn't a vector, emit a scalar GEP containing all ops
6356 // and a vector GEP with all zeroes final index.
6357 if (!Ops[FinalIndex]->getType()->isVectorTy()) {
6358 NewAddr = Builder.CreateGEP(SourceTy, Ops[0], ArrayRef(Ops).drop_front());
6359 auto *IndexTy = VectorType::get(ScalarIndexTy, NumElts);
6360 auto *SecondTy = GetElementPtrInst::getIndexedType(
6361 SourceTy, ArrayRef(Ops).drop_front());
6362 NewAddr =
6363 Builder.CreateGEP(SecondTy, NewAddr, Constant::getNullValue(IndexTy));
6364 } else {
6365 Value *Base = Ops[0];
6366 Value *Index = Ops[FinalIndex];
6367
6368 // Create a scalar GEP if there are more than 2 operands.
6369 if (Ops.size() != 2) {
6370 // Replace the last index with 0.
6371 Ops[FinalIndex] =
6372 Constant::getNullValue(Ops[FinalIndex]->getType()->getScalarType());
6373 Base = Builder.CreateGEP(SourceTy, Base, ArrayRef(Ops).drop_front());
6375 SourceTy, ArrayRef(Ops).drop_front());
6376 }
6377
6378 // Now create the GEP with scalar pointer and vector index.
6379 NewAddr = Builder.CreateGEP(SourceTy, Base, Index);
6380 }
6381 } else if (!isa<Constant>(Ptr)) {
6382 // Not a GEP, maybe its a splat and we can create a GEP to enable
6383 // SelectionDAGBuilder to use it as a uniform base.
6384 Value *V = getSplatValue(Ptr);
6385 if (!V)
6386 return false;
6387
6388 auto NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
6389
6390 IRBuilder<> Builder(MemoryInst);
6391
6392 // Emit a vector GEP with a scalar pointer and all 0s vector index.
6393 Type *ScalarIndexTy = DL->getIndexType(V->getType()->getScalarType());
6394 auto *IndexTy = VectorType::get(ScalarIndexTy, NumElts);
6395 Type *ScalarTy;
6396 if (cast<IntrinsicInst>(MemoryInst)->getIntrinsicID() ==
6397 Intrinsic::masked_gather) {
6398 ScalarTy = MemoryInst->getType()->getScalarType();
6399 } else {
6400 assert(cast<IntrinsicInst>(MemoryInst)->getIntrinsicID() ==
6401 Intrinsic::masked_scatter);
6402 ScalarTy = MemoryInst->getOperand(0)->getType()->getScalarType();
6403 }
6404 NewAddr = Builder.CreateGEP(ScalarTy, V, Constant::getNullValue(IndexTy));
6405 } else {
6406 // Constant, SelectionDAGBuilder knows to check if its a splat.
6407 return false;
6408 }
6409
6410 MemoryInst->replaceUsesOfWith(Ptr, NewAddr);
6411
6412 // If we have no uses, recursively delete the value and all dead instructions
6413 // using it.
6414 if (Ptr->use_empty())
6416 Ptr, TLInfo, nullptr,
6417 [&](Value *V) { removeAllAssertingVHReferences(V); });
6418
6419 return true;
6420}
6421
6422// This is a helper for CodeGenPrepare::optimizeMulWithOverflow.
6423// Check the pattern we are interested in where there are maximum 2 uses
6424// of the intrinsic which are the extract instructions.
6426 ExtractValueInst *&OverflowExtract) {
6427 // Bail out if it's more than 2 users:
6428 if (I->hasNUsesOrMore(3))
6429 return false;
6430
6431 for (User *U : I->users()) {
6432 auto *Extract = dyn_cast<ExtractValueInst>(U);
6433 if (!Extract || Extract->getNumIndices() != 1)
6434 return false;
6435
6436 unsigned Index = Extract->getIndices()[0];
6437 if (Index == 0)
6438 MulExtract = Extract;
6439 else if (Index == 1)
6440 OverflowExtract = Extract;
6441 else
6442 return false;
6443 }
6444 return true;
6445}
6446
6447// Rewrite the mul_with_overflow intrinsic by checking if both of the
6448// operands' value ranges are within the legal type. If so, we can optimize the
6449// multiplication algorithm. This code is supposed to be written during the step
6450// of type legalization, but given that we need to reconstruct the IR which is
6451// not doable there, we do it here.
6452// The IR after the optimization will look like:
6453// entry:
6454// if signed:
6455// ( (lhs_lo>>BW-1) ^ lhs_hi) || ( (rhs_lo>>BW-1) ^ rhs_hi) ? overflow,
6456// overflow_no
6457// else:
6458// (lhs_hi != 0) || (rhs_hi != 0) ? overflow, overflow_no
6459// overflow_no:
6460// overflow:
6461// overflow.res:
6462// \returns true if optimization was applied
6463// TODO: This optimization can be further improved to optimize branching on
6464// overflow where the 'overflow_no' BB can branch directly to the false
6465// successor of overflow, but that would add additional complexity so we leave
6466// it for future work.
6467bool CodeGenPrepare::optimizeMulWithOverflow(Instruction *I, bool IsSigned,
6468 ModifyDT &ModifiedDT) {
6469 // Check if target supports this optimization.
6471 I->getContext(),
6472 TLI->getValueType(*DL, I->getType()->getContainedType(0))))
6473 return false;
6474
6475 ExtractValueInst *MulExtract = nullptr, *OverflowExtract = nullptr;
6476 if (!matchOverflowPattern(I, MulExtract, OverflowExtract))
6477 return false;
6478
6479 // Keep track of the instruction to stop reoptimizing it again.
6480 InsertedInsts.insert(I);
6481
6482 Value *LHS = I->getOperand(0);
6483 Value *RHS = I->getOperand(1);
6484 Type *Ty = LHS->getType();
6485 unsigned VTHalfBitWidth = Ty->getScalarSizeInBits() / 2;
6486 Type *LegalTy = Ty->getWithNewBitWidth(VTHalfBitWidth);
6487
6488 // New BBs:
6489 BasicBlock *OverflowEntryBB =
6490 splitBlockBefore(I->getParent(), I, DTU, LI, nullptr, "");
6491 OverflowEntryBB->takeName(I->getParent());
6492 // Keep the 'br' instruction that is generated as a result of the split to be
6493 // erased/replaced later.
6494 Instruction *OldTerminator = OverflowEntryBB->getTerminator();
6495 BasicBlock *NoOverflowBB =
6496 BasicBlock::Create(I->getContext(), "overflow.no", I->getFunction());
6497 NoOverflowBB->moveAfter(OverflowEntryBB);
6498 BasicBlock *OverflowBB =
6499 BasicBlock::Create(I->getContext(), "overflow", I->getFunction());
6500 OverflowBB->moveAfter(NoOverflowBB);
6501
6502 // BB overflow.entry:
6503 IRBuilder<> Builder(OverflowEntryBB);
6504 // Extract low and high halves of LHS:
6505 Value *LoLHS = Builder.CreateTrunc(LHS, LegalTy, "lo.lhs");
6506 Value *HiLHS = Builder.CreateLShr(LHS, VTHalfBitWidth, "lhs.lsr");
6507 HiLHS = Builder.CreateTrunc(HiLHS, LegalTy, "hi.lhs");
6508
6509 // Extract low and high halves of RHS:
6510 Value *LoRHS = Builder.CreateTrunc(RHS, LegalTy, "lo.rhs");
6511 Value *HiRHS = Builder.CreateLShr(RHS, VTHalfBitWidth, "rhs.lsr");
6512 HiRHS = Builder.CreateTrunc(HiRHS, LegalTy, "hi.rhs");
6513
6514 Value *IsAnyBitTrue;
6515 if (IsSigned) {
6516 Value *SignLoLHS =
6517 Builder.CreateAShr(LoLHS, VTHalfBitWidth - 1, "sign.lo.lhs");
6518 Value *SignLoRHS =
6519 Builder.CreateAShr(LoRHS, VTHalfBitWidth - 1, "sign.lo.rhs");
6520 Value *XorLHS = Builder.CreateXor(HiLHS, SignLoLHS);
6521 Value *XorRHS = Builder.CreateXor(HiRHS, SignLoRHS);
6522 Value *Or = Builder.CreateOr(XorLHS, XorRHS, "or.lhs.rhs");
6523 IsAnyBitTrue = Builder.CreateCmp(ICmpInst::ICMP_NE, Or,
6524 ConstantInt::getNullValue(Or->getType()));
6525 } else {
6526 Value *CmpLHS = Builder.CreateCmp(ICmpInst::ICMP_NE, HiLHS,
6527 ConstantInt::getNullValue(LegalTy));
6528 Value *CmpRHS = Builder.CreateCmp(ICmpInst::ICMP_NE, HiRHS,
6529 ConstantInt::getNullValue(LegalTy));
6530 IsAnyBitTrue = Builder.CreateOr(CmpLHS, CmpRHS, "or.lhs.rhs");
6531 }
6532 Builder.CreateCondBr(IsAnyBitTrue, OverflowBB, NoOverflowBB);
6533
6534 // BB overflow.no:
6535 Builder.SetInsertPoint(NoOverflowBB);
6536 Value *ExtLoLHS, *ExtLoRHS;
6537 if (IsSigned) {
6538 ExtLoLHS = Builder.CreateSExt(LoLHS, Ty, "lo.lhs.ext");
6539 ExtLoRHS = Builder.CreateSExt(LoRHS, Ty, "lo.rhs.ext");
6540 } else {
6541 ExtLoLHS = Builder.CreateZExt(LoLHS, Ty, "lo.lhs.ext");
6542 ExtLoRHS = Builder.CreateZExt(LoRHS, Ty, "lo.rhs.ext");
6543 }
6544
6545 Value *Mul = Builder.CreateMul(ExtLoLHS, ExtLoRHS, "mul.overflow.no");
6546
6547 // Create the 'overflow.res' BB to merge the results of
6548 // the two paths:
6549 BasicBlock *OverflowResBB = I->getParent();
6550 OverflowResBB->setName("overflow.res");
6551
6552 // BB overflow.no: jump to overflow.res BB
6553 Builder.CreateBr(OverflowResBB);
6554 // No we don't need the old terminator in overflow.entry BB, erase it:
6555 OldTerminator->eraseFromParent();
6556
6557 // BB overflow.res:
6558 Builder.SetInsertPoint(OverflowResBB, OverflowResBB->getFirstInsertionPt());
6559 // Create PHI nodes to merge results from no.overflow BB and overflow BB to
6560 // replace the extract instructions.
6561 PHINode *OverflowResPHI = Builder.CreatePHI(Ty, 2),
6562 *OverflowFlagPHI =
6563 Builder.CreatePHI(IntegerType::getInt1Ty(I->getContext()), 2);
6564
6565 // Add the incoming values from no.overflow BB and later from overflow BB.
6566 OverflowResPHI->addIncoming(Mul, NoOverflowBB);
6567 OverflowFlagPHI->addIncoming(ConstantInt::getFalse(I->getContext()),
6568 NoOverflowBB);
6569
6570 // Replace all users of MulExtract and OverflowExtract to use the PHI nodes.
6571 if (MulExtract) {
6572 MulExtract->replaceAllUsesWith(OverflowResPHI);
6573 MulExtract->eraseFromParent();
6574 }
6575 if (OverflowExtract) {
6576 OverflowExtract->replaceAllUsesWith(OverflowFlagPHI);
6577 OverflowExtract->eraseFromParent();
6578 }
6579
6580 // Remove the intrinsic from parent (overflow.res BB) as it will be part of
6581 // overflow BB
6582 I->removeFromParent();
6583 // BB overflow:
6584 I->insertInto(OverflowBB, OverflowBB->end());
6585 Builder.SetInsertPoint(OverflowBB, OverflowBB->end());
6586 Value *MulOverflow = Builder.CreateExtractValue(I, {0}, "mul.overflow");
6587 Value *OverflowFlag = Builder.CreateExtractValue(I, {1}, "overflow.flag");
6588 Builder.CreateBr(OverflowResBB);
6589
6590 // Add The Extracted values to the PHINodes in the overflow.res BB.
6591 OverflowResPHI->addIncoming(MulOverflow, OverflowBB);
6592 OverflowFlagPHI->addIncoming(OverflowFlag, OverflowBB);
6593
6594 DTU->applyUpdates({{DominatorTree::Insert, OverflowEntryBB, OverflowBB},
6595 {DominatorTree::Insert, OverflowEntryBB, NoOverflowBB},
6596 {DominatorTree::Insert, NoOverflowBB, OverflowResBB},
6597 {DominatorTree::Delete, OverflowEntryBB, OverflowResBB},
6598 {DominatorTree::Insert, OverflowBB, OverflowResBB}});
6599
6600 ModifiedDT = ModifyDT::ModifyBBDT;
6601 return true;
6602}
6603
6604/// If there are any memory operands, use OptimizeMemoryInst to sink their
6605/// address computing into the block when possible / profitable.
6606bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
6607 bool MadeChange = false;
6608
6609 const TargetRegisterInfo *TRI =
6611 TargetLowering::AsmOperandInfoVector TargetConstraints =
6612 TLI->ParseConstraints(*DL, TRI, *CS);
6613 unsigned ArgNo = 0;
6614 for (TargetLowering::AsmOperandInfo &OpInfo : TargetConstraints) {
6615 // Compute the constraint code and ConstraintType to use.
6616 TLI->ComputeConstraintToUse(OpInfo, SDValue());
6617
6618 // TODO: Also handle C_Address?
6619 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
6620 OpInfo.isIndirect) {
6621 Value *OpVal = CS->getArgOperand(ArgNo++);
6622 MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
6623 } else if (OpInfo.Type == InlineAsm::isInput)
6624 ArgNo++;
6625 }
6626
6627 return MadeChange;
6628}
6629
6630/// Check if all the uses of \p Val are equivalent (or free) zero or
6631/// sign extensions.
6632static bool hasSameExtUse(Value *Val, const TargetLowering &TLI) {
6633 assert(!Val->use_empty() && "Input must have at least one use");
6634 const Instruction *FirstUser = cast<Instruction>(*Val->user_begin());
6635 bool IsSExt = isa<SExtInst>(FirstUser);
6636 Type *ExtTy = FirstUser->getType();
6637 for (const User *U : Val->users()) {
6638 const Instruction *UI = cast<Instruction>(U);
6639 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
6640 return false;
6641 Type *CurTy = UI->getType();
6642 // Same input and output types: Same instruction after CSE.
6643 if (CurTy == ExtTy)
6644 continue;
6645
6646 // If IsSExt is true, we are in this situation:
6647 // a = Val
6648 // b = sext ty1 a to ty2
6649 // c = sext ty1 a to ty3
6650 // Assuming ty2 is shorter than ty3, this could be turned into:
6651 // a = Val
6652 // b = sext ty1 a to ty2
6653 // c = sext ty2 b to ty3
6654 // However, the last sext is not free.
6655 if (IsSExt)
6656 return false;
6657
6658 // This is a ZExt, maybe this is free to extend from one type to another.
6659 // In that case, we would not account for a different use.
6660 Type *NarrowTy;
6661 Type *LargeTy;
6662 if (ExtTy->getScalarType()->getIntegerBitWidth() >
6663 CurTy->getScalarType()->getIntegerBitWidth()) {
6664 NarrowTy = CurTy;
6665 LargeTy = ExtTy;
6666 } else {
6667 NarrowTy = ExtTy;
6668 LargeTy = CurTy;
6669 }
6670
6671 if (!TLI.isZExtFree(NarrowTy, LargeTy))
6672 return false;
6673 }
6674 // All uses are the same or can be derived from one another for free.
6675 return true;
6676}
6677
6678/// Try to speculatively promote extensions in \p Exts and continue
6679/// promoting through newly promoted operands recursively as far as doing so is
6680/// profitable. Save extensions profitably moved up, in \p ProfitablyMovedExts.
6681/// When some promotion happened, \p TPT contains the proper state to revert
6682/// them.
6683///
6684/// \return true if some promotion happened, false otherwise.
6685bool CodeGenPrepare::tryToPromoteExts(
6686 TypePromotionTransaction &TPT, const SmallVectorImpl<Instruction *> &Exts,
6687 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
6688 unsigned CreatedInstsCost) {
6689 bool Promoted = false;
6690
6691 // Iterate over all the extensions to try to promote them.
6692 for (auto *I : Exts) {
6693 // Early check if we directly have ext(load).
6694 if (isa<LoadInst>(I->getOperand(0))) {
6695 ProfitablyMovedExts.push_back(I);
6696 continue;
6697 }
6698
6699 // Check whether or not we want to do any promotion. The reason we have
6700 // this check inside the for loop is to catch the case where an extension
6701 // is directly fed by a load because in such case the extension can be moved
6702 // up without any promotion on its operands.
6704 return false;
6705
6706 // Get the action to perform the promotion.
6707 TypePromotionHelper::Action TPH =
6708 TypePromotionHelper::getAction(I, InsertedInsts, *TLI, PromotedInsts);
6709 // Check if we can promote.
6710 if (!TPH) {
6711 // Save the current extension as we cannot move up through its operand.
6712 ProfitablyMovedExts.push_back(I);
6713 continue;
6714 }
6715
6716 // Save the current state.
6717 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
6718 TPT.getRestorationPoint();
6719 SmallVector<Instruction *, 4> NewExts;
6720 unsigned NewCreatedInstsCost = 0;
6721 unsigned ExtCost = !TLI->isExtFree(I);
6722 // Promote.
6723 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
6724 &NewExts, nullptr, *TLI);
6725 assert(PromotedVal &&
6726 "TypePromotionHelper should have filtered out those cases");
6727
6728 // We would be able to merge only one extension in a load.
6729 // Therefore, if we have more than 1 new extension we heuristically
6730 // cut this search path, because it means we degrade the code quality.
6731 // With exactly 2, the transformation is neutral, because we will merge
6732 // one extension but leave one. However, we optimistically keep going,
6733 // because the new extension may be removed too. Also avoid replacing a
6734 // single free extension with multiple extensions, as this increases the
6735 // number of IR instructions while not providing any savings.
6736 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
6737 // FIXME: It would be possible to propagate a negative value instead of
6738 // conservatively ceiling it to 0.
6739 TotalCreatedInstsCost =
6740 std::max((long long)0, (TotalCreatedInstsCost - ExtCost));
6741 if (!StressExtLdPromotion &&
6742 (TotalCreatedInstsCost > 1 ||
6743 !isPromotedInstructionLegal(*TLI, *DL, PromotedVal) ||
6744 (ExtCost == 0 && NewExts.size() > 1))) {
6745 // This promotion is not profitable, rollback to the previous state, and
6746 // save the current extension in ProfitablyMovedExts as the latest
6747 // speculative promotion turned out to be unprofitable.
6748 TPT.rollback(LastKnownGood);
6749 ProfitablyMovedExts.push_back(I);
6750 continue;
6751 }
6752 // Continue promoting NewExts as far as doing so is profitable.
6753 SmallVector<Instruction *, 2> NewlyMovedExts;
6754 (void)tryToPromoteExts(TPT, NewExts, NewlyMovedExts, TotalCreatedInstsCost);
6755 bool NewPromoted = false;
6756 for (auto *ExtInst : NewlyMovedExts) {
6757 Instruction *MovedExt = cast<Instruction>(ExtInst);
6758 Value *ExtOperand = MovedExt->getOperand(0);
6759 // If we have reached to a load, we need this extra profitability check
6760 // as it could potentially be merged into an ext(load).
6761 if (isa<LoadInst>(ExtOperand) &&
6762 !(StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
6763 (ExtOperand->hasOneUse() || hasSameExtUse(ExtOperand, *TLI))))
6764 continue;
6765
6766 ProfitablyMovedExts.push_back(MovedExt);
6767 NewPromoted = true;
6768 }
6769
6770 // If none of speculative promotions for NewExts is profitable, rollback
6771 // and save the current extension (I) as the last profitable extension.
6772 if (!NewPromoted) {
6773 TPT.rollback(LastKnownGood);
6774 ProfitablyMovedExts.push_back(I);
6775 continue;
6776 }
6777 // The promotion is profitable.
6778 Promoted = true;
6779 }
6780 return Promoted;
6781}
6782
6783/// Merging redundant sexts when one is dominating the other.
6784bool CodeGenPrepare::mergeSExts(Function &F) {
6785 bool Changed = false;
6786 for (auto &Entry : ValToSExtendedUses) {
6787 SExts &Insts = Entry.second;
6788 SExts CurPts;
6789 for (Instruction *Inst : Insts) {
6790 if (RemovedInsts.count(Inst) || !isa<SExtInst>(Inst) ||
6791 Inst->getOperand(0) != Entry.first)
6792 continue;
6793 bool inserted = false;
6794 for (auto &Pt : CurPts) {
6795 if (getDT().dominates(Inst, Pt)) {
6796 replaceAllUsesWith(Pt, Inst, FreshBBs, IsHugeFunc);
6797 RemovedInsts.insert(Pt);
6798 Pt->removeFromParent();
6799 Pt = Inst;
6800 inserted = true;
6801 Changed = true;
6802 break;
6803 }
6804 if (!getDT().dominates(Pt, Inst))
6805 // Give up if we need to merge in a common dominator as the
6806 // experiments show it is not profitable.
6807 continue;
6808 replaceAllUsesWith(Inst, Pt, FreshBBs, IsHugeFunc);
6809 RemovedInsts.insert(Inst);
6810 Inst->removeFromParent();
6811 inserted = true;
6812 Changed = true;
6813 break;
6814 }
6815 if (!inserted)
6816 CurPts.push_back(Inst);
6817 }
6818 }
6819 return Changed;
6820}
6821
6822// Splitting large data structures so that the GEPs accessing them can have
6823// smaller offsets so that they can be sunk to the same blocks as their users.
6824// For example, a large struct starting from %base is split into two parts
6825// where the second part starts from %new_base.
6826//
6827// Before:
6828// BB0:
6829// %base =
6830//
6831// BB1:
6832// %gep0 = gep %base, off0
6833// %gep1 = gep %base, off1
6834// %gep2 = gep %base, off2
6835//
6836// BB2:
6837// %load1 = load %gep0
6838// %load2 = load %gep1
6839// %load3 = load %gep2
6840//
6841// After:
6842// BB0:
6843// %base =
6844// %new_base = gep %base, off0
6845//
6846// BB1:
6847// %new_gep0 = %new_base
6848// %new_gep1 = gep %new_base, off1 - off0
6849// %new_gep2 = gep %new_base, off2 - off0
6850//
6851// BB2:
6852// %load1 = load i32, i32* %new_gep0
6853// %load2 = load i32, i32* %new_gep1
6854// %load3 = load i32, i32* %new_gep2
6855//
6856// %new_gep1 and %new_gep2 can be sunk to BB2 now after the splitting because
6857// their offsets are smaller enough to fit into the addressing mode.
6858bool CodeGenPrepare::splitLargeGEPOffsets() {
6859 bool Changed = false;
6860 for (auto &Entry : LargeOffsetGEPMap) {
6861 Value *OldBase = Entry.first;
6862 SmallVectorImpl<std::pair<AssertingVH<GetElementPtrInst>, int64_t>>
6863 &LargeOffsetGEPs = Entry.second;
6864 auto compareGEPOffset =
6865 [&](const std::pair<GetElementPtrInst *, int64_t> &LHS,
6866 const std::pair<GetElementPtrInst *, int64_t> &RHS) {
6867 if (LHS.first == RHS.first)
6868 return false;
6869 if (LHS.second != RHS.second)
6870 return LHS.second < RHS.second;
6871 return LargeOffsetGEPID[LHS.first] < LargeOffsetGEPID[RHS.first];
6872 };
6873 // Sorting all the GEPs of the same data structures based on the offsets.
6874 llvm::sort(LargeOffsetGEPs, compareGEPOffset);
6875 LargeOffsetGEPs.erase(llvm::unique(LargeOffsetGEPs), LargeOffsetGEPs.end());
6876 // Skip if all the GEPs have the same offsets.
6877 if (LargeOffsetGEPs.front().second == LargeOffsetGEPs.back().second)
6878 continue;
6879 GetElementPtrInst *BaseGEP = LargeOffsetGEPs.begin()->first;
6880 int64_t BaseOffset = LargeOffsetGEPs.begin()->second;
6881 Value *NewBaseGEP = nullptr;
6882
6883 auto createNewBase = [&](int64_t BaseOffset, Value *OldBase,
6884 GetElementPtrInst *GEP) {
6885 LLVMContext &Ctx = GEP->getContext();
6886 Type *PtrIdxTy = DL->getIndexType(GEP->getType());
6887 Type *I8PtrTy =
6888 PointerType::get(Ctx, GEP->getType()->getPointerAddressSpace());
6889
6890 BasicBlock::iterator NewBaseInsertPt;
6891 BasicBlock *NewBaseInsertBB;
6892 if (auto *BaseI = dyn_cast<Instruction>(OldBase)) {
6893 // If the base of the struct is an instruction, the new base will be
6894 // inserted close to it.
6895 NewBaseInsertBB = BaseI->getParent();
6896 if (isa<PHINode>(BaseI))
6897 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
6898 else if (InvokeInst *Invoke = dyn_cast<InvokeInst>(BaseI)) {
6899 NewBaseInsertBB =
6900 SplitEdge(NewBaseInsertBB, Invoke->getNormalDest(), &getDT(), LI);
6901 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
6902 } else
6903 NewBaseInsertPt = std::next(BaseI->getIterator());
6904 } else {
6905 // If the current base is an argument or global value, the new base
6906 // will be inserted to the entry block.
6907 NewBaseInsertBB = &BaseGEP->getFunction()->getEntryBlock();
6908 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
6909 }
6910 IRBuilder<> NewBaseBuilder(NewBaseInsertBB, NewBaseInsertPt);
6911 // Create a new base.
6912 // TODO: Avoid implicit trunc?
6913 // See https://github.com/llvm/llvm-project/issues/112510.
6914 Value *BaseIndex =
6915 ConstantInt::getSigned(PtrIdxTy, BaseOffset, /*ImplicitTrunc=*/true);
6916 NewBaseGEP = OldBase;
6917 if (NewBaseGEP->getType() != I8PtrTy)
6918 NewBaseGEP = NewBaseBuilder.CreatePointerCast(NewBaseGEP, I8PtrTy);
6919 NewBaseGEP =
6920 NewBaseBuilder.CreatePtrAdd(NewBaseGEP, BaseIndex, "splitgep");
6921 NewGEPBases.insert(NewBaseGEP);
6922 return;
6923 };
6924
6925 // Check whether all the offsets can be encoded with prefered common base.
6926 if (int64_t PreferBase = TLI->getPreferredLargeGEPBaseOffset(
6927 LargeOffsetGEPs.front().second, LargeOffsetGEPs.back().second)) {
6928 BaseOffset = PreferBase;
6929 // Create a new base if the offset of the BaseGEP can be decoded with one
6930 // instruction.
6931 createNewBase(BaseOffset, OldBase, BaseGEP);
6932 }
6933
6934 auto *LargeOffsetGEP = LargeOffsetGEPs.begin();
6935 while (LargeOffsetGEP != LargeOffsetGEPs.end()) {
6936 GetElementPtrInst *GEP = LargeOffsetGEP->first;
6937 int64_t Offset = LargeOffsetGEP->second;
6938 if (Offset != BaseOffset) {
6939 TargetLowering::AddrMode AddrMode;
6940 AddrMode.HasBaseReg = true;
6941 AddrMode.BaseOffs = Offset - BaseOffset;
6942 // The result type of the GEP might not be the type of the memory
6943 // access.
6944 if (!TLI->isLegalAddressingMode(*DL, AddrMode,
6945 GEP->getResultElementType(),
6946 GEP->getAddressSpace())) {
6947 // We need to create a new base if the offset to the current base is
6948 // too large to fit into the addressing mode. So, a very large struct
6949 // may be split into several parts.
6950 BaseGEP = GEP;
6951 BaseOffset = Offset;
6952 NewBaseGEP = nullptr;
6953 }
6954 }
6955
6956 // Generate a new GEP to replace the current one.
6957 Type *PtrIdxTy = DL->getIndexType(GEP->getType());
6958
6959 if (!NewBaseGEP) {
6960 // Create a new base if we don't have one yet. Find the insertion
6961 // pointer for the new base first.
6962 createNewBase(BaseOffset, OldBase, GEP);
6963 }
6964
6965 IRBuilder<> Builder(GEP);
6966 Value *NewGEP = NewBaseGEP;
6967 if (Offset != BaseOffset) {
6968 // Calculate the new offset for the new GEP.
6969 Value *Index = ConstantInt::get(PtrIdxTy, Offset - BaseOffset);
6970 NewGEP = Builder.CreatePtrAdd(NewBaseGEP, Index);
6971 }
6972 replaceAllUsesWith(GEP, NewGEP, FreshBBs, IsHugeFunc);
6973 LargeOffsetGEPID.erase(GEP);
6974 LargeOffsetGEP = LargeOffsetGEPs.erase(LargeOffsetGEP);
6975 GEP->eraseFromParent();
6976 Changed = true;
6977 }
6978 }
6979 return Changed;
6980}
6981
6982bool CodeGenPrepare::optimizePhiType(
6983 PHINode *I, SmallPtrSetImpl<PHINode *> &Visited,
6984 SmallPtrSetImpl<Instruction *> &DeletedInstrs) {
6985 // We are looking for a collection on interconnected phi nodes that together
6986 // only use loads/bitcasts and are used by stores/bitcasts, and the bitcasts
6987 // are of the same type. Convert the whole set of nodes to the type of the
6988 // bitcast.
6989 Type *PhiTy = I->getType();
6990 Type *ConvertTy = nullptr;
6991 if (Visited.count(I) ||
6992 (!I->getType()->isIntegerTy() && !I->getType()->isFloatingPointTy()))
6993 return false;
6994
6995 SmallVector<Instruction *, 4> Worklist;
6996 Worklist.push_back(cast<Instruction>(I));
6997 SmallPtrSet<PHINode *, 4> PhiNodes;
6998 SmallPtrSet<ConstantData *, 4> Constants;
6999 PhiNodes.insert(I);
7000 Visited.insert(I);
7001 SmallPtrSet<Instruction *, 4> Defs;
7002 SmallPtrSet<Instruction *, 4> Uses;
7003 // This works by adding extra bitcasts between load/stores and removing
7004 // existing bitcasts. If we have a phi(bitcast(load)) or a store(bitcast(phi))
7005 // we can get in the situation where we remove a bitcast in one iteration
7006 // just to add it again in the next. We need to ensure that at least one
7007 // bitcast we remove are anchored to something that will not change back.
7008 bool AnyAnchored = false;
7009
7010 while (!Worklist.empty()) {
7011 Instruction *II = Worklist.pop_back_val();
7012
7013 if (auto *Phi = dyn_cast<PHINode>(II)) {
7014 // Handle Defs, which might also be PHI's
7015 for (Value *V : Phi->incoming_values()) {
7016 if (auto *OpPhi = dyn_cast<PHINode>(V)) {
7017 if (!PhiNodes.count(OpPhi)) {
7018 if (!Visited.insert(OpPhi).second)
7019 return false;
7020 PhiNodes.insert(OpPhi);
7021 Worklist.push_back(OpPhi);
7022 }
7023 } else if (auto *OpLoad = dyn_cast<LoadInst>(V)) {
7024 if (!OpLoad->isSimple())
7025 return false;
7026 if (Defs.insert(OpLoad).second)
7027 Worklist.push_back(OpLoad);
7028 } else if (auto *OpEx = dyn_cast<ExtractElementInst>(V)) {
7029 if (Defs.insert(OpEx).second)
7030 Worklist.push_back(OpEx);
7031 } else if (auto *OpBC = dyn_cast<BitCastInst>(V)) {
7032 if (!ConvertTy)
7033 ConvertTy = OpBC->getOperand(0)->getType();
7034 if (OpBC->getOperand(0)->getType() != ConvertTy)
7035 return false;
7036 if (Defs.insert(OpBC).second) {
7037 Worklist.push_back(OpBC);
7038 AnyAnchored |= !isa<LoadInst>(OpBC->getOperand(0)) &&
7039 !isa<ExtractElementInst>(OpBC->getOperand(0));
7040 }
7041 } else if (auto *OpC = dyn_cast<ConstantData>(V))
7042 Constants.insert(OpC);
7043 else
7044 return false;
7045 }
7046 }
7047
7048 // Handle uses which might also be phi's
7049 for (User *V : II->users()) {
7050 if (auto *OpPhi = dyn_cast<PHINode>(V)) {
7051 if (!PhiNodes.count(OpPhi)) {
7052 if (Visited.count(OpPhi))
7053 return false;
7054 PhiNodes.insert(OpPhi);
7055 Visited.insert(OpPhi);
7056 Worklist.push_back(OpPhi);
7057 }
7058 } else if (auto *OpStore = dyn_cast<StoreInst>(V)) {
7059 if (!OpStore->isSimple() || OpStore->getOperand(0) != II)
7060 return false;
7061 Uses.insert(OpStore);
7062 } else if (auto *OpBC = dyn_cast<BitCastInst>(V)) {
7063 if (!ConvertTy)
7064 ConvertTy = OpBC->getType();
7065 if (OpBC->getType() != ConvertTy)
7066 return false;
7067 Uses.insert(OpBC);
7068 AnyAnchored |=
7069 any_of(OpBC->users(), [](User *U) { return !isa<StoreInst>(U); });
7070 } else {
7071 return false;
7072 }
7073 }
7074 }
7075
7076 if (!ConvertTy || !AnyAnchored || PhiTy == ConvertTy ||
7077 !TLI->shouldConvertPhiType(PhiTy, ConvertTy))
7078 return false;
7079
7080 LLVM_DEBUG(dbgs() << "Converting " << *I << "\n and connected nodes to "
7081 << *ConvertTy << "\n");
7082
7083 // Create all the new phi nodes of the new type, and bitcast any loads to the
7084 // correct type.
7085 ValueToValueMap ValMap;
7086 for (ConstantData *C : Constants)
7087 ValMap[C] = ConstantExpr::getBitCast(C, ConvertTy);
7088 for (Instruction *D : Defs) {
7089 if (isa<BitCastInst>(D)) {
7090 ValMap[D] = D->getOperand(0);
7091 DeletedInstrs.insert(D);
7092 } else {
7093 BasicBlock::iterator insertPt = std::next(D->getIterator());
7094 ValMap[D] = new BitCastInst(D, ConvertTy, D->getName() + ".bc", insertPt);
7095 }
7096 }
7097 for (PHINode *Phi : PhiNodes)
7098 ValMap[Phi] = PHINode::Create(ConvertTy, Phi->getNumIncomingValues(),
7099 Phi->getName() + ".tc", Phi->getIterator());
7100 // Pipe together all the PhiNodes.
7101 for (PHINode *Phi : PhiNodes) {
7102 PHINode *NewPhi = cast<PHINode>(ValMap[Phi]);
7103 for (int i = 0, e = Phi->getNumIncomingValues(); i < e; i++)
7104 NewPhi->addIncoming(ValMap[Phi->getIncomingValue(i)],
7105 Phi->getIncomingBlock(i));
7106 Visited.insert(NewPhi);
7107 }
7108 // And finally pipe up the stores and bitcasts
7109 for (Instruction *U : Uses) {
7110 if (isa<BitCastInst>(U)) {
7111 DeletedInstrs.insert(U);
7112 replaceAllUsesWith(U, ValMap[U->getOperand(0)], FreshBBs, IsHugeFunc);
7113 } else {
7114 U->setOperand(0, new BitCastInst(ValMap[U->getOperand(0)], PhiTy, "bc",
7115 U->getIterator()));
7116 }
7117 }
7118
7119 // Save the removed phis to be deleted later.
7120 DeletedInstrs.insert_range(PhiNodes);
7121 return true;
7122}
7123
7124bool CodeGenPrepare::optimizePhiTypes(Function &F) {
7125 if (!OptimizePhiTypes)
7126 return false;
7127
7128 bool Changed = false;
7129 SmallPtrSet<PHINode *, 4> Visited;
7130 SmallPtrSet<Instruction *, 4> DeletedInstrs;
7131
7132 // Attempt to optimize all the phis in the functions to the correct type.
7133 for (auto &BB : F)
7134 for (auto &Phi : BB.phis())
7135 Changed |= optimizePhiType(&Phi, Visited, DeletedInstrs);
7136
7137 // Remove any old phi's that have been converted.
7138 for (auto *I : DeletedInstrs) {
7139 replaceAllUsesWith(I, PoisonValue::get(I->getType()), FreshBBs, IsHugeFunc);
7140 I->eraseFromParent();
7141 }
7142
7143 return Changed;
7144}
7145
7146/// Return true, if an ext(load) can be formed from an extension in
7147/// \p MovedExts.
7148bool CodeGenPrepare::canFormExtLd(
7149 const SmallVectorImpl<Instruction *> &MovedExts, LoadInst *&LI,
7150 Instruction *&Inst, bool HasPromoted) {
7151 for (auto *MovedExtInst : MovedExts) {
7152 if (isa<LoadInst>(MovedExtInst->getOperand(0))) {
7153 LI = cast<LoadInst>(MovedExtInst->getOperand(0));
7154 Inst = MovedExtInst;
7155 break;
7156 }
7157 }
7158 if (!LI)
7159 return false;
7160
7161 // If they're already in the same block, there's nothing to do.
7162 // Make the cheap checks first if we did not promote.
7163 // If we promoted, we need to check if it is indeed profitable.
7164 if (!HasPromoted && LI->getParent() == Inst->getParent())
7165 return false;
7166
7167 return TLI->isExtLoad(LI, Inst, *DL);
7168}
7169
7170/// Move a zext or sext fed by a load into the same basic block as the load,
7171/// unless conditions are unfavorable. This allows SelectionDAG to fold the
7172/// extend into the load.
7173///
7174/// E.g.,
7175/// \code
7176/// %ld = load i32* %addr
7177/// %add = add nuw i32 %ld, 4
7178/// %zext = zext i32 %add to i64
7179// \endcode
7180/// =>
7181/// \code
7182/// %ld = load i32* %addr
7183/// %zext = zext i32 %ld to i64
7184/// %add = add nuw i64 %zext, 4
7185/// \encode
7186/// Note that the promotion in %add to i64 is done in tryToPromoteExts(), which
7187/// allow us to match zext(load i32*) to i64.
7188///
7189/// Also, try to promote the computations used to obtain a sign extended
7190/// value used into memory accesses.
7191/// E.g.,
7192/// \code
7193/// a = add nsw i32 b, 3
7194/// d = sext i32 a to i64
7195/// e = getelementptr ..., i64 d
7196/// \endcode
7197/// =>
7198/// \code
7199/// f = sext i32 b to i64
7200/// a = add nsw i64 f, 3
7201/// e = getelementptr ..., i64 a
7202/// \endcode
7203///
7204/// \p Inst[in/out] the extension may be modified during the process if some
7205/// promotions apply.
7206bool CodeGenPrepare::optimizeExt(Instruction *&Inst) {
7207 bool AllowPromotionWithoutCommonHeader = false;
7208 /// See if it is an interesting sext operations for the address type
7209 /// promotion before trying to promote it, e.g., the ones with the right
7210 /// type and used in memory accesses.
7211 bool ATPConsiderable = TTI->shouldConsiderAddressTypePromotion(
7212 *Inst, AllowPromotionWithoutCommonHeader);
7213 TypePromotionTransaction TPT(RemovedInsts);
7214 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
7215 TPT.getRestorationPoint();
7217 SmallVector<Instruction *, 2> SpeculativelyMovedExts;
7218 Exts.push_back(Inst);
7219
7220 bool HasPromoted = tryToPromoteExts(TPT, Exts, SpeculativelyMovedExts);
7221
7222 // Look for a load being extended.
7223 LoadInst *LI = nullptr;
7224 Instruction *ExtFedByLoad;
7225
7226 // Try to promote a chain of computation if it allows to form an extended
7227 // load.
7228 if (canFormExtLd(SpeculativelyMovedExts, LI, ExtFedByLoad, HasPromoted)) {
7229 assert(LI && ExtFedByLoad && "Expect a valid load and extension");
7230 TPT.commit();
7231 // Move the extend into the same block as the load.
7232 ExtFedByLoad->moveAfter(LI);
7233 ++NumExtsMoved;
7234 Inst = ExtFedByLoad;
7235 return true;
7236 }
7237
7238 // Continue promoting SExts if known as considerable depending on targets.
7239 if (ATPConsiderable &&
7240 performAddressTypePromotion(Inst, AllowPromotionWithoutCommonHeader,
7241 HasPromoted, TPT, SpeculativelyMovedExts))
7242 return true;
7243
7244 TPT.rollback(LastKnownGood);
7245 return false;
7246}
7247
7248// Perform address type promotion if doing so is profitable.
7249// If AllowPromotionWithoutCommonHeader == false, we should find other sext
7250// instructions that sign extended the same initial value. However, if
7251// AllowPromotionWithoutCommonHeader == true, we expect promoting the
7252// extension is just profitable.
7253bool CodeGenPrepare::performAddressTypePromotion(
7254 Instruction *&Inst, bool AllowPromotionWithoutCommonHeader,
7255 bool HasPromoted, TypePromotionTransaction &TPT,
7256 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts) {
7257 bool Promoted = false;
7258 SmallPtrSet<Instruction *, 1> UnhandledExts;
7259 bool AllSeenFirst = true;
7260 for (auto *I : SpeculativelyMovedExts) {
7261 Value *HeadOfChain = I->getOperand(0);
7262 auto AlreadySeen = SeenChainsForSExt.find(HeadOfChain);
7263 // If there is an unhandled SExt which has the same header, try to promote
7264 // it as well.
7265 if (AlreadySeen != SeenChainsForSExt.end()) {
7266 if (AlreadySeen->second != nullptr)
7267 UnhandledExts.insert(AlreadySeen->second);
7268 AllSeenFirst = false;
7269 }
7270 }
7271
7272 if (!AllSeenFirst || (AllowPromotionWithoutCommonHeader &&
7273 SpeculativelyMovedExts.size() == 1)) {
7274 TPT.commit();
7275 if (HasPromoted)
7276 Promoted = true;
7277 for (auto *I : SpeculativelyMovedExts) {
7278 Value *HeadOfChain = I->getOperand(0);
7279 SeenChainsForSExt[HeadOfChain] = nullptr;
7280 ValToSExtendedUses[HeadOfChain].push_back(I);
7281 }
7282 // Update Inst as promotion happen.
7283 Inst = SpeculativelyMovedExts.pop_back_val();
7284 } else {
7285 // This is the first chain visited from the header, keep the current chain
7286 // as unhandled. Defer to promote this until we encounter another SExt
7287 // chain derived from the same header.
7288 for (auto *I : SpeculativelyMovedExts) {
7289 Value *HeadOfChain = I->getOperand(0);
7290 SeenChainsForSExt[HeadOfChain] = Inst;
7291 }
7292 return false;
7293 }
7294
7295 if (!AllSeenFirst && !UnhandledExts.empty())
7296 for (auto *VisitedSExt : UnhandledExts) {
7297 if (RemovedInsts.count(VisitedSExt))
7298 continue;
7299 TypePromotionTransaction TPT(RemovedInsts);
7301 SmallVector<Instruction *, 2> Chains;
7302 Exts.push_back(VisitedSExt);
7303 bool HasPromoted = tryToPromoteExts(TPT, Exts, Chains);
7304 TPT.commit();
7305 if (HasPromoted)
7306 Promoted = true;
7307 for (auto *I : Chains) {
7308 Value *HeadOfChain = I->getOperand(0);
7309 // Mark this as handled.
7310 SeenChainsForSExt[HeadOfChain] = nullptr;
7311 ValToSExtendedUses[HeadOfChain].push_back(I);
7312 }
7313 }
7314 return Promoted;
7315}
7316
7317bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
7318 BasicBlock *DefBB = I->getParent();
7319
7320 // If the result of a {s|z}ext and its source are both live out, rewrite all
7321 // other uses of the source with result of extension.
7322 Value *Src = I->getOperand(0);
7323 if (Src->hasOneUse())
7324 return false;
7325
7326 // Only do this xform if truncating is free.
7327 if (!TLI->isTruncateFree(I->getType(), Src->getType()))
7328 return false;
7329
7330 // Only safe to perform the optimization if the source is also defined in
7331 // this block.
7332 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
7333 return false;
7334
7335 bool DefIsLiveOut = false;
7336 for (User *U : I->users()) {
7338
7339 // Figure out which BB this ext is used in.
7340 BasicBlock *UserBB = UI->getParent();
7341 if (UserBB == DefBB)
7342 continue;
7343 DefIsLiveOut = true;
7344 break;
7345 }
7346 if (!DefIsLiveOut)
7347 return false;
7348
7349 // Make sure none of the uses are PHI nodes.
7350 for (User *U : Src->users()) {
7352 BasicBlock *UserBB = UI->getParent();
7353 if (UserBB == DefBB)
7354 continue;
7355 // Be conservative. We don't want this xform to end up introducing
7356 // reloads just before load / store instructions.
7357 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
7358 return false;
7359 }
7360
7361 // InsertedTruncs - Only insert one trunc in each block once.
7362 DenseMap<BasicBlock *, Instruction *> InsertedTruncs;
7363
7364 bool MadeChange = false;
7365 for (Use &U : Src->uses()) {
7366 Instruction *User = cast<Instruction>(U.getUser());
7367
7368 // Figure out which BB this ext is used in.
7369 BasicBlock *UserBB = User->getParent();
7370 if (UserBB == DefBB)
7371 continue;
7372
7373 // Both src and def are live in this block. Rewrite the use.
7374 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
7375
7376 if (!InsertedTrunc) {
7377 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
7378 assert(InsertPt != UserBB->end());
7379 InsertedTrunc = new TruncInst(I, Src->getType(), "");
7380 InsertedTrunc->insertBefore(*UserBB, InsertPt);
7381 InsertedInsts.insert(InsertedTrunc);
7382 }
7383
7384 // Replace a use of the {s|z}ext source with a use of the result.
7385 U = InsertedTrunc;
7386 ++NumExtUses;
7387 MadeChange = true;
7388 }
7389
7390 return MadeChange;
7391}
7392
7393// Find loads whose uses only use some of the loaded value's bits. Add an "and"
7394// just after the load if the target can fold this into one extload instruction,
7395// with the hope of eliminating some of the other later "and" instructions using
7396// the loaded value. "and"s that are made trivially redundant by the insertion
7397// of the new "and" are removed by this function, while others (e.g. those whose
7398// path from the load goes through a phi) are left for isel to potentially
7399// remove.
7400//
7401// For example:
7402//
7403// b0:
7404// x = load i32
7405// ...
7406// b1:
7407// y = and x, 0xff
7408// z = use y
7409//
7410// becomes:
7411//
7412// b0:
7413// x = load i32
7414// x' = and x, 0xff
7415// ...
7416// b1:
7417// z = use x'
7418//
7419// whereas:
7420//
7421// b0:
7422// x1 = load i32
7423// ...
7424// b1:
7425// x2 = load i32
7426// ...
7427// b2:
7428// x = phi x1, x2
7429// y = and x, 0xff
7430//
7431// becomes (after a call to optimizeLoadExt for each load):
7432//
7433// b0:
7434// x1 = load i32
7435// x1' = and x1, 0xff
7436// ...
7437// b1:
7438// x2 = load i32
7439// x2' = and x2, 0xff
7440// ...
7441// b2:
7442// x = phi x1', x2'
7443// y = and x, 0xff
7444bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
7445 if (!Load->isSimple() || !Load->getType()->isIntOrPtrTy())
7446 return false;
7447
7448 // Skip loads we've already transformed.
7449 if (Load->hasOneUse() &&
7450 InsertedInsts.count(cast<Instruction>(*Load->user_begin())))
7451 return false;
7452
7453 // Look at all uses of Load, looking through phis, to determine how many bits
7454 // of the loaded value are needed.
7455 SmallVector<Instruction *, 8> WorkList;
7456 SmallPtrSet<Instruction *, 16> Visited;
7457 SmallVector<Instruction *, 8> AndsToMaybeRemove;
7458 SmallVector<Instruction *, 8> DropFlags;
7459 for (auto *U : Load->users())
7460 WorkList.push_back(cast<Instruction>(U));
7461
7462 EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
7463 unsigned BitWidth = LoadResultVT.getSizeInBits();
7464 // If the BitWidth is 0, do not try to optimize the type
7465 if (BitWidth == 0)
7466 return false;
7467
7468 APInt DemandBits(BitWidth, 0);
7469 APInt WidestAndBits(BitWidth, 0);
7470
7471 while (!WorkList.empty()) {
7472 Instruction *I = WorkList.pop_back_val();
7473
7474 // Break use-def graph loops.
7475 if (!Visited.insert(I).second)
7476 continue;
7477
7478 // For a PHI node, push all of its users.
7479 if (auto *Phi = dyn_cast<PHINode>(I)) {
7480 for (auto *U : Phi->users())
7481 WorkList.push_back(cast<Instruction>(U));
7482 continue;
7483 }
7484
7485 switch (I->getOpcode()) {
7486 case Instruction::And: {
7487 auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
7488 if (!AndC)
7489 return false;
7490 APInt AndBits = AndC->getValue();
7491 DemandBits |= AndBits;
7492 // Keep track of the widest and mask we see.
7493 if (AndBits.ugt(WidestAndBits))
7494 WidestAndBits = AndBits;
7495 if (AndBits == WidestAndBits && I->getOperand(0) == Load)
7496 AndsToMaybeRemove.push_back(I);
7497 break;
7498 }
7499
7500 case Instruction::Shl: {
7501 auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
7502 if (!ShlC)
7503 return false;
7504 uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
7505 DemandBits.setLowBits(BitWidth - ShiftAmt);
7506 DropFlags.push_back(I);
7507 break;
7508 }
7509
7510 case Instruction::Trunc: {
7511 EVT TruncVT = TLI->getValueType(*DL, I->getType());
7512 unsigned TruncBitWidth = TruncVT.getSizeInBits();
7513 DemandBits.setLowBits(TruncBitWidth);
7514 DropFlags.push_back(I);
7515 break;
7516 }
7517
7518 default:
7519 return false;
7520 }
7521 }
7522
7523 uint32_t ActiveBits = DemandBits.getActiveBits();
7524 // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
7525 // target even if isLoadLegal says an i1 EXTLOAD is valid. For example,
7526 // for the AArch64 target isLoadLegal(i32, i1, ..., ZEXTLOAD, false) returns
7527 // true, but (and (load x) 1) is not matched as a single instruction, rather
7528 // as a LDR followed by an AND.
7529 // TODO: Look into removing this restriction by fixing backends to either
7530 // return false for isLoadLegal for i1 or have them select this pattern to
7531 // a single instruction.
7532 //
7533 // Also avoid hoisting if we didn't see any ands with the exact DemandBits
7534 // mask, since these are the only ands that will be removed by isel.
7535 if (ActiveBits <= 1 || !DemandBits.isMask(ActiveBits) ||
7536 WidestAndBits != DemandBits)
7537 return false;
7538
7539 LLVMContext &Ctx = Load->getType()->getContext();
7540 Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
7541 EVT TruncVT = TLI->getValueType(*DL, TruncTy);
7542
7543 // Reject cases that won't be matched as extloads.
7544 if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
7545 !TLI->isLoadLegal(LoadResultVT, TruncVT, Load->getAlign(),
7546 Load->getPointerAddressSpace(), ISD::ZEXTLOAD, false))
7547 return false;
7548
7549 IRBuilder<> Builder(Load->getNextNode());
7550 auto *NewAnd = cast<Instruction>(
7551 Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
7552 // Mark this instruction as "inserted by CGP", so that other
7553 // optimizations don't touch it.
7554 InsertedInsts.insert(NewAnd);
7555
7556 // Replace all uses of load with new and (except for the use of load in the
7557 // new and itself).
7558 replaceAllUsesWith(Load, NewAnd, FreshBBs, IsHugeFunc);
7559 NewAnd->setOperand(0, Load);
7560
7561 // Remove any and instructions that are now redundant.
7562 for (auto *And : AndsToMaybeRemove)
7563 // Check that the and mask is the same as the one we decided to put on the
7564 // new and.
7565 if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
7566 replaceAllUsesWith(And, NewAnd, FreshBBs, IsHugeFunc);
7567 if (&*CurInstIterator == And)
7568 CurInstIterator = std::next(And->getIterator());
7569 And->eraseFromParent();
7570 ++NumAndUses;
7571 }
7572
7573 // NSW flags may not longer hold.
7574 for (auto *Inst : DropFlags)
7575 Inst->setHasNoSignedWrap(false);
7576
7577 ++NumAndsAdded;
7578 return true;
7579}
7580
7581/// Check if V (an operand of a select instruction) is an expensive instruction
7582/// that is only used once.
7584 auto *I = dyn_cast<Instruction>(V);
7585 // If it's safe to speculatively execute, then it should not have side
7586 // effects; therefore, it's safe to sink and possibly *not* execute.
7587 return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
7588 TTI->isExpensiveToSpeculativelyExecute(I);
7589}
7590
7591/// Returns true if a SelectInst should be turned into an explicit branch.
7593 const TargetLowering *TLI,
7594 SelectInst *SI) {
7595 // If even a predictable select is cheap, then a branch can't be cheaper.
7596 if (!TLI->isPredictableSelectExpensive())
7597 return false;
7598
7599 // FIXME: This should use the same heuristics as IfConversion to determine
7600 // whether a select is better represented as a branch.
7601
7602 // If metadata tells us that the select condition is obviously predictable,
7603 // then we want to replace the select with a branch.
7604 uint64_t TrueWeight, FalseWeight;
7605 if (extractBranchWeights(*SI, TrueWeight, FalseWeight)) {
7606 uint64_t Max = std::max(TrueWeight, FalseWeight);
7607 uint64_t Sum = TrueWeight + FalseWeight;
7608 if (Sum != 0) {
7609 auto Probability = BranchProbability::getBranchProbability(Max, Sum);
7610 if (Probability > TTI->getPredictableBranchThreshold())
7611 return true;
7612 }
7613 }
7614
7615 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
7616
7617 // If a branch is predictable, an out-of-order CPU can avoid blocking on its
7618 // comparison condition. If the compare has more than one use, there's
7619 // probably another cmov or setcc around, so it's not worth emitting a branch.
7620 if (!Cmp || !Cmp->hasOneUse())
7621 return false;
7622
7623 // If either operand of the select is expensive and only needed on one side
7624 // of the select, we should form a branch.
7625 if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
7626 sinkSelectOperand(TTI, SI->getFalseValue()))
7627 return true;
7628
7629 return false;
7630}
7631
7632/// If \p isTrue is true, return the true value of \p SI, otherwise return
7633/// false value of \p SI. If the true/false value of \p SI is defined by any
7634/// select instructions in \p Selects, look through the defining select
7635/// instruction until the true/false value is not defined in \p Selects.
7636static Value *
7638 const SmallPtrSet<const Instruction *, 2> &Selects) {
7639 Value *V = nullptr;
7640
7641 for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI);
7642 DefSI = dyn_cast<SelectInst>(V)) {
7643 assert(DefSI->getCondition() == SI->getCondition() &&
7644 "The condition of DefSI does not match with SI");
7645 V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
7646 }
7647
7648 assert(V && "Failed to get select true/false value");
7649 return V;
7650}
7651
7652bool CodeGenPrepare::optimizeShiftInst(BinaryOperator *Shift) {
7653 assert(Shift->isShift() && "Expected a shift");
7654
7655 // If this is (1) a vector shift, (2) shifts by scalars are cheaper than
7656 // general vector shifts, and (3) the shift amount is a select-of-splatted
7657 // values, hoist the shifts before the select:
7658 // shift Op0, (select Cond, TVal, FVal) -->
7659 // select Cond, (shift Op0, TVal), (shift Op0, FVal)
7660 //
7661 // This is inverting a generic IR transform when we know that the cost of a
7662 // general vector shift is more than the cost of 2 shift-by-scalars.
7663 // We can't do this effectively in SDAG because we may not be able to
7664 // determine if the select operands are splats from within a basic block.
7665 Type *Ty = Shift->getType();
7666 if (!Ty->isVectorTy() || !TTI->isVectorShiftByScalarCheap(Ty))
7667 return false;
7668 Value *Cond, *TVal, *FVal;
7669 if (!match(Shift->getOperand(1),
7670 m_OneUse(m_Select(m_Value(Cond), m_Value(TVal), m_Value(FVal)))))
7671 return false;
7672 if (!isSplatValue(TVal) || !isSplatValue(FVal))
7673 return false;
7674
7675 IRBuilder<> Builder(Shift);
7676 BinaryOperator::BinaryOps Opcode = Shift->getOpcode();
7677 Value *NewTVal = Builder.CreateBinOp(Opcode, Shift->getOperand(0), TVal);
7678 Value *NewFVal = Builder.CreateBinOp(Opcode, Shift->getOperand(0), FVal);
7679 Value *NewSel = Builder.CreateSelect(Cond, NewTVal, NewFVal);
7680 replaceAllUsesWith(Shift, NewSel, FreshBBs, IsHugeFunc);
7681 Shift->eraseFromParent();
7682 return true;
7683}
7684
7685bool CodeGenPrepare::optimizeFunnelShift(IntrinsicInst *Fsh) {
7686 Intrinsic::ID Opcode = Fsh->getIntrinsicID();
7687 assert((Opcode == Intrinsic::fshl || Opcode == Intrinsic::fshr) &&
7688 "Expected a funnel shift");
7689
7690 // If this is (1) a vector funnel shift, (2) shifts by scalars are cheaper
7691 // than general vector shifts, and (3) the shift amount is select-of-splatted
7692 // values, hoist the funnel shifts before the select:
7693 // fsh Op0, Op1, (select Cond, TVal, FVal) -->
7694 // select Cond, (fsh Op0, Op1, TVal), (fsh Op0, Op1, FVal)
7695 //
7696 // This is inverting a generic IR transform when we know that the cost of a
7697 // general vector shift is more than the cost of 2 shift-by-scalars.
7698 // We can't do this effectively in SDAG because we may not be able to
7699 // determine if the select operands are splats from within a basic block.
7700 Type *Ty = Fsh->getType();
7701 if (!Ty->isVectorTy() || !TTI->isVectorShiftByScalarCheap(Ty))
7702 return false;
7703 Value *Cond, *TVal, *FVal;
7704 if (!match(Fsh->getOperand(2),
7705 m_OneUse(m_Select(m_Value(Cond), m_Value(TVal), m_Value(FVal)))))
7706 return false;
7707 if (!isSplatValue(TVal) || !isSplatValue(FVal))
7708 return false;
7709
7710 IRBuilder<> Builder(Fsh);
7711 Value *X = Fsh->getOperand(0), *Y = Fsh->getOperand(1);
7712 Value *NewTVal = Builder.CreateIntrinsic(Opcode, Ty, {X, Y, TVal});
7713 Value *NewFVal = Builder.CreateIntrinsic(Opcode, Ty, {X, Y, FVal});
7714 Value *NewSel = Builder.CreateSelect(Cond, NewTVal, NewFVal);
7715 replaceAllUsesWith(Fsh, NewSel, FreshBBs, IsHugeFunc);
7716 Fsh->eraseFromParent();
7717 return true;
7718}
7719
7720/// If we have a SelectInst that will likely profit from branch prediction,
7721/// turn it into a branch.
7722bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
7724 return false;
7725
7726 // If the SelectOptimize pass is enabled, selects have already been optimized.
7728 return false;
7729
7730 // Find all consecutive select instructions that share the same condition.
7732 ASI.push_back(SI);
7734 It != SI->getParent()->end(); ++It) {
7735 SelectInst *I = dyn_cast<SelectInst>(&*It);
7736 if (I && SI->getCondition() == I->getCondition()) {
7737 ASI.push_back(I);
7738 } else {
7739 break;
7740 }
7741 }
7742
7743 SelectInst *LastSI = ASI.back();
7744 // Increment the current iterator to skip all the rest of select instructions
7745 // because they will be either "not lowered" or "all lowered" to branch.
7746 CurInstIterator = std::next(LastSI->getIterator());
7747 // Examine debug-info attached to the consecutive select instructions. They
7748 // won't be individually optimised by optimizeInst, so we need to perform
7749 // DbgVariableRecord maintenence here instead.
7750 for (SelectInst *SI : ArrayRef(ASI).drop_front())
7751 fixupDbgVariableRecordsOnInst(*SI);
7752
7753 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
7754
7755 // Can we convert the 'select' to CF ?
7756 if (VectorCond || SI->getMetadata(LLVMContext::MD_unpredictable))
7757 return false;
7758
7759 TargetLowering::SelectSupportKind SelectKind;
7760 if (SI->getType()->isVectorTy())
7761 SelectKind = TargetLowering::ScalarCondVectorVal;
7762 else
7763 SelectKind = TargetLowering::ScalarValSelect;
7764
7765 if (TLI->isSelectSupported(SelectKind) &&
7767 llvm::shouldOptimizeForSize(SI->getParent(), PSI, BFI)))
7768 return false;
7769
7770 // Transform a sequence like this:
7771 // start:
7772 // %cmp = cmp uge i32 %a, %b
7773 // %sel = select i1 %cmp, i32 %c, i32 %d
7774 //
7775 // Into:
7776 // start:
7777 // %cmp = cmp uge i32 %a, %b
7778 // %cmp.frozen = freeze %cmp
7779 // br i1 %cmp.frozen, label %select.true, label %select.false
7780 // select.true:
7781 // br label %select.end
7782 // select.false:
7783 // br label %select.end
7784 // select.end:
7785 // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
7786 //
7787 // %cmp should be frozen, otherwise it may introduce undefined behavior.
7788 // In addition, we may sink instructions that produce %c or %d from
7789 // the entry block into the destination(s) of the new branch.
7790 // If the true or false blocks do not contain a sunken instruction, that
7791 // block and its branch may be optimized away. In that case, one side of the
7792 // first branch will point directly to select.end, and the corresponding PHI
7793 // predecessor block will be the start block.
7794 // The CFG is altered here and we update the DominatorTree and the LoopInfo,
7795 // but we don't set a ModifiedDT flag to avoid restarting the function walk in
7796 // runOnFunction for each select optimized.
7797
7798 // Collect values that go on the true side and the values that go on the false
7799 // side.
7800 SmallVector<Instruction *> TrueInstrs, FalseInstrs;
7801 for (SelectInst *SI : ASI) {
7802 if (Value *V = SI->getTrueValue(); sinkSelectOperand(TTI, V))
7803 TrueInstrs.push_back(cast<Instruction>(V));
7804 if (Value *V = SI->getFalseValue(); sinkSelectOperand(TTI, V))
7805 FalseInstrs.push_back(cast<Instruction>(V));
7806 }
7807
7808 // Split the select block, according to how many (if any) values go on each
7809 // side.
7810 BasicBlock *StartBlock = SI->getParent();
7811 BasicBlock::iterator SplitPt = std::next(BasicBlock::iterator(LastSI));
7812 // We should split before any debug-info.
7813 SplitPt.setHeadBit(true);
7814
7815 IRBuilder<> IB(SI);
7816 auto *CondFr = IB.CreateFreeze(SI->getCondition(), SI->getName() + ".frozen");
7817
7818 BasicBlock *TrueBlock = nullptr;
7819 BasicBlock *FalseBlock = nullptr;
7820 BasicBlock *EndBlock = nullptr;
7821 UncondBrInst *TrueBranch = nullptr;
7822 UncondBrInst *FalseBranch = nullptr;
7823 if (TrueInstrs.size() == 0) {
7824 FalseBranch = cast<UncondBrInst>(
7825 SplitBlockAndInsertIfElse(CondFr, SplitPt, false, nullptr, DTU, LI));
7826 FalseBlock = FalseBranch->getParent();
7827 EndBlock = cast<BasicBlock>(FalseBranch->getOperand(0));
7828 } else if (FalseInstrs.size() == 0) {
7829 TrueBranch = cast<UncondBrInst>(
7830 SplitBlockAndInsertIfThen(CondFr, SplitPt, false, nullptr, DTU, LI));
7831 TrueBlock = TrueBranch->getParent();
7832 EndBlock = TrueBranch->getSuccessor();
7833 } else {
7834 Instruction *ThenTerm = nullptr;
7835 Instruction *ElseTerm = nullptr;
7836 SplitBlockAndInsertIfThenElse(CondFr, SplitPt, &ThenTerm, &ElseTerm,
7837 nullptr, DTU, LI);
7838 TrueBranch = cast<UncondBrInst>(ThenTerm);
7839 FalseBranch = cast<UncondBrInst>(ElseTerm);
7840 TrueBlock = TrueBranch->getParent();
7841 FalseBlock = FalseBranch->getParent();
7842 EndBlock = TrueBranch->getSuccessor();
7843 }
7844
7845 EndBlock->setName("select.end");
7846 if (TrueBlock)
7847 TrueBlock->setName("select.true.sink");
7848 if (FalseBlock)
7849 FalseBlock->setName(FalseInstrs.size() == 0 ? "select.false"
7850 : "select.false.sink");
7851
7852 if (IsHugeFunc) {
7853 if (TrueBlock)
7854 FreshBBs.insert(TrueBlock);
7855 if (FalseBlock)
7856 FreshBBs.insert(FalseBlock);
7857 FreshBBs.insert(EndBlock);
7858 }
7859
7860 BFI->setBlockFreq(EndBlock, BFI->getBlockFreq(StartBlock));
7861
7862 static const unsigned MD[] = {
7863 LLVMContext::MD_prof, LLVMContext::MD_unpredictable,
7864 LLVMContext::MD_make_implicit, LLVMContext::MD_dbg};
7865 StartBlock->getTerminator()->copyMetadata(*SI, MD);
7866
7867 // Sink expensive instructions into the conditional blocks to avoid executing
7868 // them speculatively.
7869 for (Instruction *I : TrueInstrs)
7870 I->moveBefore(TrueBranch->getIterator());
7871 for (Instruction *I : FalseInstrs)
7872 I->moveBefore(FalseBranch->getIterator());
7873
7874 // If we did not create a new block for one of the 'true' or 'false' paths
7875 // of the condition, it means that side of the branch goes to the end block
7876 // directly and the path originates from the start block from the point of
7877 // view of the new PHI.
7878 if (TrueBlock == nullptr)
7879 TrueBlock = StartBlock;
7880 else if (FalseBlock == nullptr)
7881 FalseBlock = StartBlock;
7882
7883 SmallPtrSet<const Instruction *, 2> INS(llvm::from_range, ASI);
7884 // Use reverse iterator because later select may use the value of the
7885 // earlier select, and we need to propagate value through earlier select
7886 // to get the PHI operand.
7887 for (SelectInst *SI : llvm::reverse(ASI)) {
7888 // The select itself is replaced with a PHI Node.
7889 PHINode *PN = PHINode::Create(SI->getType(), 2, "");
7890 PN->insertBefore(EndBlock->begin());
7891 PN->takeName(SI);
7892 PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock);
7893 PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock);
7894 PN->setDebugLoc(SI->getDebugLoc());
7895
7896 replaceAllUsesWith(SI, PN, FreshBBs, IsHugeFunc);
7897 SI->eraseFromParent();
7898 INS.erase(SI);
7899 ++NumSelectsExpanded;
7900 }
7901
7902 // Instruct OptimizeBlock to skip to the next block.
7903 CurInstIterator = StartBlock->end();
7904 return true;
7905}
7906
7907/// Some targets only accept certain types for splat inputs. For example a VDUP
7908/// in MVE takes a GPR (integer) register, and the instruction that incorporate
7909/// a VDUP (such as a VADD qd, qm, rm) also require a gpr register.
7910bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
7911 // Accept shuf(insertelem(undef/poison, val, 0), undef/poison, <0,0,..>) only
7913 m_Undef(), m_ZeroMask())))
7914 return false;
7915 Type *NewType = TLI->shouldConvertSplatType(SVI);
7916 if (!NewType)
7917 return false;
7918
7919 auto *SVIVecType = cast<FixedVectorType>(SVI->getType());
7920 assert(!NewType->isVectorTy() && "Expected a scalar type!");
7921 assert(NewType->getScalarSizeInBits() == SVIVecType->getScalarSizeInBits() &&
7922 "Expected a type of the same size!");
7923 auto *NewVecType =
7924 FixedVectorType::get(NewType, SVIVecType->getNumElements());
7925
7926 // Create a bitcast (shuffle (insert (bitcast(..))))
7927 IRBuilder<> Builder(SVI->getContext());
7928 Builder.SetInsertPoint(SVI);
7929 Value *BC1 = Builder.CreateBitCast(
7930 cast<Instruction>(SVI->getOperand(0))->getOperand(1), NewType);
7931 Value *Shuffle = Builder.CreateVectorSplat(NewVecType->getNumElements(), BC1);
7932 Value *BC2 = Builder.CreateBitCast(Shuffle, SVIVecType);
7933
7934 replaceAllUsesWith(SVI, BC2, FreshBBs, IsHugeFunc);
7936 SVI, TLInfo, nullptr,
7937 [&](Value *V) { removeAllAssertingVHReferences(V); });
7938
7939 // Also hoist the bitcast up to its operand if it they are not in the same
7940 // block.
7941 if (auto *BCI = dyn_cast<Instruction>(BC1))
7942 if (auto *Op = dyn_cast<Instruction>(BCI->getOperand(0)))
7943 if (BCI->getParent() != Op->getParent() && !isa<PHINode>(Op) &&
7944 !Op->isTerminator() && !Op->isEHPad())
7945 BCI->moveAfter(Op);
7946
7947 return true;
7948}
7949
7950bool CodeGenPrepare::tryToSinkFreeOperands(Instruction *I) {
7951 // If the operands of I can be folded into a target instruction together with
7952 // I, duplicate and sink them.
7953 SmallVector<Use *, 4> OpsToSink;
7954 if (!TTI->isProfitableToSinkOperands(I, OpsToSink))
7955 return false;
7956
7957 // OpsToSink can contain multiple uses in a use chain (e.g.
7958 // (%u1 with %u1 = shufflevector), (%u2 with %u2 = zext %u1)). The dominating
7959 // uses must come first, so we process the ops in reverse order so as to not
7960 // create invalid IR.
7961 BasicBlock *TargetBB = I->getParent();
7962 bool Changed = false;
7963 SmallVector<Use *, 4> ToReplace;
7964 Instruction *InsertPoint = I;
7965 for (Use *U : reverse(OpsToSink)) {
7966 auto *UI = cast<Instruction>(U->get());
7967 if (isa<PHINode>(UI) || UI->mayHaveSideEffects() || UI->mayReadFromMemory())
7968 continue;
7969 if (UI->getParent() == TargetBB) {
7970 if (UI->comesBefore(InsertPoint))
7971 InsertPoint = UI;
7972 continue;
7973 }
7974 ToReplace.push_back(U);
7975 }
7976
7977 SetVector<Instruction *> MaybeDead;
7978 DenseMap<Instruction *, Instruction *> NewInstructions;
7979 for (Use *U : ToReplace) {
7980 auto *UI = cast<Instruction>(U->get());
7981 Instruction *NI = UI->clone();
7982
7983 if (IsHugeFunc) {
7984 // Now we clone an instruction, its operands' defs may sink to this BB
7985 // now. So we put the operands defs' BBs into FreshBBs to do optimization.
7986 for (Value *Op : NI->operands())
7987 if (auto *OpDef = dyn_cast<Instruction>(Op))
7988 FreshBBs.insert(OpDef->getParent());
7989 }
7990
7991 NewInstructions[UI] = NI;
7992 MaybeDead.insert(UI);
7993 LLVM_DEBUG(dbgs() << "Sinking " << *UI << " to user " << *I << "\n");
7994 NI->insertBefore(InsertPoint->getIterator());
7995 InsertPoint = NI;
7996 InsertedInsts.insert(NI);
7997
7998 // Update the use for the new instruction, making sure that we update the
7999 // sunk instruction uses, if it is part of a chain that has already been
8000 // sunk.
8001 Instruction *OldI = cast<Instruction>(U->getUser());
8002 if (auto It = NewInstructions.find(OldI); It != NewInstructions.end())
8003 It->second->setOperand(U->getOperandNo(), NI);
8004 else
8005 U->set(NI);
8006 Changed = true;
8007 }
8008
8009 // Remove instructions that are dead after sinking.
8010 for (auto *I : MaybeDead) {
8011 if (!I->hasNUsesOrMore(1)) {
8012 LLVM_DEBUG(dbgs() << "Removing dead instruction: " << *I << "\n");
8013 I->eraseFromParent();
8014 }
8015 }
8016
8017 return Changed;
8018}
8019
8020bool CodeGenPrepare::optimizeSwitchType(SwitchInst *SI) {
8021 Value *Cond = SI->getCondition();
8022 Type *OldType = Cond->getType();
8023 LLVMContext &Context = Cond->getContext();
8024 EVT OldVT = TLI->getValueType(*DL, OldType);
8026 unsigned RegWidth = RegType.getSizeInBits();
8027
8028 if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
8029 return false;
8030
8031 // If the register width is greater than the type width, expand the condition
8032 // of the switch instruction and each case constant to the width of the
8033 // register. By widening the type of the switch condition, subsequent
8034 // comparisons (for case comparisons) will not need to be extended to the
8035 // preferred register width, so we will potentially eliminate N-1 extends,
8036 // where N is the number of cases in the switch.
8037 auto *NewType = Type::getIntNTy(Context, RegWidth);
8038
8039 // Extend the switch condition and case constants using the target preferred
8040 // extend unless the switch condition is a function argument with an extend
8041 // attribute. In that case, we can avoid an unnecessary mask/extension by
8042 // matching the argument extension instead.
8043 Instruction::CastOps ExtType = Instruction::ZExt;
8044 // Some targets prefer SExt over ZExt.
8045 if (TLI->isSExtCheaperThanZExt(OldVT, RegType))
8046 ExtType = Instruction::SExt;
8047
8048 if (auto *Arg = dyn_cast<Argument>(Cond)) {
8049 if (Arg->hasSExtAttr())
8050 ExtType = Instruction::SExt;
8051 if (Arg->hasZExtAttr())
8052 ExtType = Instruction::ZExt;
8053 }
8054
8055 auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
8056 ExtInst->insertBefore(SI->getIterator());
8057 ExtInst->setDebugLoc(SI->getDebugLoc());
8058 SI->setCondition(ExtInst);
8059 for (auto Case : SI->cases()) {
8060 const APInt &NarrowConst = Case.getCaseValue()->getValue();
8061 APInt WideConst = (ExtType == Instruction::ZExt)
8062 ? NarrowConst.zext(RegWidth)
8063 : NarrowConst.sext(RegWidth);
8064 Case.setValue(ConstantInt::get(Context, WideConst));
8065 }
8066
8067 return true;
8068}
8069
8070bool CodeGenPrepare::optimizeSwitchPhiConstants(SwitchInst *SI) {
8071 // The SCCP optimization tends to produce code like this:
8072 // switch(x) { case 42: phi(42, ...) }
8073 // Materializing the constant for the phi-argument needs instructions; So we
8074 // change the code to:
8075 // switch(x) { case 42: phi(x, ...) }
8076
8077 Value *Condition = SI->getCondition();
8078 // Avoid endless loop in degenerate case.
8079 if (isa<ConstantInt>(*Condition))
8080 return false;
8081
8082 bool Changed = false;
8083 BasicBlock *SwitchBB = SI->getParent();
8084 Type *ConditionType = Condition->getType();
8085
8086 for (const SwitchInst::CaseHandle &Case : SI->cases()) {
8087 ConstantInt *CaseValue = Case.getCaseValue();
8088 BasicBlock *CaseBB = Case.getCaseSuccessor();
8089 // Set to true if we previously checked that `CaseBB` is only reached by
8090 // a single case from this switch.
8091 bool CheckedForSinglePred = false;
8092 for (PHINode &PHI : CaseBB->phis()) {
8093 Type *PHIType = PHI.getType();
8094 // If ZExt is free then we can also catch patterns like this:
8095 // switch((i32)x) { case 42: phi((i64)42, ...); }
8096 // and replace `(i64)42` with `zext i32 %x to i64`.
8097 bool TryZExt =
8098 PHIType->isIntegerTy() &&
8099 PHIType->getIntegerBitWidth() > ConditionType->getIntegerBitWidth() &&
8100 TLI->isZExtFree(ConditionType, PHIType);
8101 if (PHIType == ConditionType || TryZExt) {
8102 // Set to true to skip this case because of multiple preds.
8103 bool SkipCase = false;
8104 Value *Replacement = nullptr;
8105 for (unsigned I = 0, E = PHI.getNumIncomingValues(); I != E; I++) {
8106 Value *PHIValue = PHI.getIncomingValue(I);
8107 if (PHIValue != CaseValue) {
8108 if (!TryZExt)
8109 continue;
8110 ConstantInt *PHIValueInt = dyn_cast<ConstantInt>(PHIValue);
8111 if (!PHIValueInt ||
8112 PHIValueInt->getValue() !=
8113 CaseValue->getValue().zext(PHIType->getIntegerBitWidth()))
8114 continue;
8115 }
8116 if (PHI.getIncomingBlock(I) != SwitchBB)
8117 continue;
8118 // We cannot optimize if there are multiple case labels jumping to
8119 // this block. This check may get expensive when there are many
8120 // case labels so we test for it last.
8121 if (!CheckedForSinglePred) {
8122 CheckedForSinglePred = true;
8123 if (SI->findCaseDest(CaseBB) == nullptr) {
8124 SkipCase = true;
8125 break;
8126 }
8127 }
8128
8129 if (Replacement == nullptr) {
8130 if (PHIValue == CaseValue) {
8131 Replacement = Condition;
8132 } else {
8133 IRBuilder<> Builder(SI);
8134 Replacement = Builder.CreateZExt(Condition, PHIType);
8135 }
8136 }
8137 PHI.setIncomingValue(I, Replacement);
8138 Changed = true;
8139 }
8140 if (SkipCase)
8141 break;
8142 }
8143 }
8144 }
8145 return Changed;
8146}
8147
8148bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
8149 bool Changed = optimizeSwitchType(SI);
8150 Changed |= optimizeSwitchPhiConstants(SI);
8151 return Changed;
8152}
8153
8154namespace {
8155
8156/// Helper class to promote a scalar operation to a vector one.
8157/// This class is used to move downward extractelement transition.
8158/// E.g.,
8159/// a = vector_op <2 x i32>
8160/// b = extractelement <2 x i32> a, i32 0
8161/// c = scalar_op b
8162/// store c
8163///
8164/// =>
8165/// a = vector_op <2 x i32>
8166/// c = vector_op a (equivalent to scalar_op on the related lane)
8167/// * d = extractelement <2 x i32> c, i32 0
8168/// * store d
8169/// Assuming both extractelement and store can be combine, we get rid of the
8170/// transition.
8171class VectorPromoteHelper {
8172 /// DataLayout associated with the current module.
8173 const DataLayout &DL;
8174
8175 /// Used to perform some checks on the legality of vector operations.
8176 const TargetLowering &TLI;
8177
8178 /// Used to estimated the cost of the promoted chain.
8179 const TargetTransformInfo &TTI;
8180
8181 /// The transition being moved downwards.
8182 Instruction *Transition;
8183
8184 /// The sequence of instructions to be promoted.
8185 SmallVector<Instruction *, 4> InstsToBePromoted;
8186
8187 /// Cost of combining a store and an extract.
8188 unsigned StoreExtractCombineCost;
8189
8190 /// Instruction that will be combined with the transition.
8191 Instruction *CombineInst = nullptr;
8192
8193 /// The instruction that represents the current end of the transition.
8194 /// Since we are faking the promotion until we reach the end of the chain
8195 /// of computation, we need a way to get the current end of the transition.
8196 Instruction *getEndOfTransition() const {
8197 if (InstsToBePromoted.empty())
8198 return Transition;
8199 return InstsToBePromoted.back();
8200 }
8201
8202 /// Return the index of the original value in the transition.
8203 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
8204 /// c, is at index 0.
8205 unsigned getTransitionOriginalValueIdx() const {
8206 assert(isa<ExtractElementInst>(Transition) &&
8207 "Other kind of transitions are not supported yet");
8208 return 0;
8209 }
8210
8211 /// Return the index of the index in the transition.
8212 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
8213 /// is at index 1.
8214 unsigned getTransitionIdx() const {
8215 assert(isa<ExtractElementInst>(Transition) &&
8216 "Other kind of transitions are not supported yet");
8217 return 1;
8218 }
8219
8220 /// Get the type of the transition.
8221 /// This is the type of the original value.
8222 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
8223 /// transition is <2 x i32>.
8224 Type *getTransitionType() const {
8225 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
8226 }
8227
8228 /// Promote \p ToBePromoted by moving \p Def downward through.
8229 /// I.e., we have the following sequence:
8230 /// Def = Transition <ty1> a to <ty2>
8231 /// b = ToBePromoted <ty2> Def, ...
8232 /// =>
8233 /// b = ToBePromoted <ty1> a, ...
8234 /// Def = Transition <ty1> ToBePromoted to <ty2>
8235 void promoteImpl(Instruction *ToBePromoted);
8236
8237 /// Check whether or not it is profitable to promote all the
8238 /// instructions enqueued to be promoted.
8239 bool isProfitableToPromote() {
8240 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
8241 unsigned Index = isa<ConstantInt>(ValIdx)
8242 ? cast<ConstantInt>(ValIdx)->getZExtValue()
8243 : -1;
8244 Type *PromotedType = getTransitionType();
8245
8246 StoreInst *ST = cast<StoreInst>(CombineInst);
8247 unsigned AS = ST->getPointerAddressSpace();
8248 // Check if this store is supported.
8250 TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
8251 ST->getAlign())) {
8252 // If this is not supported, there is no way we can combine
8253 // the extract with the store.
8254 return false;
8255 }
8256
8257 // The scalar chain of computation has to pay for the transition
8258 // scalar to vector.
8259 // The vector chain has to account for the combining cost.
8262 InstructionCost ScalarCost =
8263 TTI.getVectorInstrCost(*Transition, PromotedType, CostKind, Index);
8264 InstructionCost VectorCost = StoreExtractCombineCost;
8265 for (const auto &Inst : InstsToBePromoted) {
8266 // Compute the cost.
8267 // By construction, all instructions being promoted are arithmetic ones.
8268 // Moreover, one argument is a constant that can be viewed as a splat
8269 // constant.
8270 Value *Arg0 = Inst->getOperand(0);
8271 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
8272 isa<ConstantFP>(Arg0);
8273 TargetTransformInfo::OperandValueInfo Arg0Info, Arg1Info;
8274 if (IsArg0Constant)
8276 else
8278
8279 ScalarCost += TTI.getArithmeticInstrCost(
8280 Inst->getOpcode(), Inst->getType(), CostKind, Arg0Info, Arg1Info);
8281 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
8282 CostKind, Arg0Info, Arg1Info);
8283 }
8284 LLVM_DEBUG(
8285 dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
8286 << ScalarCost << "\nVector: " << VectorCost << '\n');
8287 return ScalarCost > VectorCost;
8288 }
8289
8290 /// Generate a constant vector with \p Val with the same
8291 /// number of elements as the transition.
8292 /// \p UseSplat defines whether or not \p Val should be replicated
8293 /// across the whole vector.
8294 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
8295 /// otherwise we generate a vector with as many poison as possible:
8296 /// <poison, ..., poison, Val, poison, ..., poison> where \p Val is only
8297 /// used at the index of the extract.
8298 Value *getConstantVector(Constant *Val, bool UseSplat) const {
8299 unsigned ExtractIdx = std::numeric_limits<unsigned>::max();
8300 if (!UseSplat) {
8301 // If we cannot determine where the constant must be, we have to
8302 // use a splat constant.
8303 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
8304 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
8305 ExtractIdx = CstVal->getSExtValue();
8306 else
8307 UseSplat = true;
8308 }
8309
8310 ElementCount EC = cast<VectorType>(getTransitionType())->getElementCount();
8311 if (UseSplat)
8312 return ConstantVector::getSplat(EC, Val);
8313
8314 if (!EC.isScalable()) {
8315 SmallVector<Constant *, 4> ConstVec;
8316 PoisonValue *PoisonVal = PoisonValue::get(Val->getType());
8317 for (unsigned Idx = 0; Idx != EC.getKnownMinValue(); ++Idx) {
8318 if (Idx == ExtractIdx)
8319 ConstVec.push_back(Val);
8320 else
8321 ConstVec.push_back(PoisonVal);
8322 }
8323 return ConstantVector::get(ConstVec);
8324 } else
8326 "Generate scalable vector for non-splat is unimplemented");
8327 }
8328
8329 /// Check if promoting to a vector type an operand at \p OperandIdx
8330 /// in \p Use can trigger undefined behavior.
8331 static bool canCauseUndefinedBehavior(const Instruction *Use,
8332 unsigned OperandIdx) {
8333 // This is not safe to introduce undef when the operand is on
8334 // the right hand side of a division-like instruction.
8335 if (OperandIdx != 1)
8336 return false;
8337 switch (Use->getOpcode()) {
8338 default:
8339 return false;
8340 case Instruction::SDiv:
8341 case Instruction::UDiv:
8342 case Instruction::SRem:
8343 case Instruction::URem:
8344 return true;
8345 case Instruction::FDiv:
8346 case Instruction::FRem:
8347 return !Use->hasNoNaNs();
8348 }
8349 llvm_unreachable(nullptr);
8350 }
8351
8352public:
8353 VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
8354 const TargetTransformInfo &TTI, Instruction *Transition,
8355 unsigned CombineCost)
8356 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
8357 StoreExtractCombineCost(CombineCost) {
8358 assert(Transition && "Do not know how to promote null");
8359 }
8360
8361 /// Check if we can promote \p ToBePromoted to \p Type.
8362 bool canPromote(const Instruction *ToBePromoted) const {
8363 // We could support CastInst too.
8364 return isa<BinaryOperator>(ToBePromoted);
8365 }
8366
8367 /// Check if it is profitable to promote \p ToBePromoted
8368 /// by moving downward the transition through.
8369 bool shouldPromote(const Instruction *ToBePromoted) const {
8370 // Promote only if all the operands can be statically expanded.
8371 // Indeed, we do not want to introduce any new kind of transitions.
8372 for (const Use &U : ToBePromoted->operands()) {
8373 const Value *Val = U.get();
8374 if (Val == getEndOfTransition()) {
8375 // If the use is a division and the transition is on the rhs,
8376 // we cannot promote the operation, otherwise we may create a
8377 // division by zero.
8378 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
8379 return false;
8380 continue;
8381 }
8382 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
8383 !isa<ConstantFP>(Val))
8384 return false;
8385 }
8386 // Check that the resulting operation is legal.
8387 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
8388 if (!ISDOpcode)
8389 return false;
8390 return StressStoreExtract ||
8392 ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
8393 }
8394
8395 /// Check whether or not \p Use can be combined
8396 /// with the transition.
8397 /// I.e., is it possible to do Use(Transition) => AnotherUse?
8398 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
8399
8400 /// Record \p ToBePromoted as part of the chain to be promoted.
8401 void enqueueForPromotion(Instruction *ToBePromoted) {
8402 InstsToBePromoted.push_back(ToBePromoted);
8403 }
8404
8405 /// Set the instruction that will be combined with the transition.
8406 void recordCombineInstruction(Instruction *ToBeCombined) {
8407 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
8408 CombineInst = ToBeCombined;
8409 }
8410
8411 /// Promote all the instructions enqueued for promotion if it is
8412 /// is profitable.
8413 /// \return True if the promotion happened, false otherwise.
8414 bool promote() {
8415 // Check if there is something to promote.
8416 // Right now, if we do not have anything to combine with,
8417 // we assume the promotion is not profitable.
8418 if (InstsToBePromoted.empty() || !CombineInst)
8419 return false;
8420
8421 // Check cost.
8422 if (!StressStoreExtract && !isProfitableToPromote())
8423 return false;
8424
8425 // Promote.
8426 for (auto &ToBePromoted : InstsToBePromoted)
8427 promoteImpl(ToBePromoted);
8428 InstsToBePromoted.clear();
8429 return true;
8430 }
8431};
8432
8433} // end anonymous namespace
8434
8435void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
8436 // At this point, we know that all the operands of ToBePromoted but Def
8437 // can be statically promoted.
8438 // For Def, we need to use its parameter in ToBePromoted:
8439 // b = ToBePromoted ty1 a
8440 // Def = Transition ty1 b to ty2
8441 // Move the transition down.
8442 // 1. Replace all uses of the promoted operation by the transition.
8443 // = ... b => = ... Def.
8444 assert(ToBePromoted->getType() == Transition->getType() &&
8445 "The type of the result of the transition does not match "
8446 "the final type");
8447 ToBePromoted->replaceAllUsesWith(Transition);
8448 // 2. Update the type of the uses.
8449 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
8450 Type *TransitionTy = getTransitionType();
8451 ToBePromoted->mutateType(TransitionTy);
8452 // 3. Update all the operands of the promoted operation with promoted
8453 // operands.
8454 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
8455 for (Use &U : ToBePromoted->operands()) {
8456 Value *Val = U.get();
8457 Value *NewVal = nullptr;
8458 if (Val == Transition)
8459 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
8460 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
8461 isa<ConstantFP>(Val)) {
8462 // Use a splat constant if it is not safe to use undef.
8463 NewVal = getConstantVector(
8464 cast<Constant>(Val),
8465 isa<UndefValue>(Val) ||
8466 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
8467 } else
8468 llvm_unreachable("Did you modified shouldPromote and forgot to update "
8469 "this?");
8470 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
8471 }
8472 Transition->moveAfter(ToBePromoted);
8473 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
8474}
8475
8476/// Some targets can do store(extractelement) with one instruction.
8477/// Try to push the extractelement towards the stores when the target
8478/// has this feature and this is profitable.
8479bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
8480 unsigned CombineCost = std::numeric_limits<unsigned>::max();
8481 if (DisableStoreExtract ||
8484 Inst->getOperand(1), CombineCost)))
8485 return false;
8486
8487 // At this point we know that Inst is a vector to scalar transition.
8488 // Try to move it down the def-use chain, until:
8489 // - We can combine the transition with its single use
8490 // => we got rid of the transition.
8491 // - We escape the current basic block
8492 // => we would need to check that we are moving it at a cheaper place and
8493 // we do not do that for now.
8494 BasicBlock *Parent = Inst->getParent();
8495 LLVM_DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
8496 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
8497 // If the transition has more than one use, assume this is not going to be
8498 // beneficial.
8499 while (Inst->hasOneUse()) {
8500 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
8501 LLVM_DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
8502
8503 if (ToBePromoted->getParent() != Parent) {
8504 LLVM_DEBUG(dbgs() << "Instruction to promote is in a different block ("
8505 << ToBePromoted->getParent()->getName()
8506 << ") than the transition (" << Parent->getName()
8507 << ").\n");
8508 return false;
8509 }
8510
8511 if (VPH.canCombine(ToBePromoted)) {
8512 LLVM_DEBUG(dbgs() << "Assume " << *Inst << '\n'
8513 << "will be combined with: " << *ToBePromoted << '\n');
8514 VPH.recordCombineInstruction(ToBePromoted);
8515 bool Changed = VPH.promote();
8516 NumStoreExtractExposed += Changed;
8517 return Changed;
8518 }
8519
8520 LLVM_DEBUG(dbgs() << "Try promoting.\n");
8521 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
8522 return false;
8523
8524 LLVM_DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
8525
8526 VPH.enqueueForPromotion(ToBePromoted);
8527 Inst = ToBePromoted;
8528 }
8529 return false;
8530}
8531
8532/// For the instruction sequence of store below, F and I values
8533/// are bundled together as an i64 value before being stored into memory.
8534/// Sometimes it is more efficient to generate separate stores for F and I,
8535/// which can remove the bitwise instructions or sink them to colder places.
8536///
8537/// (store (or (zext (bitcast F to i32) to i64),
8538/// (shl (zext I to i64), 32)), addr) -->
8539/// (store F, addr) and (store I, addr+4)
8540///
8541/// Similarly, splitting for other merged store can also be beneficial, like:
8542/// For pair of {i32, i32}, i64 store --> two i32 stores.
8543/// For pair of {i32, i16}, i64 store --> two i32 stores.
8544/// For pair of {i16, i16}, i32 store --> two i16 stores.
8545/// For pair of {i16, i8}, i32 store --> two i16 stores.
8546/// For pair of {i8, i8}, i16 store --> two i8 stores.
8547///
8548/// We allow each target to determine specifically which kind of splitting is
8549/// supported.
8550///
8551/// The store patterns are commonly seen from the simple code snippet below
8552/// if only std::make_pair(...) is sroa transformed before inlined into hoo.
8553/// void goo(const std::pair<int, float> &);
8554/// hoo() {
8555/// ...
8556/// goo(std::make_pair(tmp, ftmp));
8557/// ...
8558/// }
8559///
8560/// Although we already have similar splitting in DAG Combine, we duplicate
8561/// it in CodeGenPrepare to catch the case in which pattern is across
8562/// multiple BBs. The logic in DAG Combine is kept to catch case generated
8563/// during code expansion.
8565 const TargetLowering &TLI) {
8566 // Handle simple but common cases only.
8567 Type *StoreType = SI.getValueOperand()->getType();
8568
8569 // The code below assumes shifting a value by <number of bits>,
8570 // whereas scalable vectors would have to be shifted by
8571 // <2log(vscale) + number of bits> in order to store the
8572 // low/high parts. Bailing out for now.
8573 if (StoreType->isScalableTy())
8574 return false;
8575
8576 if (!DL.typeSizeEqualsStoreSize(StoreType) ||
8577 DL.getTypeSizeInBits(StoreType) == 0)
8578 return false;
8579
8580 unsigned HalfValBitSize = DL.getTypeSizeInBits(StoreType) / 2;
8581 Type *SplitStoreType = Type::getIntNTy(SI.getContext(), HalfValBitSize);
8582 if (!DL.typeSizeEqualsStoreSize(SplitStoreType))
8583 return false;
8584
8585 // Don't split the store if it is volatile or atomic.
8586 if (!SI.isSimple())
8587 return false;
8588
8589 // Match the following patterns:
8590 // (store (or (zext LValue to i64),
8591 // (shl (zext HValue to i64), 32)), HalfValBitSize)
8592 // or
8593 // (store (or (shl (zext HValue to i64), 32)), HalfValBitSize)
8594 // (zext LValue to i64),
8595 // Expect both operands of OR and the first operand of SHL have only
8596 // one use.
8597 Value *LValue, *HValue;
8598 if (!match(SI.getValueOperand(),
8601 m_SpecificInt(HalfValBitSize))))))
8602 return false;
8603
8604 // Check LValue and HValue are int with size less or equal than 32.
8605 if (!LValue->getType()->isIntegerTy() ||
8606 DL.getTypeSizeInBits(LValue->getType()) > HalfValBitSize ||
8607 !HValue->getType()->isIntegerTy() ||
8608 DL.getTypeSizeInBits(HValue->getType()) > HalfValBitSize)
8609 return false;
8610
8611 // If LValue/HValue is a bitcast instruction, use the EVT before bitcast
8612 // as the input of target query.
8613 auto *LBC = dyn_cast<BitCastInst>(LValue);
8614 auto *HBC = dyn_cast<BitCastInst>(HValue);
8615 EVT LowTy = LBC ? EVT::getEVT(LBC->getOperand(0)->getType())
8616 : EVT::getEVT(LValue->getType());
8617 EVT HighTy = HBC ? EVT::getEVT(HBC->getOperand(0)->getType())
8618 : EVT::getEVT(HValue->getType());
8619 if (!ForceSplitStore && !TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
8620 return false;
8621
8622 // Start to split store.
8623 IRBuilder<> Builder(SI.getContext());
8624 Builder.SetInsertPoint(&SI);
8625
8626 // If LValue/HValue is a bitcast in another BB, create a new one in current
8627 // BB so it may be merged with the splitted stores by dag combiner.
8628 if (LBC && LBC->getParent() != SI.getParent())
8629 LValue = Builder.CreateBitCast(LBC->getOperand(0), LBC->getType());
8630 if (HBC && HBC->getParent() != SI.getParent())
8631 HValue = Builder.CreateBitCast(HBC->getOperand(0), HBC->getType());
8632
8633 bool IsLE = SI.getDataLayout().isLittleEndian();
8634 auto CreateSplitStore = [&](Value *V, bool Upper) {
8635 V = Builder.CreateZExtOrBitCast(V, SplitStoreType);
8636 Value *Addr = SI.getPointerOperand();
8637 Align Alignment = SI.getAlign();
8638 const bool IsOffsetStore = (IsLE && Upper) || (!IsLE && !Upper);
8639 if (IsOffsetStore) {
8640 Addr = Builder.CreateGEP(
8641 SplitStoreType, Addr,
8642 ConstantInt::get(Type::getInt32Ty(SI.getContext()), 1));
8643
8644 // When splitting the store in half, naturally one half will retain the
8645 // alignment of the original wider store, regardless of whether it was
8646 // over-aligned or not, while the other will require adjustment.
8647 Alignment = commonAlignment(Alignment, HalfValBitSize / 8);
8648 }
8649 Builder.CreateAlignedStore(V, Addr, Alignment);
8650 };
8651
8652 CreateSplitStore(LValue, false);
8653 CreateSplitStore(HValue, true);
8654
8655 // Delete the old store.
8656 SI.eraseFromParent();
8657 return true;
8658}
8659
8660// Return true if the GEP has two operands, the first operand is of a sequential
8661// type, and the second operand is a constant.
8664 return GEP->getNumOperands() == 2 && I.isSequential() &&
8665 isa<ConstantInt>(GEP->getOperand(1));
8666}
8667
8668// Try unmerging GEPs to reduce liveness interference (register pressure) across
8669// IndirectBr edges. Since IndirectBr edges tend to touch on many blocks,
8670// reducing liveness interference across those edges benefits global register
8671// allocation. Currently handles only certain cases.
8672//
8673// For example, unmerge %GEPI and %UGEPI as below.
8674//
8675// ---------- BEFORE ----------
8676// SrcBlock:
8677// ...
8678// %GEPIOp = ...
8679// ...
8680// %GEPI = gep %GEPIOp, Idx
8681// ...
8682// indirectbr ... [ label %DstB0, label %DstB1, ... label %DstBi ... ]
8683// (* %GEPI is alive on the indirectbr edges due to other uses ahead)
8684// (* %GEPIOp is alive on the indirectbr edges only because of it's used by
8685// %UGEPI)
8686//
8687// DstB0: ... (there may be a gep similar to %UGEPI to be unmerged)
8688// DstB1: ... (there may be a gep similar to %UGEPI to be unmerged)
8689// ...
8690//
8691// DstBi:
8692// ...
8693// %UGEPI = gep %GEPIOp, UIdx
8694// ...
8695// ---------------------------
8696//
8697// ---------- AFTER ----------
8698// SrcBlock:
8699// ... (same as above)
8700// (* %GEPI is still alive on the indirectbr edges)
8701// (* %GEPIOp is no longer alive on the indirectbr edges as a result of the
8702// unmerging)
8703// ...
8704//
8705// DstBi:
8706// ...
8707// %UGEPI = gep %GEPI, (UIdx-Idx)
8708// ...
8709// ---------------------------
8710//
8711// The register pressure on the IndirectBr edges is reduced because %GEPIOp is
8712// no longer alive on them.
8713//
8714// We try to unmerge GEPs here in CodGenPrepare, as opposed to limiting merging
8715// of GEPs in the first place in InstCombiner::visitGetElementPtrInst() so as
8716// not to disable further simplications and optimizations as a result of GEP
8717// merging.
8718//
8719// Note this unmerging may increase the length of the data flow critical path
8720// (the path from %GEPIOp to %UGEPI would go through %GEPI), which is a tradeoff
8721// between the register pressure and the length of data-flow critical
8722// path. Restricting this to the uncommon IndirectBr case would minimize the
8723// impact of potentially longer critical path, if any, and the impact on compile
8724// time.
8726 const TargetTransformInfo *TTI) {
8727 BasicBlock *SrcBlock = GEPI->getParent();
8728 // Check that SrcBlock ends with an IndirectBr. If not, give up. The common
8729 // (non-IndirectBr) cases exit early here.
8730 if (!isa<IndirectBrInst>(SrcBlock->getTerminator()))
8731 return false;
8732 // Check that GEPI is a simple gep with a single constant index.
8733 if (!GEPSequentialConstIndexed(GEPI))
8734 return false;
8735 ConstantInt *GEPIIdx = cast<ConstantInt>(GEPI->getOperand(1));
8736 // Check that GEPI is a cheap one.
8737 if (TTI->getIntImmCost(GEPIIdx->getValue(), GEPIIdx->getType(),
8740 return false;
8741 Value *GEPIOp = GEPI->getOperand(0);
8742 // Check that GEPIOp is an instruction that's also defined in SrcBlock.
8743 if (!isa<Instruction>(GEPIOp))
8744 return false;
8745 auto *GEPIOpI = cast<Instruction>(GEPIOp);
8746 if (GEPIOpI->getParent() != SrcBlock)
8747 return false;
8748 // Check that GEP is used outside the block, meaning it's alive on the
8749 // IndirectBr edge(s).
8750 if (llvm::none_of(GEPI->users(), [&](User *Usr) {
8751 if (auto *I = dyn_cast<Instruction>(Usr)) {
8752 if (I->getParent() != SrcBlock) {
8753 return true;
8754 }
8755 }
8756 return false;
8757 }))
8758 return false;
8759 // The second elements of the GEP chains to be unmerged.
8760 std::vector<GetElementPtrInst *> UGEPIs;
8761 // Check each user of GEPIOp to check if unmerging would make GEPIOp not alive
8762 // on IndirectBr edges.
8763 for (User *Usr : GEPIOp->users()) {
8764 if (Usr == GEPI)
8765 continue;
8766 // Check if Usr is an Instruction. If not, give up.
8767 if (!isa<Instruction>(Usr))
8768 return false;
8769 auto *UI = cast<Instruction>(Usr);
8770 // Check if Usr in the same block as GEPIOp, which is fine, skip.
8771 if (UI->getParent() == SrcBlock)
8772 continue;
8773 // Check if Usr is a GEP. If not, give up.
8774 if (!isa<GetElementPtrInst>(Usr))
8775 return false;
8776 auto *UGEPI = cast<GetElementPtrInst>(Usr);
8777 // Check if UGEPI is a simple gep with a single constant index and GEPIOp is
8778 // the pointer operand to it. If so, record it in the vector. If not, give
8779 // up.
8780 if (!GEPSequentialConstIndexed(UGEPI))
8781 return false;
8782 if (UGEPI->getOperand(0) != GEPIOp)
8783 return false;
8784 if (UGEPI->getSourceElementType() != GEPI->getSourceElementType())
8785 return false;
8786 if (GEPIIdx->getType() !=
8787 cast<ConstantInt>(UGEPI->getOperand(1))->getType())
8788 return false;
8789 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
8790 if (TTI->getIntImmCost(UGEPIIdx->getValue(), UGEPIIdx->getType(),
8793 return false;
8794 UGEPIs.push_back(UGEPI);
8795 }
8796 if (UGEPIs.size() == 0)
8797 return false;
8798 // Check the materializing cost of (Uidx-Idx).
8799 for (GetElementPtrInst *UGEPI : UGEPIs) {
8800 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
8801 APInt NewIdx = UGEPIIdx->getValue() - GEPIIdx->getValue();
8803 NewIdx, GEPIIdx->getType(), TargetTransformInfo::TCK_SizeAndLatency);
8804 if (ImmCost > TargetTransformInfo::TCC_Basic)
8805 return false;
8806 }
8807 // Now unmerge between GEPI and UGEPIs.
8808 for (GetElementPtrInst *UGEPI : UGEPIs) {
8809 UGEPI->setOperand(0, GEPI);
8810 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
8811 auto NewIdx = UGEPIIdx->getValue() - GEPIIdx->getValue();
8812 Constant *NewUGEPIIdx = ConstantInt::get(GEPIIdx->getType(), NewIdx);
8813 UGEPI->setOperand(1, NewUGEPIIdx);
8814
8815 auto SourceFlags = GEPI->getNoWrapFlags();
8816 // Intersect flags to avoid UB in updated GEP.
8817 auto TargetFlags =
8818 UGEPI->getNoWrapFlags().intersectForOffsetAdd(SourceFlags);
8819 // If UGEPI now has a negative index, drop the nuw flag.
8820 if (NewIdx.isNegative() && TargetFlags.hasNoUnsignedWrap())
8821 TargetFlags = TargetFlags.withoutNoUnsignedWrap();
8822 UGEPI->setNoWrapFlags(TargetFlags);
8823 }
8824 // After unmerging, verify that GEPIOp is actually only used in SrcBlock (not
8825 // alive on IndirectBr edges).
8826 assert(llvm::none_of(GEPIOp->users(),
8827 [&](User *Usr) {
8828 return cast<Instruction>(Usr)->getParent() != SrcBlock;
8829 }) &&
8830 "GEPIOp is used outside SrcBlock");
8831 return true;
8832}
8833
8834static bool optimizeBranch(CondBrInst *Branch, const TargetLowering &TLI,
8836 bool IsHugeFunc) {
8837 // Try and convert
8838 // %c = icmp ult %x, 8
8839 // br %c, bla, blb
8840 // %tc = lshr %x, 3
8841 // to
8842 // %tc = lshr %x, 3
8843 // %c = icmp eq %tc, 0
8844 // br %c, bla, blb
8845 // Creating the cmp to zero can be better for the backend, especially if the
8846 // lshr produces flags that can be used automatically.
8847 if (!TLI.preferZeroCompareBranch())
8848 return false;
8849
8850 ICmpInst *Cmp = dyn_cast<ICmpInst>(Branch->getCondition());
8851 if (!Cmp || !isa<ConstantInt>(Cmp->getOperand(1)) || !Cmp->hasOneUse())
8852 return false;
8853
8854 Value *X = Cmp->getOperand(0);
8855 if (!X->hasUseList())
8856 return false;
8857
8858 APInt CmpC = cast<ConstantInt>(Cmp->getOperand(1))->getValue();
8859
8860 for (auto *U : X->users()) {
8862 // A quick dominance check
8863 if (!UI ||
8864 (UI->getParent() != Branch->getParent() &&
8865 UI->getParent() != Branch->getSuccessor(0) &&
8866 UI->getParent() != Branch->getSuccessor(1)) ||
8867 (UI->getParent() != Branch->getParent() &&
8868 !UI->getParent()->getSinglePredecessor()))
8869 continue;
8870
8871 if (CmpC.isPowerOf2() && Cmp->getPredicate() == ICmpInst::ICMP_ULT &&
8872 match(UI, m_Shr(m_Specific(X), m_SpecificInt(CmpC.logBase2())))) {
8873 IRBuilder<> Builder(Branch);
8874 if (UI->getParent() != Branch->getParent())
8875 UI->moveBefore(Branch->getIterator());
8877 Value *NewCmp = Builder.CreateCmp(ICmpInst::ICMP_EQ, UI,
8878 ConstantInt::get(UI->getType(), 0));
8879 LLVM_DEBUG(dbgs() << "Converting " << *Cmp << "\n");
8880 LLVM_DEBUG(dbgs() << " to compare on zero: " << *NewCmp << "\n");
8881 replaceAllUsesWith(Cmp, NewCmp, FreshBBs, IsHugeFunc);
8882 return true;
8883 }
8884 if (Cmp->isEquality() &&
8885 (match(UI, m_Add(m_Specific(X), m_SpecificInt(-CmpC))) ||
8886 match(UI, m_Sub(m_Specific(X), m_SpecificInt(CmpC))) ||
8887 match(UI, m_Xor(m_Specific(X), m_SpecificInt(CmpC))))) {
8888 IRBuilder<> Builder(Branch);
8889 if (UI->getParent() != Branch->getParent())
8890 UI->moveBefore(Branch->getIterator());
8892 Value *NewCmp = Builder.CreateCmp(Cmp->getPredicate(), 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 }
8900 return false;
8901}
8902
8903bool CodeGenPrepare::optimizeInst(Instruction *I, ModifyDT &ModifiedDT) {
8904 bool AnyChange = false;
8905 AnyChange = fixupDbgVariableRecordsOnInst(*I);
8906
8907 // Bail out if we inserted the instruction to prevent optimizations from
8908 // stepping on each other's toes.
8909 if (InsertedInsts.count(I))
8910 return AnyChange;
8911
8912 // TODO: Move into the switch on opcode below here.
8913 if (PHINode *P = dyn_cast<PHINode>(I)) {
8914 // It is possible for very late stage optimizations (such as SimplifyCFG)
8915 // to introduce PHI nodes too late to be cleaned up. If we detect such a
8916 // trivial PHI, go ahead and zap it here.
8917 if (Value *V = simplifyInstruction(P, {*DL, TLInfo})) {
8918 LargeOffsetGEPMap.erase(P);
8919 replaceAllUsesWith(P, V, FreshBBs, IsHugeFunc);
8920 P->eraseFromParent();
8921 ++NumPHIsElim;
8922 return true;
8923 }
8924 return AnyChange;
8925 }
8926
8927 if (CastInst *CI = dyn_cast<CastInst>(I)) {
8928 // If the source of the cast is a constant, then this should have
8929 // already been constant folded. The only reason NOT to constant fold
8930 // it is if something (e.g. LSR) was careful to place the constant
8931 // evaluation in a block other than then one that uses it (e.g. to hoist
8932 // the address of globals out of a loop). If this is the case, we don't
8933 // want to forward-subst the cast.
8934 if (isa<Constant>(CI->getOperand(0)))
8935 return AnyChange;
8936
8937 if (OptimizeNoopCopyExpression(CI, *TLI, *DL))
8938 return true;
8939
8941 isa<TruncInst>(I)) &&
8943 I, LI->getLoopFor(I->getParent()), *TTI))
8944 return true;
8945
8946 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
8947 /// Sink a zext or sext into its user blocks if the target type doesn't
8948 /// fit in one register
8949 if (TLI->getTypeAction(CI->getContext(),
8950 TLI->getValueType(*DL, CI->getType())) ==
8951 TargetLowering::TypeExpandInteger) {
8952 return SinkCast(CI);
8953 } else {
8955 I, LI->getLoopFor(I->getParent()), *TTI))
8956 return true;
8957
8958 bool MadeChange = optimizeExt(I);
8959 return MadeChange | optimizeExtUses(I);
8960 }
8961 }
8962 return AnyChange;
8963 }
8964
8965 if (auto *Cmp = dyn_cast<CmpInst>(I))
8966 if (optimizeCmp(Cmp, ModifiedDT))
8967 return true;
8968
8969 if (match(I, m_URem(m_Value(), m_Value())))
8970 if (optimizeURem(I))
8971 return true;
8972
8973 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
8974 LI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
8975 bool Modified = optimizeLoadExt(LI);
8976 unsigned AS = LI->getPointerAddressSpace();
8977 Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
8978 return Modified;
8979 }
8980
8981 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
8982 if (splitMergedValStore(*SI, *DL, *TLI))
8983 return true;
8984 SI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
8985 unsigned AS = SI->getPointerAddressSpace();
8986 return optimizeMemoryInst(I, SI->getOperand(1),
8987 SI->getOperand(0)->getType(), AS);
8988 }
8989
8990 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
8991 unsigned AS = RMW->getPointerAddressSpace();
8992 return optimizeMemoryInst(I, RMW->getPointerOperand(), RMW->getType(), AS);
8993 }
8994
8995 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(I)) {
8996 unsigned AS = CmpX->getPointerAddressSpace();
8997 return optimizeMemoryInst(I, CmpX->getPointerOperand(),
8998 CmpX->getCompareOperand()->getType(), AS);
8999 }
9000
9001 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
9002
9003 if (BinOp && BinOp->getOpcode() == Instruction::And && EnableAndCmpSinking &&
9004 sinkAndCmp0Expression(BinOp, *TLI, InsertedInsts))
9005 return true;
9006
9007 // TODO: Move this into the switch on opcode - it handles shifts already.
9008 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
9009 BinOp->getOpcode() == Instruction::LShr)) {
9010 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
9011 if (CI && TLI->hasExtractBitsInsn())
9012 if (OptimizeExtractBits(BinOp, CI, *TLI, *DL))
9013 return true;
9014 }
9015
9016 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
9017 if (GEPI->hasAllZeroIndices()) {
9018 /// The GEP operand must be a pointer, so must its result -> BitCast
9019 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
9020 GEPI->getName(), GEPI->getIterator());
9021 NC->setDebugLoc(GEPI->getDebugLoc());
9022 replaceAllUsesWith(GEPI, NC, FreshBBs, IsHugeFunc);
9024 GEPI, TLInfo, nullptr,
9025 [&](Value *V) { removeAllAssertingVHReferences(V); });
9026 ++NumGEPsElim;
9027 optimizeInst(NC, ModifiedDT);
9028 return true;
9029 }
9031 return true;
9032 }
9033 }
9034
9035 if (FreezeInst *FI = dyn_cast<FreezeInst>(I)) {
9036 // freeze(icmp a, const)) -> icmp (freeze a), const
9037 // This helps generate efficient conditional jumps.
9038 Instruction *CmpI = nullptr;
9039 if (ICmpInst *II = dyn_cast<ICmpInst>(FI->getOperand(0)))
9040 CmpI = II;
9041 else if (FCmpInst *F = dyn_cast<FCmpInst>(FI->getOperand(0)))
9042 CmpI = F->getFastMathFlags().none() ? F : nullptr;
9043
9044 if (CmpI && CmpI->hasOneUse()) {
9045 auto Op0 = CmpI->getOperand(0), Op1 = CmpI->getOperand(1);
9046 bool Const0 = isa<ConstantInt>(Op0) || isa<ConstantFP>(Op0) ||
9048 bool Const1 = isa<ConstantInt>(Op1) || isa<ConstantFP>(Op1) ||
9050 if (Const0 || Const1) {
9051 if (!Const0 || !Const1) {
9052 auto *F = new FreezeInst(Const0 ? Op1 : Op0, "", CmpI->getIterator());
9053 F->takeName(FI);
9054 CmpI->setOperand(Const0 ? 1 : 0, F);
9055 }
9056 replaceAllUsesWith(FI, CmpI, FreshBBs, IsHugeFunc);
9057 FI->eraseFromParent();
9058 return true;
9059 }
9060 }
9061 return AnyChange;
9062 }
9063
9064 if (tryToSinkFreeOperands(I))
9065 return true;
9066
9067 switch (I->getOpcode()) {
9068 case Instruction::Shl:
9069 case Instruction::LShr:
9070 case Instruction::AShr:
9071 return optimizeShiftInst(cast<BinaryOperator>(I));
9072 case Instruction::Call:
9073 return optimizeCallInst(cast<CallInst>(I), ModifiedDT);
9074 case Instruction::Select:
9075 return optimizeSelectInst(cast<SelectInst>(I));
9076 case Instruction::ShuffleVector:
9077 return optimizeShuffleVectorInst(cast<ShuffleVectorInst>(I));
9078 case Instruction::Switch:
9079 return optimizeSwitchInst(cast<SwitchInst>(I));
9080 case Instruction::ExtractElement:
9081 return optimizeExtractElementInst(cast<ExtractElementInst>(I));
9082 case Instruction::CondBr:
9083 return optimizeBranch(cast<CondBrInst>(I), *TLI, FreshBBs, IsHugeFunc);
9084 }
9085
9086 return AnyChange;
9087}
9088
9089/// Given an OR instruction, check to see if this is a bitreverse
9090/// idiom. If so, insert the new intrinsic and return true.
9091bool CodeGenPrepare::makeBitReverse(Instruction &I) {
9092 if (!I.getType()->isIntegerTy() ||
9094 TLI->getValueType(*DL, I.getType(), true)))
9095 return false;
9096
9097 SmallVector<Instruction *, 4> Insts;
9098 if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts))
9099 return false;
9100 Instruction *LastInst = Insts.back();
9101 replaceAllUsesWith(&I, LastInst, FreshBBs, IsHugeFunc);
9103 &I, TLInfo, nullptr,
9104 [&](Value *V) { removeAllAssertingVHReferences(V); });
9105 return true;
9106}
9107
9108// In this pass we look for GEP and cast instructions that are used
9109// across basic blocks and rewrite them to improve basic-block-at-a-time
9110// selection.
9111bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, ModifyDT &ModifiedDT) {
9112 SunkAddrs.clear();
9113 bool MadeChange = false;
9114
9115 do {
9116 CurInstIterator = BB.begin();
9117 ModifiedDT = ModifyDT::NotModifyDT;
9118 while (CurInstIterator != BB.end()) {
9119 MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
9120 if (ModifiedDT != ModifyDT::NotModifyDT) {
9121 // For huge function we tend to quickly go though the inner optmization
9122 // opportunities in the BB. So we go back to the BB head to re-optimize
9123 // each instruction instead of go back to the function head.
9124 if (IsHugeFunc)
9125 break;
9126 return true;
9127 }
9128 }
9129 } while (ModifiedDT == ModifyDT::ModifyInstDT);
9130
9131 bool MadeBitReverse = true;
9132 while (MadeBitReverse) {
9133 MadeBitReverse = false;
9134 for (auto &I : reverse(BB)) {
9135 if (makeBitReverse(I)) {
9136 MadeBitReverse = MadeChange = true;
9137 break;
9138 }
9139 }
9140 }
9141 MadeChange |= dupRetToEnableTailCallOpts(&BB, ModifiedDT);
9142
9143 return MadeChange;
9144}
9145
9146bool CodeGenPrepare::fixupDbgVariableRecordsOnInst(Instruction &I) {
9147 bool AnyChange = false;
9148 for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange()))
9149 AnyChange |= fixupDbgVariableRecord(DVR);
9150 return AnyChange;
9151}
9152
9153// FIXME: should updating debug-info really cause the "changed" flag to fire,
9154// which can cause a function to be reprocessed?
9155bool CodeGenPrepare::fixupDbgVariableRecord(DbgVariableRecord &DVR) {
9156 if (DVR.Type != DbgVariableRecord::LocationType::Value &&
9157 DVR.Type != DbgVariableRecord::LocationType::Assign)
9158 return false;
9159
9160 // Does this DbgVariableRecord refer to a sunk address calculation?
9161 bool AnyChange = false;
9162 SmallDenseSet<Value *> LocationOps(DVR.location_ops().begin(),
9163 DVR.location_ops().end());
9164 for (Value *Location : LocationOps) {
9165 WeakTrackingVH SunkAddrVH = SunkAddrs[Location];
9166 Value *SunkAddr = SunkAddrVH.pointsToAliveValue() ? SunkAddrVH : nullptr;
9167 if (SunkAddr) {
9168 // Point dbg.value at locally computed address, which should give the best
9169 // opportunity to be accurately lowered. This update may change the type
9170 // of pointer being referred to; however this makes no difference to
9171 // debugging information, and we can't generate bitcasts that may affect
9172 // codegen.
9173 DVR.replaceVariableLocationOp(Location, SunkAddr);
9174 AnyChange = true;
9175 }
9176 }
9177 return AnyChange;
9178}
9179
9181 DVR->removeFromParent();
9182 BasicBlock *VIBB = VI->getParent();
9183 if (isa<PHINode>(VI))
9184 VIBB->insertDbgRecordBefore(DVR, VIBB->getFirstInsertionPt());
9185 else
9186 VIBB->insertDbgRecordAfter(DVR, &*VI);
9187}
9188
9189// A llvm.dbg.value may be using a value before its definition, due to
9190// optimizations in this pass and others. Scan for such dbg.values, and rescue
9191// them by moving the dbg.value to immediately after the value definition.
9192// FIXME: Ideally this should never be necessary, and this has the potential
9193// to re-order dbg.value intrinsics.
9194bool CodeGenPrepare::placeDbgValues(Function &F) {
9195 bool MadeChange = false;
9196 DominatorTree &DT = getDT();
9197
9198 auto DbgProcessor = [&](auto *DbgItem, Instruction *Position) {
9199 SmallVector<Instruction *, 4> VIs;
9200 for (Value *V : DbgItem->location_ops())
9201 if (Instruction *VI = dyn_cast_or_null<Instruction>(V))
9202 VIs.push_back(VI);
9203
9204 // This item may depend on multiple instructions, complicating any
9205 // potential sink. This block takes the defensive approach, opting to
9206 // "undef" the item if it has more than one instruction and any of them do
9207 // not dominate iem.
9208 for (Instruction *VI : VIs) {
9209 if (VI->isTerminator())
9210 continue;
9211
9212 // If VI is a phi in a block with an EHPad terminator, we can't insert
9213 // after it.
9214 if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
9215 continue;
9216
9217 // If the defining instruction dominates the dbg.value, we do not need
9218 // to move the dbg.value.
9219 if (DT.dominates(VI, Position))
9220 continue;
9221
9222 // If we depend on multiple instructions and any of them doesn't
9223 // dominate this DVI, we probably can't salvage it: moving it to
9224 // after any of the instructions could cause us to lose the others.
9225 if (VIs.size() > 1) {
9226 LLVM_DEBUG(
9227 dbgs()
9228 << "Unable to find valid location for Debug Value, undefing:\n"
9229 << *DbgItem);
9230 DbgItem->setKillLocation();
9231 break;
9232 }
9233
9234 LLVM_DEBUG(dbgs() << "Moving Debug Value before :\n"
9235 << *DbgItem << ' ' << *VI);
9236 DbgInserterHelper(DbgItem, VI->getIterator());
9237 MadeChange = true;
9238 ++NumDbgValueMoved;
9239 }
9240 };
9241
9242 for (BasicBlock &BB : F) {
9243 for (Instruction &Insn : llvm::make_early_inc_range(BB)) {
9244 // Process any DbgVariableRecord records attached to this
9245 // instruction.
9246 for (DbgVariableRecord &DVR : llvm::make_early_inc_range(
9247 filterDbgVars(Insn.getDbgRecordRange()))) {
9248 if (DVR.Type != DbgVariableRecord::LocationType::Value)
9249 continue;
9250 DbgProcessor(&DVR, &Insn);
9251 }
9252 }
9253 }
9254
9255 return MadeChange;
9256}
9257
9258// Group scattered pseudo probes in a block to favor SelectionDAG. Scattered
9259// probes can be chained dependencies of other regular DAG nodes and block DAG
9260// combine optimizations.
9261bool CodeGenPrepare::placePseudoProbes(Function &F) {
9262 bool MadeChange = false;
9263 for (auto &Block : F) {
9264 // Move the rest probes to the beginning of the block.
9265 auto FirstInst = Block.getFirstInsertionPt();
9266 while (FirstInst != Block.end() && FirstInst->isDebugOrPseudoInst())
9267 ++FirstInst;
9268 BasicBlock::iterator I(FirstInst);
9269 I++;
9270 while (I != Block.end()) {
9271 if (auto *II = dyn_cast<PseudoProbeInst>(I++)) {
9272 II->moveBefore(FirstInst);
9273 MadeChange = true;
9274 }
9275 }
9276 }
9277 return MadeChange;
9278}
9279
9280/// Some targets prefer to split a conditional branch like:
9281/// \code
9282/// %0 = icmp ne i32 %a, 0
9283/// %1 = icmp ne i32 %b, 0
9284/// %or.cond = or i1 %0, %1
9285/// br i1 %or.cond, label %TrueBB, label %FalseBB
9286/// \endcode
9287/// into multiple branch instructions like:
9288/// \code
9289/// bb1:
9290/// %0 = icmp ne i32 %a, 0
9291/// br i1 %0, label %TrueBB, label %bb2
9292/// bb2:
9293/// %1 = icmp ne i32 %b, 0
9294/// br i1 %1, label %TrueBB, label %FalseBB
9295/// \endcode
9296/// This usually allows instruction selection to do even further optimizations
9297/// and combine the compare with the branch instruction. Currently this is
9298/// applied for targets which have "cheap" jump instructions.
9299///
9300/// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
9301///
9302bool CodeGenPrepare::splitBranchCondition(Function &F) {
9303 if (!TM->Options.EnableFastISel || TLI->isJumpExpensive())
9304 return false;
9305
9306 bool MadeChange = false;
9307 for (auto &BB : F) {
9308 // Does this BB end with the following?
9309 // %cond1 = icmp|fcmp|binary instruction ...
9310 // %cond2 = icmp|fcmp|binary instruction ...
9311 // %cond.or = or|and i1 %cond1, cond2
9312 // br i1 %cond.or label %dest1, label %dest2"
9313 Instruction *LogicOp;
9314 BasicBlock *TBB, *FBB;
9315 if (!match(BB.getTerminator(),
9316 m_Br(m_OneUse(m_Instruction(LogicOp)), TBB, FBB)))
9317 continue;
9318
9319 auto *Br1 = cast<CondBrInst>(BB.getTerminator());
9320 if (Br1->getMetadata(LLVMContext::MD_unpredictable))
9321 continue;
9322
9323 // The merging of mostly empty BB can cause a degenerate branch.
9324 if (TBB == FBB)
9325 continue;
9326
9327 unsigned Opc;
9328 Value *Cond1, *Cond2;
9329 if (match(LogicOp,
9330 m_LogicalAnd(m_OneUse(m_Value(Cond1)), m_OneUse(m_Value(Cond2)))))
9331 Opc = Instruction::And;
9332 else if (match(LogicOp, m_LogicalOr(m_OneUse(m_Value(Cond1)),
9333 m_OneUse(m_Value(Cond2)))))
9334 Opc = Instruction::Or;
9335 else
9336 continue;
9337
9338 auto IsGoodCond = [](Value *Cond) {
9339 return match(
9340 Cond,
9342 m_LogicalOr(m_Value(), m_Value()))));
9343 };
9344 if (!IsGoodCond(Cond1) || !IsGoodCond(Cond2))
9345 continue;
9346
9347 LLVM_DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
9348
9349 // Create a new BB.
9350 auto *TmpBB =
9351 BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split",
9352 BB.getParent(), BB.getNextNode());
9353 if (IsHugeFunc)
9354 FreshBBs.insert(TmpBB);
9355
9356 // Update original basic block by using the first condition directly by the
9357 // branch instruction and removing the no longer needed and/or instruction.
9358 Br1->setCondition(Cond1);
9359 LogicOp->eraseFromParent();
9360
9361 // Depending on the condition we have to either replace the true or the
9362 // false successor of the original branch instruction.
9363 if (Opc == Instruction::And)
9364 Br1->setSuccessor(0, TmpBB);
9365 else
9366 Br1->setSuccessor(1, TmpBB);
9367
9368 // Fill in the new basic block.
9369 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
9370 if (auto *I = dyn_cast<Instruction>(Cond2)) {
9371 I->removeFromParent();
9372 I->insertBefore(Br2->getIterator());
9373 }
9374
9375 // Update PHI nodes in both successors. The original BB needs to be
9376 // replaced in one successor's PHI nodes, because the branch comes now from
9377 // the newly generated BB (NewBB). In the other successor we need to add one
9378 // incoming edge to the PHI nodes, because both branch instructions target
9379 // now the same successor. Depending on the original branch condition
9380 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
9381 // we perform the correct update for the PHI nodes.
9382 // This doesn't change the successor order of the just created branch
9383 // instruction (or any other instruction).
9384 if (Opc == Instruction::Or)
9385 std::swap(TBB, FBB);
9386
9387 // Replace the old BB with the new BB.
9388 TBB->replacePhiUsesWith(&BB, TmpBB);
9389
9390 // Add another incoming edge from the new BB.
9391 for (PHINode &PN : FBB->phis()) {
9392 auto *Val = PN.getIncomingValueForBlock(&BB);
9393 PN.addIncoming(Val, TmpBB);
9394 }
9395
9396 if (Loop *L = LI->getLoopFor(&BB))
9397 L->addBasicBlockToLoop(TmpBB, *LI);
9398
9399 // The edge we need to delete starts at BB and ends at whatever TBB ends
9400 // up pointing to.
9401 DTU->applyUpdates({{DominatorTree::Insert, &BB, TmpBB},
9402 {DominatorTree::Insert, TmpBB, TBB},
9403 {DominatorTree::Insert, TmpBB, FBB},
9404 {DominatorTree::Delete, &BB, TBB}});
9405
9406 // Update the branch weights (from SelectionDAGBuilder::
9407 // FindMergedConditions).
9408 if (Opc == Instruction::Or) {
9409 // Codegen X | Y as:
9410 // BB1:
9411 // jmp_if_X TBB
9412 // jmp TmpBB
9413 // TmpBB:
9414 // jmp_if_Y TBB
9415 // jmp FBB
9416 //
9417
9418 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
9419 // The requirement is that
9420 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
9421 // = TrueProb for original BB.
9422 // Assuming the original weights are A and B, one choice is to set BB1's
9423 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
9424 // assumes that
9425 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
9426 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
9427 // TmpBB, but the math is more complicated.
9428 uint64_t TrueWeight, FalseWeight;
9429 if (extractBranchWeights(*Br1, TrueWeight, FalseWeight)) {
9430 uint64_t NewTrueWeight = TrueWeight;
9431 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
9432 setFittedBranchWeights(*Br1, {NewTrueWeight, NewFalseWeight},
9433 hasBranchWeightOrigin(*Br1));
9434
9435 NewTrueWeight = TrueWeight;
9436 NewFalseWeight = 2 * FalseWeight;
9437 setFittedBranchWeights(*Br2, {NewTrueWeight, NewFalseWeight},
9438 /*IsExpected=*/false);
9439 }
9440 } else {
9441 // Codegen X & Y as:
9442 // BB1:
9443 // jmp_if_X TmpBB
9444 // jmp FBB
9445 // TmpBB:
9446 // jmp_if_Y TBB
9447 // jmp FBB
9448 //
9449 // This requires creation of TmpBB after CurBB.
9450
9451 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
9452 // The requirement is that
9453 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
9454 // = FalseProb for original BB.
9455 // Assuming the original weights are A and B, one choice is to set BB1's
9456 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
9457 // assumes that
9458 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
9459 uint64_t TrueWeight, FalseWeight;
9460 if (extractBranchWeights(*Br1, TrueWeight, FalseWeight)) {
9461 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
9462 uint64_t NewFalseWeight = FalseWeight;
9463 setFittedBranchWeights(*Br1, {NewTrueWeight, NewFalseWeight},
9464 /*IsExpected=*/false);
9465
9466 NewTrueWeight = 2 * TrueWeight;
9467 NewFalseWeight = FalseWeight;
9468 setFittedBranchWeights(*Br2, {NewTrueWeight, NewFalseWeight},
9469 /*IsExpected=*/false);
9470 }
9471 }
9472
9473 MadeChange = true;
9474
9475 LLVM_DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
9476 TmpBB->dump());
9477 }
9478 return MadeChange;
9479}
#define Success
return SDValue()
static unsigned getIntrinsicID(const SDNode *N)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
AMDGPU Register Bank Select
Rewrite undef for PHI
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
This file contains the simple types necessary to represent the attributes associated with functions a...
static const Function * getParent(const Value *V)
#define X(NUM, ENUM, NAME)
Definition ELF.h:856
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 cl::opt< bool > OptimizePhiTypes("cgp-optimize-phi-types", cl::Hidden, cl::init(true), cl::desc("Enable converting phi types in CodeGenPrepare"))
static cl::opt< bool > DisableStoreExtract("disable-cgp-store-extract", cl::Hidden, cl::init(false), cl::desc("Disable store(extract) optimizations in CodeGenPrepare"))
static bool foldFCmpToFPClassTest(CmpInst *Cmp, const TargetLowering &TLI, const DataLayout &DL)
static cl::opt< bool > ProfileUnknownInSpecialSection("profile-unknown-in-special-section", cl::Hidden, cl::desc("In profiling mode like sampleFDO, if a function doesn't have " "profile, we cannot tell the function is cold for sure because " "it may be a function newly added without ever being sampled. " "With the flag enabled, compiler can put such profile unknown " "functions into a special section, so runtime system can choose " "to handle it in a different way than .text section, to save " "RAM for example. "))
static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI, const TargetLowering &TLI, const DataLayout &DL)
Sink the shift right instruction into user blocks if the uses could potentially be combined with this...
static cl::opt< bool > DisableExtLdPromotion("disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false), cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in " "CodeGenPrepare"))
static cl::opt< bool > DisablePreheaderProtect("disable-preheader-prot", cl::Hidden, cl::init(false), cl::desc("Disable protection against removing loop preheaders"))
static cl::opt< bool > AddrSinkCombineBaseOffs("addr-sink-combine-base-offs", cl::Hidden, cl::init(true), cl::desc("Allow combining of BaseOffs field in Address sinking."))
static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI, const DataLayout &DL)
If the specified cast instruction is a noop copy (e.g.
static bool splitMergedValStore(StoreInst &SI, const DataLayout &DL, const TargetLowering &TLI)
For the instruction sequence of store below, F and I values are bundled together as an i64 value befo...
static bool SinkCast(CastInst *CI)
Sink the specified cast instruction into its user blocks.
static bool swapICmpOperandsToExposeCSEOpportunities(CmpInst *Cmp)
Many architectures use the same instruction for both subtract and cmp.
static cl::opt< bool > AddrSinkCombineBaseReg("addr-sink-combine-base-reg", cl::Hidden, cl::init(true), cl::desc("Allow combining of BaseReg field in Address sinking."))
static bool FindAllMemoryUses(Instruction *I, SmallVectorImpl< std::pair< Use *, Type * > > &MemoryUses, SmallPtrSetImpl< Instruction * > &ConsideredInsts, const TargetLowering &TLI, const TargetRegisterInfo &TRI, bool OptSize, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI, unsigned &SeenInsts)
Recursively walk all the uses of I until we find a memory use.
static cl::opt< bool > StressStoreExtract("stress-cgp-store-extract", cl::Hidden, cl::init(false), cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"))
static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI, const TargetLowering *TLI, SelectInst *SI)
Returns true if a SelectInst should be turned into an explicit branch.
static std::optional< std::pair< Instruction *, Constant * > > getIVIncrement(const PHINode *PN, const LoopInfo *LI)
If given PN is an inductive variable with value IVInc coming from the backedge, and on each iteration...
static cl::opt< bool > AddrSinkCombineBaseGV("addr-sink-combine-base-gv", cl::Hidden, cl::init(true), cl::desc("Allow combining of BaseGV field in Address sinking."))
static cl::opt< bool > AddrSinkUsingGEPs("addr-sink-using-gep", cl::Hidden, cl::init(true), cl::desc("Address sinking in CGP using GEPs."))
static Value * getTrueOrFalseValue(SelectInst *SI, bool isTrue, const SmallPtrSet< const Instruction *, 2 > &Selects)
If isTrue is true, return the true value of SI, otherwise return false value of SI.
static cl::opt< bool > DisableBranchOpts("disable-cgp-branch-opts", cl::Hidden, cl::init(false), cl::desc("Disable branch optimizations in CodeGenPrepare"))
static cl::opt< bool > EnableTypePromotionMerge("cgp-type-promotion-merge", cl::Hidden, cl::desc("Enable merging of redundant sexts when one is dominating" " the other."), cl::init(true))
static cl::opt< bool > ProfileGuidedSectionPrefix("profile-guided-section-prefix", cl::Hidden, cl::init(true), cl::desc("Use profile info to add section prefix for hot/cold functions"))
static cl::opt< unsigned > HugeFuncThresholdInCGPP("cgpp-huge-func", cl::init(10000), cl::Hidden, cl::desc("Least BB number of huge function."))
static cl::opt< bool > AddrSinkNewSelects("addr-sink-new-select", cl::Hidden, cl::init(true), cl::desc("Allow creation of selects in Address sinking."))
static bool foldURemOfLoopIncrement(Instruction *Rem, const DataLayout *DL, const LoopInfo *LI, SmallPtrSet< BasicBlock *, 32 > &FreshBBs, bool IsHuge)
static bool optimizeBranch(CondBrInst *Branch, const TargetLowering &TLI, SmallPtrSet< BasicBlock *, 32 > &FreshBBs, bool IsHugeFunc)
static bool tryUnmergingGEPsAcrossIndirectBr(GetElementPtrInst *GEPI, const TargetTransformInfo *TTI)
static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal, const TargetLowering &TLI, const TargetRegisterInfo &TRI)
Check to see if all uses of OpVal by the specified inline asm call are due to memory operands.
static bool isIntrinsicOrLFToBeTailCalled(const TargetLibraryInfo *TLInfo, const CallInst *CI)
static void replaceAllUsesWith(Value *Old, Value *New, SmallPtrSet< BasicBlock *, 32 > &FreshBBs, bool IsHuge)
Replace all old uses with new ones, and push the updated BBs into FreshBBs.
static cl::opt< bool > ForceSplitStore("force-split-store", cl::Hidden, cl::init(false), cl::desc("Force store splitting no matter what the target query says."))
static bool matchOverflowPattern(Instruction *&I, ExtractValueInst *&MulExtract, ExtractValueInst *&OverflowExtract)
static void computeBaseDerivedRelocateMap(const SmallVectorImpl< GCRelocateInst * > &AllRelocateCalls, MapVector< GCRelocateInst *, SmallVector< GCRelocateInst *, 0 > > &RelocateInstMap)
static bool simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase, const SmallVectorImpl< GCRelocateInst * > &Targets)
static cl::opt< bool > AddrSinkCombineScaledReg("addr-sink-combine-scaled-reg", cl::Hidden, cl::init(true), cl::desc("Allow combining of ScaledReg field in Address sinking."))
static bool foldICmpWithDominatingICmp(CmpInst *Cmp, const TargetLowering &TLI)
For pattern like:
static bool MightBeFoldableInst(Instruction *I)
This is a little filter, which returns true if an addressing computation involving I might be folded ...
static bool matchIncrement(const Instruction *IVInc, Instruction *&LHS, Constant *&Step)
static cl::opt< bool > EnableGEPOffsetSplit("cgp-split-large-offset-gep", cl::Hidden, cl::init(true), cl::desc("Enable splitting large offset of GEP."))
static cl::opt< bool > DisableComplexAddrModes("disable-complex-addr-modes", cl::Hidden, cl::init(false), cl::desc("Disables combining addressing modes with different parts " "in optimizeMemoryInst."))
static cl::opt< bool > EnableICMP_EQToICMP_ST("cgp-icmp-eq2icmp-st", cl::Hidden, cl::init(false), cl::desc("Enable ICMP_EQ to ICMP_S(L|G)T conversion."))
static cl::opt< bool > VerifyBFIUpdates("cgp-verify-bfi-updates", cl::Hidden, cl::init(false), cl::desc("Enable BFI update verification for " "CodeGenPrepare."))
static cl::opt< bool > BBSectionsGuidedSectionPrefix("bbsections-guided-section-prefix", cl::Hidden, cl::init(true), cl::desc("Use the basic-block-sections profile to determine the text " "section prefix for hot functions. Functions with " "basic-block-sections profile will be placed in `.text.hot` " "regardless of their FDO profile info. Other functions won't be " "impacted, i.e., their prefixes will be decided by FDO/sampleFDO " "profiles."))
static bool isRemOfLoopIncrementWithLoopInvariant(Instruction *Rem, const LoopInfo *LI, Value *&RemAmtOut, Value *&AddInstOut, Value *&AddOffsetOut, PHINode *&LoopIncrPNOut)
static bool isIVIncrement(const Value *V, const LoopInfo *LI)
static cl::opt< bool > DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false), cl::desc("Disable GC optimizations in CodeGenPrepare"))
static bool GEPSequentialConstIndexed(GetElementPtrInst *GEP)
static void DbgInserterHelper(DbgVariableRecord *DVR, BasicBlock::iterator VI)
static bool isPromotedInstructionLegal(const TargetLowering &TLI, const DataLayout &DL, Value *Val)
Check whether or not Val is a legal instruction for TLI.
static cl::opt< uint64_t > FreqRatioToSkipMerge("cgp-freq-ratio-to-skip-merge", cl::Hidden, cl::init(2), cl::desc("Skip merging empty blocks if (frequency of empty block) / " "(frequency of destination block) is greater than this ratio"))
static BasicBlock::iterator findInsertPos(Value *Addr, Instruction *MemoryInst, Value *SunkAddr)
static bool IsNonLocalValue(Value *V, BasicBlock *BB)
Return true if the specified values are defined in a different basic block than BB.
static cl::opt< bool > EnableAndCmpSinking("enable-andcmp-sinking", cl::Hidden, cl::init(true), cl::desc("Enable sinking and/cmp into branches."))
static bool despeculateCountZeros(IntrinsicInst *CountZeros, DomTreeUpdater *DTU, LoopInfo *LI, const TargetLowering *TLI, const DataLayout *DL, ModifyDT &ModifiedDT, SmallPtrSet< BasicBlock *, 32 > &FreshBBs, bool IsHugeFunc)
If counting leading or trailing zeros is an expensive operation and a zero input is defined,...
static bool sinkCmpExpression(CmpInst *Cmp, const TargetLowering &TLI, const DataLayout &DL)
Sink the given CmpInst into user blocks to reduce the number of virtual registers that must be create...
static bool hasSameExtUse(Value *Val, const TargetLowering &TLI)
Check if all the uses of Val are equivalent (or free) zero or sign extensions.
static cl::opt< bool > StressExtLdPromotion("stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false), cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) " "optimization in CodeGenPrepare"))
static bool matchUAddWithOverflowConstantEdgeCases(CmpInst *Cmp, BinaryOperator *&Add)
Match special-case patterns that check for unsigned add overflow.
static cl::opt< bool > DisableSelectToBranch("disable-cgp-select2branch", cl::Hidden, cl::init(false), cl::desc("Disable select to branch conversion."))
static cl::opt< bool > DisableDeletePHIs("disable-cgp-delete-phis", cl::Hidden, cl::init(false), cl::desc("Disable elimination of dead PHI nodes."))
static cl::opt< bool > AddrSinkNewPhis("addr-sink-new-phis", cl::Hidden, cl::init(false), cl::desc("Allow creation of Phis in Address sinking."))
Defines an IR pass for CodeGen Prepare.
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:678
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static cl::opt< OutputCostKind > CostKind("cost-kind", cl::desc("Target cost kind"), cl::init(OutputCostKind::RecipThroughput), cl::values(clEnumValN(OutputCostKind::RecipThroughput, "throughput", "Reciprocal throughput"), clEnumValN(OutputCostKind::Latency, "latency", "Instruction latency"), clEnumValN(OutputCostKind::CodeSize, "code-size", "Code size"), clEnumValN(OutputCostKind::SizeAndLatency, "size-latency", "Code size and latency"), clEnumValN(OutputCostKind::All, "all", "Print all cost kinds")))
This file declares the LLVM IR specialization of the GenericCycle templates.
This file defines the DenseMap class.
static bool runOnFunction(Function &F, bool PostInlining)
#define DEBUG_TYPE
static Value * getCondition(Instruction *I)
Hexagon Common GEP
IRTranslator LLVM IR MI
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Module.h This file contains the declarations for the Module class.
This defines the Use class.
iv users
Definition IVUsers.cpp:48
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static void eraseInstruction(Instruction &I, ICFLoopSafetyInfo &SafetyInfo, MemorySSAUpdater &MSSAU)
Definition LICM.cpp:1544
#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:1050
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1187
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:377
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:326
bool isSignedIntN(unsigned N) const
Check if this APInt has an N-bits signed integer value.
Definition APInt.h:432
unsigned getSignificantBits() const
Get the minimum bit size for this signed APInt.
Definition APInt.h:1552
unsigned logBase2() const
Definition APInt.h:1782
LLVM_ABI APInt sext(unsigned width) const
Sign extend to a new width.
Definition APInt.cpp:1023
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:437
int64_t getSExtValue() const
Get sign extended value.
Definition APInt.h:1583
LLVM_ABI bool isStaticAlloca() const
Return true if this alloca is in the entry block of the function and is a constant size.
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
LLVM_ABI std::optional< TypeSize > getAllocationSize(const DataLayout &DL) const
Get allocation size in bytes.
void setAlignment(Align Align)
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addUsedIfAvailable()
Add the specified Pass class to the set of analyses used by this pass.
AnalysisUsage & addRequired()
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
An instruction that atomically checks whether a specified value is in a memory location,...
static unsigned getPointerOperandIndex()
an instruction that atomically reads a memory location, combines it with another value,...
static unsigned getPointerOperandIndex()
Analysis pass providing the BasicBlockSectionsProfileReader.
LLVM_ABI bool isFunctionHot(StringRef FuncName) const
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:459
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:446
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:515
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches,...
Definition BasicBlock.h:672
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
LLVM_ABI void insertDbgRecordBefore(DbgRecord *DR, InstListType::iterator Here)
Insert a DbgRecord into a block at the position given by Here.
InstListType::const_iterator const_iterator
Definition BasicBlock.h:171
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
LLVM_ABI void moveAfter(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it right after MovePos in the function M...
LLVM_ABI InstListType::const_iterator getFirstNonPHIOrDbg(bool SkipPseudoOp=true) const
Returns a pointer to the first instruction in this block that is not a PHINode or a debug intrinsic,...
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
LLVM_ABI const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
LLVM_ABI const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
LLVM_ABI void insertDbgRecordAfter(DbgRecord *DR, Instruction *I)
Insert a DbgRecord into a block at the position given by I.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
BinaryOps getOpcode() const
Definition InstrTypes.h:409
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
Analysis pass which computes BlockFrequencyInfo.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
LLVM_ABI void setBlockFreq(const BasicBlock *BB, BlockFrequency Freq)
LLVM_ABI BlockFrequency getBlockFreq(const BasicBlock *BB) const
getblockFreq - Return block frequency.
Analysis pass which computes BranchProbabilityInfo.
static LLVM_ABI BranchProbability getBranchProbability(uint64_t Numerator, uint64_t Denominator)
bool isInlineAsm() const
Check if this call is an inline asm statement.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
bool hasFnAttr(Attribute::AttrKind Kind) const
Determine whether this call has the given attribute.
Value * getArgOperand(unsigned i) const
void setArgOperand(unsigned i, Value *v)
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
This class represents a function call, abstracting a target machine's calling convention.
This is the base class for all instructions that perform data casts.
Definition InstrTypes.h:512
static LLVM_ABI CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
This class is the base class for the comparison instructions.
Definition InstrTypes.h:728
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition InstrTypes.h:890
static LLVM_ABI CmpInst * Create(OtherOps Op, Predicate Pred, Value *S1, Value *S2, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Construct a compare instruction, given the opcode, the predicate and the two operands.
Predicate getPredicate() const
Return the predicate for this instruction.
Definition InstrTypes.h:828
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Conditional Branch instruction.
static LLVM_ABI Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI Constant * getNeg(Constant *C, bool HasNSW=false)
This is the shared class of boolean and integer constants.
Definition Constants.h:87
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:135
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition Constants.h:219
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
int64_t getSExtValue() const
Return the constant as a 64-bit integer value after it has been sign extended as appropriate for the ...
Definition Constants.h:174
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
static LLVM_ABI Constant * getSplat(ElementCount EC, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
Definition Constant.h:43
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
LLVM_ABI void removeFromParent()
Record of a variable value-assignment, aka a non instruction representation of the dbg....
LocationType Type
Classification of the debug-info record that this DbgVariableRecord represents.
LLVM_ABI void replaceVariableLocationOp(Value *OldValue, Value *NewValue, bool AllowEmpty=false)
LLVM_ABI iterator_range< location_op_iterator > location_ops() const
Get the locations corresponding to the variable referenced by the debug info intrinsic.
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:223
bool erase(const KeyT &Val)
Definition DenseMap.h:377
unsigned size() const
Definition DenseMap.h:172
iterator end()
Definition DenseMap.h:141
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:284
LLVM_ABI void deleteBB(BasicBlock *DelBB)
Delete DelBB.
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
Legacy analysis pass which computes a DominatorTree.
Definition Dominators.h:277
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
This instruction extracts a struct member or array element value from an aggregate value.
iterator_range< idx_iterator > indices() const
This instruction compares its operands according to the predicate given to the constructor.
bool none() const
Definition FMF.h:57
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:867
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
const BasicBlock & getEntryBlock() const
Definition Function.h:793
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:2893
LLVM_ABI Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following:
LLVM_ABI void removeFromParent()
This method unlinks 'this' from the containing basic block, but does not delete it.
LLVM_ABI bool isDebugOrPseudoInst() const LLVM_READONLY
Return true if the instruction is a DbgInfoIntrinsic or PseudoProbeInst.
LLVM_ABI void setHasNoSignedWrap(bool b=true)
Set or clear the nsw flag on this instruction, which must be an operator which supports this flag.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI void moveAfter(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
bool hasMetadata() const
Return true if this instruction has any metadata attached to it.
LLVM_ABI void moveBefore(InstListType::iterator InsertPos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
bool isEHPad() const
Return true if the instruction is a variety of EH-block.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Instruction * user_back()
Specialize the methods defined in Value, as we know that an instruction can only be used by other ins...
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
LLVM_ABI bool mayHaveSideEffects() const LLVM_READONLY
Return true if the instruction may have side effects.
LLVM_ABI bool comesBefore(const Instruction *Other) const
Given an instruction Other in the same basic block as this instruction, return true if this instructi...
LLVM_ABI bool mayReadFromMemory() const LLVM_READONLY
Return true if this instruction may read memory.
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
LLVM_ABI FastMathFlags getFastMathFlags() const LLVM_READONLY
Convenience function for getting all the fast-math flags, which must be an operator which supports th...
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
bool isShift() const
LLVM_ABI void dropPoisonGeneratingFlags()
Drops flags that may cause this instruction to evaluate to poison despite having non-poison inputs.
LLVM_ABI std::optional< simple_ilist< DbgRecord >::iterator > getDbgReinsertionPosition()
Return an iterator to the position of the "Next" DbgRecord after this instruction,...
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI void copyMetadata(const Instruction &SrcInst, ArrayRef< unsigned > WL=ArrayRef< unsigned >())
Copy metadata from SrcInst to this instruction.
LLVM_ABI void insertAfter(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately after the specified instruction.
A wrapper class for inspecting calls to intrinsic functions.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
An instruction for reading from memory.
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:594
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
The legacy pass manager's analysis pass to compute loop information.
Definition LoopInfo.h:619
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
static MVT getIntegerVT(unsigned BitWidth)
LLVM_ABI void replacePhiUsesWith(MachineBasicBlock *Old, MachineBasicBlock *New)
Update all phi nodes in this basic block to refer to basic block New instead of basic block Old.
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:38
iterator find(const KeyT &Key)
Definition MapVector.h:156
iterator end()
Definition MapVector.h:69
bool empty() const
Definition MapVector.h:79
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition MapVector.h:126
VectorType::iterator erase(typename VectorType::iterator Iterator)
Remove the element given by Iterator.
Definition MapVector.h:210
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
op_range incoming_values()
Value * getIncomingValueForBlock(const BasicBlock *BB) const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
PointerIntPair - This class implements a pair of a pointer and small integer.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:132
An analysis pass based on the new PM to deliver ProfileSummaryInfo.
An analysis pass based on legacy pass manager to deliver ProfileSummaryInfo.
Analysis providing profile information.
Value * getReturnValue() const
Convenience accessor. Returns null if there is no return value.
This class represents the LLVM 'select' instruction.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, const Instruction *MDFrom=nullptr)
size_type count(const_arg_type key) const
Count the number of elements of a given key in the SetVector.
Definition SetVector.h:268
void clear()
Completely clear the SetVector.
Definition SetVector.h:273
bool empty() const
Determine if the SetVector is empty or not.
Definition SetVector.h:100
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
value_type pop_back_val()
Definition SetVector.h:285
VectorType * getType() const
Overload to return most specific vector type.
size_type size() const
Definition SmallPtrSet.h:99
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
bool erase(PtrType Ptr)
Remove pointer from the set.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
void insert_range(Range &&R)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition SmallSet.h:176
bool erase(const T &V)
Definition SmallSet.h:200
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
iterator erase(const_iterator CI)
typename SuperClass::iterator iterator
void resize(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
static unsigned getPointerOperandIndex()
TypeSize getElementOffset(unsigned Idx) const
Definition DataLayout.h:774
Analysis pass providing the TargetTransformInfo.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
LibFunc getLibFunc(StringRef funcName) const
Searches for a particular function name.
int InstructionOpcodeToISD(unsigned Opcode) const
Get the ISD node that corresponds to the Instruction class opcode.
EVT getValueType(const DataLayout &DL, Type *Ty, bool AllowUnknown=false) const
Return the EVT corresponding to this LLVM type.
virtual bool isSelectSupported(SelectSupportKind) const
virtual bool isEqualityCmpFoldedWithSignedCmp() const
Return true if instruction generated for equality comparison is folded with instruction generated for...
virtual bool shouldFormOverflowOp(unsigned Opcode, EVT VT, bool MathUsed) const
Try to convert math with an overflow comparison into the corresponding DAG node operation.
virtual bool isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const
Return if the target supports combining a chain like:
virtual bool shouldOptimizeMulOverflowWithZeroHighBits(LLVMContext &Context, EVT VT) const
bool isExtLoad(const LoadInst *Load, const Instruction *Ext, const DataLayout &DL) const
Return true if Load and Ext can form an ExtLoad.
virtual bool isSExtCheaperThanZExt(EVT FromTy, EVT ToTy) const
Return true if sign-extension from FromTy to ToTy is cheaper than zero-extension.
const TargetMachine & getTargetMachine() const
virtual bool isCtpopFast(EVT VT) const
Return true if ctpop instruction is fast.
virtual bool isZExtFree(Type *FromTy, Type *ToTy) const
Return true if any actual instruction that defines a value of type FromTy implicitly zero-extends the...
bool enableExtLdPromotion() const
Return true if the target wants to use the optimization that turns ext(promotableInst1(....
virtual bool isCheapToSpeculateCttz(Type *Ty) const
Return true if it is cheap to speculate a call to intrinsic cttz.
bool isJumpExpensive() const
Return true if Flow Control is an expensive operation that should be avoided.
bool hasExtractBitsInsn() const
Return true if the target has BitExtract instructions.
virtual bool allowsMisalignedMemoryAccesses(EVT, unsigned AddrSpace=0, Align Alignment=Align(1), MachineMemOperand::Flags Flags=MachineMemOperand::MONone, unsigned *=nullptr) const
Determine if the target supports unaligned memory accesses.
bool isSlowDivBypassed() const
Returns true if target has indicated at least one type should be bypassed.
virtual bool isTruncateFree(Type *FromTy, Type *ToTy) const
Return true if it's free to truncate a value of type FromTy to type ToTy.
virtual bool hasMultipleConditionRegisters(EVT VT) const
Does the target have multiple (allocatable) condition registers that can be used to store the results...
virtual EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const
For types supported by the target, this is an identity function.
virtual MVT getPreferredSwitchConditionType(LLVMContext &Context, EVT ConditionVT) const
Returns preferred type for switch condition.
bool isCondCodeLegal(ISD::CondCode CC, MVT VT) const
Return true if the specified condition code is legal for a comparison of the specified types on this ...
virtual bool canCombineStoreAndExtract(Type *VectorTy, Value *Idx, unsigned &Cost) const
Return true if the target can combine store(extractelement VectorTy,Idx).
bool isTypeLegal(EVT VT) const
Return true if the target has native support for the specified value type.
virtual bool isFreeAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const
Returns true if a cast from SrcAS to DestAS is "cheap", such that e.g.
virtual bool shouldConsiderGEPOffsetSplit() const
bool isExtFree(const Instruction *I) const
Return true if the extension represented by I is free.
bool isOperationLegalOrCustom(unsigned Op, EVT VT, bool LegalOnly=false) const
Return true if the specified operation is legal on this target or can be made legal with custom lower...
bool isPredictableSelectExpensive() const
Return true if selects are only cheaper than branches if the branch is unlikely to be predicted right...
virtual bool isMultiStoresCheaperThanBitsMerge(EVT LTy, EVT HTy) const
Return true if it is cheaper to split the store of a merged int val from a pair of smaller values int...
virtual bool getAddrModeArguments(const IntrinsicInst *, SmallVectorImpl< Value * > &, Type *&) const
CodeGenPrepare sinks address calculations into the same BB as Load/Store instructions reading the add...
const DenseMap< unsigned int, unsigned int > & getBypassSlowDivWidths() const
Returns map of slow types for division or remainder with corresponding fast types.
virtual bool isCheapToSpeculateCtlz(Type *Ty) const
Return true if it is cheap to speculate a call to intrinsic ctlz.
virtual bool useSoftFloat() const
virtual int64_t getPreferredLargeGEPBaseOffset(int64_t MinOffset, int64_t MaxOffset) const
Return the prefered common base offset.
LegalizeTypeAction getTypeAction(LLVMContext &Context, EVT VT) const
Return how we should legalize values of this type, either it is already legal (return 'Legal') or we ...
virtual bool shouldAlignPointerArgs(CallInst *, unsigned &, Align &) const
Return true if the pointer arguments to CI should be aligned by aligning the object whose address is ...
virtual Type * shouldConvertSplatType(ShuffleVectorInst *SVI) const
Given a shuffle vector SVI representing a vector splat, return a new scalar type of size equal to SVI...
bool isLoadLegal(EVT ValVT, EVT MemVT, Align Alignment, unsigned AddrSpace, unsigned ExtType, bool Atomic) const
Return true if the specified load with extension is legal on this target.
virtual bool addressingModeSupportsTLS(const GlobalValue &) const
Returns true if the targets addressing mode can target thread local storage (TLS).
virtual bool shouldConvertPhiType(Type *From, Type *To) const
Given a set in interconnected phis of type 'From' that are loaded/stored or bitcast to type 'To',...
virtual bool isFAbsFree(EVT VT) const
Return true if an fabs operation is free to the point where it is never worthwhile to replace it with...
virtual bool preferZeroCompareBranch() const
Return true if the heuristic to prefer icmp eq zero should be used in code gen prepare.
virtual bool isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM, Type *Ty, unsigned AddrSpace, Instruction *I=nullptr) const
Return true if the addressing mode represented by AM is legal for this target, for a load/store of th...
virtual bool optimizeExtendOrTruncateConversion(Instruction *I, Loop *L, const TargetTransformInfo &TTI) const
Try to optimize extending or truncating conversion instructions (like zext, trunc,...
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
std::vector< AsmOperandInfo > AsmOperandInfoVector
virtual AsmOperandInfoVector ParseConstraints(const DataLayout &DL, const TargetRegisterInfo *TRI, const CallBase &Call) const
Split up the constraint string from the inline assembly value into the specific constraints and their...
virtual void ComputeConstraintToUse(AsmOperandInfo &OpInfo, SDValue Op, SelectionDAG *DAG=nullptr) const
Determines the constraint code and constraint type to use for the specific AsmOperandInfo,...
virtual bool mayBeEmittedAsTailCall(const CallInst *) const
Return true if the target may be able emit the call instruction as a tail call.
virtual bool isNoopAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const
Returns true if a cast between SrcAS and DestAS is a noop.
virtual const TargetSubtargetInfo * getSubtargetImpl(const Function &) const
Virtual method implemented by subclasses that returns a reference to that target's TargetSubtargetInf...
TargetOptions Options
unsigned EnableFastISel
EnableFastISel - This flag enables fast-path instruction selection which trades away generated code q...
Target-Independent Code Generator Pass Configuration Options.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
virtual const TargetLowering * getTargetLowering() const
virtual bool addrSinkUsingGEPs() const
Sink addresses into blocks using GEP instructions rather than pointer casts and arithmetic.
Wrapper pass for TargetTransformInfo.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
LLVM_ABI InstructionCost getVectorInstrCost(unsigned Opcode, Type *Val, TTI::TargetCostKind CostKind, unsigned Index=-1, const Value *Op0=nullptr, const Value *Op1=nullptr, TTI::VectorInstrContext VIC=TTI::VectorInstrContext::None) const
TargetCostKind
The kind of cost model.
@ TCK_RecipThroughput
Reciprocal throughput.
@ TCK_SizeAndLatency
The weighted sum of size and latency.
LLVM_ABI InstructionCost getArithmeticInstrCost(unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput, TTI::OperandValueInfo Opd1Info={TTI::OK_AnyValue, TTI::OP_None}, TTI::OperandValueInfo Opd2Info={TTI::OK_AnyValue, TTI::OP_None}, ArrayRef< const Value * > Args={}, const Instruction *CxtI=nullptr, const TargetLibraryInfo *TLibInfo=nullptr) const
This is an approximation of reciprocal throughput of a math/logic op.
LLVM_ABI InstructionCost getIntImmCost(const APInt &Imm, Type *Ty, TargetCostKind CostKind) const
Return the expected cost of materializing for the given integer immediate of the specified type.
LLVM_ABI bool shouldConsiderAddressTypePromotion(const Instruction &I, bool &AllowPromotionWithoutCommonHeader) const
@ TCC_Basic
The cost of a typical 'add' instruction.
LLVM_ABI bool isVectorShiftByScalarCheap(Type *Ty) const
Return true if it's significantly cheaper to shift a vector by a uniform scalar than by an amount whi...
LLVM_ABI bool isProfitableToSinkOperands(Instruction *I, SmallVectorImpl< Use * > &Ops) const
Return true if sinking I's operands to the same basic block as I is profitable, e....
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM_ABI unsigned getIntegerBitWidth() const
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:288
LLVM_ABI bool isScalableTy(SmallPtrSetImpl< const Type * > &Visited) const
Return true if this is a type whose size is a known multiple of vscale.
Definition Type.cpp:61
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:309
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:368
LLVM_ABI Type * getWithNewBitWidth(unsigned NewBitWidth) const
Given an integer or vector type, change the lane bitwidth to NewBitwidth, whilst keeping the old numb...
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:232
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
Definition Type.h:270
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:257
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:313
BasicBlock * getSuccessor(unsigned i=0) const
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
op_range operands()
Definition User.h:267
const Use & getOperandUse(unsigned i) const
Definition User.h:220
void setOperand(unsigned i, Value *Val)
Definition User.h:212
LLVM_ABI bool replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Definition User.cpp:25
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
user_iterator user_begin()
Definition Value.h:402
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:394
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:439
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:553
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:258
iterator_range< user_iterator > users()
Definition Value.h:426
LLVM_ABI Align getPointerAlignment(const DataLayout &DL) const
Returns an alignment of the pointer value.
Definition Value.cpp:1002
LLVM_ABI bool isUsedInBasicBlock(const BasicBlock *BB) const
Check if this value is used in the specified basic block.
Definition Value.cpp:239
LLVM_ABI void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition Value.cpp:713
bool use_empty() const
Definition Value.h:346
user_iterator user_end()
Definition Value.h:410
iterator_range< use_iterator > uses()
Definition Value.h:380
void mutateType(Type *Ty)
Mutate the type of this Value to be of the specified type.
Definition Value.h:807
user_iterator_impl< User > user_iterator
Definition Value.h:391
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:400
LLVM_ABI void dump() const
Support for debugging, callable in GDB: V->dump()
bool pointsToAliveValue() const
int getNumOccurrences() const
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
constexpr bool isNonZero() const
Definition TypeSize.h:155
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
TypeSize getSequentialElementStride(const DataLayout &DL) const
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition ilist_node.h:348
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
@ Entry
Definition COFF.h:862
unsigned getAddrMode(MCInstrInfo const &MCII, MCInst const &MCI)
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
SpecificConstantMatch m_ZeroInt()
Convenience matchers for specific integer values.
AllOnesConstantMatch m_AllOnes()
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
match_bind< PHINode > m_Phi(PHINode *&PN)
Match a PHI node, capturing it if we match.
auto m_Cmp()
Matches any compare instruction and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::URem > m_URem(const LHS &L, const RHS &R)
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
BinaryOp_match< LHS, RHS, Instruction::Xor > m_Xor(const LHS &L, const RHS &R)
ap_match< APInt > m_APIntAllowPoison(const APInt *&Res)
Match APInt while allowing poison in splat vector constants.
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
bool match(Val *V, const Pattern &P)
match_bind< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
BinOpPred_match< LHS, RHS, is_right_shift_op > m_Shr(const LHS &L, const RHS &R)
Matches logical shift operations.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap, true > m_c_NUWAdd(const LHS &L, const RHS &R)
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_BinOp()
Match an arbitrary binary operation and ignore it.
ExtractValue_match< Ind, Val_t > m_ExtractValue(const Val_t &V)
Match a single index ExtractValue instruction.
auto m_Value()
Match an arbitrary value and ignore it.
auto m_Ctpop(const Opnd0 &Op0)
auto m_Constant()
Match an arbitrary Constant and ignore it.
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
TwoOps_match< V1_t, V2_t, Instruction::ShuffleVector > m_Shuffle(const V1_t &v1, const V2_t &v2)
Matches ShuffleVectorInst independently of mask value.
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
match_immconstant_ty m_ImmConstant()
Match an arbitrary immediate Constant and ignore it.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoSignedWrap > m_NSWAdd(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
UAddWithOverflow_match< LHS_t, RHS_t, Sum_t > m_UAddWithOverflow(const LHS_t &L, const RHS_t &R, const Sum_t &S)
Match an icmp instruction checking for unsigned overflow on addition.
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
brc_match< Cond_t, match_bind< BasicBlock >, match_bind< BasicBlock > > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
auto m_Undef()
Match an arbitrary undef constant.
BinaryOp_match< LHS, RHS, Instruction::Or, true > m_c_Or(const LHS &L, const RHS &R)
Matches an Or with LHS and RHS in either order.
ThreeOps_match< Val_t, Elt_t, Idx_t, Instruction::InsertElement > m_InsertElt(const Val_t &Val, const Elt_t &Elt, const Idx_t &Idx)
Matches InsertElementInst.
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
int compare(DigitsT LDigits, int16_t LScale, DigitsT RDigits, int16_t RScale)
Compare two scaled numbers.
@ CE
Windows NT (Windows on ARM)
Definition MCAsmInfo.h:51
initializer< Ty > init(const Ty &Val)
DXILDebugInfoMap run(Module &M)
@ User
could "use" a pointer
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
SmallVector< Node, 4 > NodeList
Definition RDFGraph.h:550
iterator end() const
Definition BasicBlock.h:89
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
LLVM_ABI iterator begin() const
BaseReg
Stack frame base register. Bit 0 of FREInfo.Info.
Definition SFrame.h:77
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:315
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
@ Offset
Definition DWP.cpp:578
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1765
LLVM_ABI bool RemoveRedundantDbgInstrs(BasicBlock *BB)
Try to remove redundant dbg.value instructions from given basic block.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1739
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1669
LLVM_ABI bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
If the specified value is a trivially dead instruction, delete it.
Definition Local.cpp:535
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:134
LLVM_ABI bool bypassSlowDivision(BasicBlock *BB, const DenseMap< unsigned int, unsigned int > &BypassWidth, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BranchProbabilityInfo *BPI=nullptr)
This optimization identifies DIV instructions in a BB that can be profitably bypassed and carried out...
LLVM_ABI void findDbgValues(Value *V, SmallVectorImpl< DbgVariableRecord * > &DbgVariableRecords)
Finds the dbg.values describing a value.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
APInt operator*(APInt a, uint64_t RHS)
Definition APInt.h:2262
bool isAligned(Align Lhs, uint64_t SizeInBytes)
Checks that SizeInBytes is a multiple of the alignment.
Definition Alignment.h:134
LLVM_ABI void salvageDebugInfo(const MachineRegisterInfo &MRI, MachineInstr &MI)
Assuming the instruction MI is going to be deleted, attempt to salvage debug users of MI by writing t...
Definition Utils.cpp:1675
auto successors(const MachineBasicBlock *BB)
@ Load
The value being inserted comes from a load (InsertElement only).
OuterAnalysisManagerProxy< ModuleAnalysisManager, Function > ModuleAnalysisManagerFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
LLVM_ABI ReturnInst * FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB, BasicBlock *Pred, DomTreeUpdater *DTU=nullptr)
This method duplicates the specified return instruction into a predecessor which ends in an unconditi...
bool operator!=(uint64_t V1, const APInt &V2)
Definition APInt.h:2140
constexpr from_range_t from_range
LLVM_ABI BasicBlock * splitBlockBefore(BasicBlock *Old, BasicBlock::iterator SplitPt, DomTreeUpdater *DTU, LoopInfo *LI, MemorySSAUpdater *MSSAU, const Twine &BBName="")
Split the specified block at the specified instruction SplitPt.
LLVM_ABI Instruction * SplitBlockAndInsertIfElse(Value *Cond, BasicBlock::iterator SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BasicBlock *ElseBlock=nullptr)
Similar to SplitBlockAndInsertIfThen, but the inserted block is on the false path of the branch.
LLVM_ABI bool SplitIndirectBrCriticalEdges(Function &F, bool IgnoreBlocksWithoutPHI, BranchProbabilityInfo *BPI=nullptr, BlockFrequencyInfo *BFI=nullptr, DomTreeUpdater *DTU=nullptr)
LLVM_ABI bool DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, SmallPtrSetImpl< PHINode * > *KnownNonDeadPHIs=nullptr)
Examine each PHI in the given block and delete it if it is dead.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2208
LLVM_ABI bool shouldOptimizeForSize(const MachineFunction *MF, ProfileSummaryInfo *PSI, const MachineBlockFrequencyInfo *BFI, PGSOQueryType QueryType=PGSOQueryType::Other)
Returns true if machine function MF is suggested to be size-optimized based on the profile.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:633
constexpr std::enable_if_t< std::is_signed_v< T >, std::pair< T, bool > > AddOverflow(T X, T Y)
Add two signed integers, computing the two's complement truncated result, returning a pair {result,...
Definition MathExtras.h:704
LLVM_ABI void DeleteDeadBlock(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, bool KeepOneInputPHIs=false)
Delete the specified block, which must have no predecessors.
LLVM_ABI bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true, bool IgnoreUBImplyingAttrs=true)
Return true if the instruction does not have any effects besides calculating the result and does not ...
auto unique(Range &&R, Predicate P)
Definition STLExtras.h:2134
LLVM_ABI Value * getSplatValue(const Value *V)
Get splat value if the input is a splat vector or return nullptr.
LLVM_ABI bool hasBranchWeightOrigin(const Instruction &I)
Check if Branch Weight Metadata has an "expected" field from an llvm.expect* intrinsic.
constexpr auto equal_to(T &&Arg)
Functor variant of std::equal_to that can be used as a UnaryPredicate in functional algorithms like a...
Definition STLExtras.h:2173
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
constexpr int popcount(T Value) noexcept
Count the number of set bits in a value.
Definition bit.h:156
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
LLVM_ABI Value * simplifyAddInst(Value *LHS, Value *RHS, bool IsNSW, bool IsNUW, const SimplifyQuery &Q)
Given operands for an Add, fold the result or return null.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
Align getKnownAlignment(Value *V, const DataLayout &DL, const Instruction *CxtI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr)
Try to infer an alignment for the specified pointer.
Definition Local.h:248
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
Definition STLExtras.h:2200
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1746
LLVM_ABI bool isSplatValue(const Value *V, int Index=-1, unsigned Depth=0)
Return true if each element of the vector value V is poisoned or equal to every other non-poisoned el...
LLVM_ABI bool replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV, const TargetLibraryInfo *TLI=nullptr, const DominatorTree *DT=nullptr, AssumptionCache *AC=nullptr, SmallSetVector< Instruction *, 8 > *UnsimplifiedUsers=nullptr)
Replace all uses of 'I' with 'SimpleV' and simplify the uses recursively.
auto reverse(ContainerTy &&C)
Definition STLExtras.h:407
LLVM_ABI bool recognizeBSwapOrBitReverseIdiom(Instruction *I, bool MatchBSwaps, bool MatchBitReversals, SmallVectorImpl< Instruction * > &InsertedInsts)
Try to match a bswap or bitreverse idiom.
Definition Local.cpp:3802
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1636
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
LLVM_ABI void SplitBlockAndInsertIfThenElse(Value *Cond, BasicBlock::iterator SplitBefore, Instruction **ThenTerm, Instruction **ElseTerm, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr)
SplitBlockAndInsertIfThenElse is similar to SplitBlockAndInsertIfThen, but also creates the ElseBlock...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1753
auto make_first_range(ContainerTy &&c)
Given a container of pairs, return a range over the first elements.
Definition STLExtras.h:1399
generic_gep_type_iterator<> gep_type_iterator
LLVM_ABI FunctionPass * createCodeGenPrepareLegacyPass()
createCodeGenPrepareLegacyPass - Transform the code to expose more pattern matching during instructio...
LLVM_ABI ISD::CondCode getFCmpCondCode(FCmpInst::Predicate Pred)
getFCmpCondCode - Return the ISD condition code corresponding to the given LLVM IR floating-point con...
Definition Analysis.cpp:203
LLVM_ABI bool VerifyLoopInfo
Enable verification of loop info.
Definition LoopInfo.cpp:53
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
LLVM_ABI bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
LLVM_ABI bool attributesPermitTailCall(const Function *F, const Instruction *I, const ReturnInst *Ret, const TargetLoweringBase &TLI, bool *AllowDifferingSizes=nullptr)
Test if given that the input instruction is in the tail call position, if there is an attribute misma...
Definition Analysis.cpp:588
TargetTransformInfo TTI
IRBuilder(LLVMContext &, FolderTy, InserterTy, MDNode *, ArrayRef< OperandBundleDef >) -> IRBuilder< FolderTy, InserterTy >
LLVM_ABI bool MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, MemoryDependenceResults *MemDep=nullptr, bool PredecessorWithTwoSuccessors=false, DominatorTree *DT=nullptr)
Attempts to merge a block into its predecessor, if possible.
@ Or
Bitwise or logical OR of integers.
@ Xor
Bitwise or logical XOR of integers.
@ And
Bitwise or logical AND of integers.
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
LLVM_ABI BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction.
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition STLExtras.h:2012
IntPtrTy
Definition InstrProf.h:82
DWARFExpression::Operation Op
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Return true if this function can prove that V does not have undef bits and is never poison.
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI bool VerifyDomInfo
Enables verification of dominator trees.
constexpr unsigned BitWidth
LLVM_ABI bool extractBranchWeights(const MDNode *ProfileData, SmallVectorImpl< uint32_t > &Weights)
Extract branch weights from MD_prof metadata.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
gep_type_iterator gep_type_begin(const User *GEP)
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2192
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition Alignment.h:201
constexpr std::enable_if_t< std::is_signed_v< T >, std::pair< T, bool > > MulOverflow(T X, T Y)
Multiply two signed integers, computing the two's complement truncated result, returning a pair {resu...
Definition MathExtras.h:778
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 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.