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