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