LLVM 24.0.0git
Utils.cpp
Go to the documentation of this file.
1//===- llvm/CodeGen/GlobalISel/Utils.cpp -------------------------*- C++ -*-==//
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/// \file This file implements the utility functions used by the GlobalISel
9/// pipeline.
10//===----------------------------------------------------------------------===//
11
13#include "llvm/ADT/APFloat.h"
14#include "llvm/ADT/APInt.h"
37#include "llvm/IR/Constants.h"
38#include "llvm/IR/Function.h"
39#include "llvm/IR/Type.h"
43#include <cmath>
44#include <limits>
45#include <numeric>
46#include <optional>
47#include <tuple>
48
49#define DEBUG_TYPE "globalisel-utils"
50
51using namespace llvm;
52using namespace MIPatternMatch;
53
55 const TargetInstrInfo &TII,
56 const RegisterBankInfo &RBI, Register Reg,
57 const TargetRegisterClass &RegClass) {
58 if (!RBI.constrainGenericRegister(Reg, RegClass, MRI))
59 return MRI.createVirtualRegister(&RegClass);
60
61 return Reg;
62}
63
65 const MachineFunction &MF, const TargetRegisterInfo &TRI,
67 const RegisterBankInfo &RBI, MachineInstr &InsertPt,
68 const TargetRegisterClass &RegClass, MachineOperand &RegMO) {
69 Register Reg = RegMO.getReg();
70 // Assume physical registers are properly constrained.
71 assert(Reg.isVirtual() && "PhysReg not implemented");
72
73 // Save the old register class to check whether
74 // the change notifications will be required.
75 // TODO: A better approach would be to pass
76 // the observers to constrainRegToClass().
77 auto *OldRegClass = MRI.getRegClassOrNull(Reg);
78 Register ConstrainedReg = constrainRegToClass(MRI, TII, RBI, Reg, RegClass);
79 // If we created a new virtual register because the class is not compatible
80 // then create a copy between the new and the old register.
81 if (ConstrainedReg != Reg) {
82 MachineBasicBlock::iterator InsertIt(&InsertPt);
83 MachineBasicBlock &MBB = *InsertPt.getParent();
84 // FIXME: The copy needs to have the classes constrained for its operands.
85 // Use operand's regbank to get the class for old register (Reg).
86 if (RegMO.isUse()) {
87 BuildMI(MBB, InsertIt, InsertPt.getDebugLoc(),
88 TII.get(TargetOpcode::COPY), ConstrainedReg)
89 .addReg(Reg);
90 } else {
91 assert(RegMO.isDef() && "Must be a definition");
92 BuildMI(MBB, std::next(InsertIt), InsertPt.getDebugLoc(),
93 TII.get(TargetOpcode::COPY), Reg)
94 .addReg(ConstrainedReg);
95 }
96 if (GISelChangeObserver *Observer = MF.getObserver()) {
97 Observer->changingInstr(*RegMO.getParent());
98 }
99 RegMO.setReg(ConstrainedReg);
100 if (GISelChangeObserver *Observer = MF.getObserver()) {
101 Observer->changedInstr(*RegMO.getParent());
102 }
103 } else if (OldRegClass != MRI.getRegClassOrNull(Reg)) {
104 if (GISelChangeObserver *Observer = MF.getObserver()) {
105 if (!RegMO.isDef()) {
106 MachineInstr *RegDef = MRI.getVRegDef(Reg);
107 Observer->changedInstr(*RegDef);
108 }
109 Observer->changingAllUsesOfReg(MRI, Reg);
110 Observer->finishedChangingAllUsesOfReg();
111 }
112 }
113 return ConstrainedReg;
114}
115
117 const MachineFunction &MF, const TargetRegisterInfo &TRI,
119 const RegisterBankInfo &RBI, MachineInstr &InsertPt, const MCInstrDesc &II,
120 MachineOperand &RegMO, unsigned OpIdx) {
121 Register Reg = RegMO.getReg();
122 // Assume physical registers are properly constrained.
123 assert(Reg.isVirtual() && "PhysReg not implemented");
124
125 const TargetRegisterClass *OpRC = TII.getRegClass(II, OpIdx);
126 // Some of the target independent instructions, like COPY, may not impose any
127 // register class constraints on some of their operands: If it's a use, we can
128 // skip constraining as the instruction defining the register would constrain
129 // it.
130
131 if (OpRC) {
132 // Obtain the RC from incoming regbank if it is a proper sub-class. Operands
133 // can have multiple regbanks for a superclass that combine different
134 // register types (E.g., AMDGPU's VGPR and AGPR). The regbank ambiguity
135 // resolved by targets during regbankselect should not be overridden.
136 if (const auto *SubRC = TRI.getCommonSubClass(
137 OpRC, TRI.getConstrainedRegClassForReg(Reg, MRI)))
138 OpRC = SubRC;
139
140 OpRC = TRI.getAllocatableClass(OpRC);
141 }
142
143 if (!OpRC) {
144 assert((!isTargetSpecificOpcode(II.getOpcode()) || RegMO.isUse()) &&
145 "Register class constraint is required unless either the "
146 "instruction is target independent or the operand is a use");
147 // FIXME: Just bailing out like this here could be not enough, unless we
148 // expect the users of this function to do the right thing for PHIs and
149 // COPY:
150 // v1 = COPY v0
151 // v2 = COPY v1
152 // v1 here may end up not being constrained at all. Please notice that to
153 // reproduce the issue we likely need a destination pattern of a selection
154 // rule producing such extra copies, not just an input GMIR with them as
155 // every existing target using selectImpl handles copies before calling it
156 // and they never reach this function.
157 return Reg;
158 }
159 return constrainOperandRegClass(MF, TRI, MRI, TII, RBI, InsertPt, *OpRC,
160 RegMO);
161}
162
164 const TargetInstrInfo &TII,
165 const TargetRegisterInfo &TRI,
166 const RegisterBankInfo &RBI) {
167 assert(!isPreISelGenericOpcode(I.getOpcode()) &&
168 "A selected instruction is expected");
169 MachineBasicBlock &MBB = *I.getParent();
170 MachineFunction &MF = *MBB.getParent();
172
173 for (unsigned OpI = 0, OpE = I.getNumExplicitOperands(); OpI != OpE; ++OpI) {
174 MachineOperand &MO = I.getOperand(OpI);
175
176 // There's nothing to be done on non-register operands.
177 if (!MO.isReg())
178 continue;
179
180 LLVM_DEBUG(dbgs() << "Converting operand: " << MO << '\n');
181
182 Register Reg = MO.getReg();
183 // Physical registers don't need to be constrained.
184 if (Reg.isPhysical())
185 continue;
186
187 // Register operands with a value of 0 (e.g. predicate operands) don't need
188 // to be constrained.
189 if (Reg == 0)
190 continue;
191
192 // If the operand is a vreg, we should constrain its regclass, and only
193 // insert COPYs if that's impossible.
194 // constrainOperandRegClass does that for us.
195 constrainOperandRegClass(MF, TRI, MRI, TII, RBI, I, I.getDesc(), MO, OpI);
196
197 // Tie uses to defs as indicated in MCInstrDesc if this hasn't already been
198 // done.
199 if (MO.isUse()) {
200 int DefIdx = I.getDesc().getOperandConstraint(OpI, MCOI::TIED_TO);
201 if (DefIdx != -1 && !I.isRegTiedToUseOperand(DefIdx))
202 I.tieOperands(DefIdx, OpI);
203 }
204 }
205}
206
209 // Give up if either DstReg or SrcReg is a physical register.
210 if (DstReg.isPhysical() || SrcReg.isPhysical())
211 return false;
212 // Give up if the types don't match.
213 if (MRI.getType(DstReg) != MRI.getType(SrcReg))
214 return false;
215 // Replace if either DstReg has no constraints or the register
216 // constraints match.
217 const auto &DstRBC = MRI.getRegClassOrRegBank(DstReg);
218 if (!DstRBC || DstRBC == MRI.getRegClassOrRegBank(SrcReg))
219 return true;
220
221 // Otherwise match if the Src is already a regclass that is covered by the Dst
222 // RegBank.
223 return isa<const RegisterBank *>(DstRBC) && MRI.getRegClassOrNull(SrcReg) &&
224 cast<const RegisterBank *>(DstRBC)->covers(
225 *MRI.getRegClassOrNull(SrcReg));
226}
227
229 const MachineRegisterInfo &MRI) {
230 // Instructions without side-effects are dead iff they only define dead regs.
231 // This function is hot and this loop returns early in the common case,
232 // so only perform additional checks before this if absolutely necessary.
233 for (const auto &MO : MI.all_defs()) {
234 Register Reg = MO.getReg();
235 if (Reg.isPhysical() || !MRI.use_nodbg_empty(Reg))
236 return false;
237 }
238 return MI.wouldBeTriviallyDead();
239}
240
242 MachineFunction &MF,
245 bool IsGlobalISelAbortEnabled =
247 bool IsFatal = Severity == DS_Error && IsGlobalISelAbortEnabled;
248 // Print the function name explicitly if we don't have a debug location (which
249 // makes the diagnostic less useful) or if we're going to emit a raw error.
250 if (!R.getLocation().isValid() || IsFatal)
251 R << (" (in function: " + MF.getName() + ")").str();
252
253 if (IsFatal)
254 reportFatalUsageError(Twine(R.getMsg()));
255 else
256 MORE.emit(R);
257}
258
264
271
274 const char *PassName, StringRef Msg,
275 const MachineInstr &MI) {
276 MachineOptimizationRemarkMissed R(PassName, "GISelFailure: ",
277 MI.getDebugLoc(), MI.getParent());
278 R << Msg;
279 // Printing MI is expensive; only do it if expensive remarks are enabled.
281 MORE.allowExtraAnalysis(PassName))
282 R << ": " << ore::MNV("Inst", MI);
283 reportGISelFailure(MF, MORE, R);
284}
285
286unsigned llvm::getInverseGMinMaxOpcode(unsigned MinMaxOpc) {
287 switch (MinMaxOpc) {
288 case TargetOpcode::G_SMIN:
289 return TargetOpcode::G_SMAX;
290 case TargetOpcode::G_SMAX:
291 return TargetOpcode::G_SMIN;
292 case TargetOpcode::G_UMIN:
293 return TargetOpcode::G_UMAX;
294 case TargetOpcode::G_UMAX:
295 return TargetOpcode::G_UMIN;
296 default:
297 llvm_unreachable("unrecognized opcode");
298 }
299}
300
301std::optional<APInt> llvm::getIConstantVRegVal(Register VReg,
302 const MachineRegisterInfo &MRI) {
303 std::optional<ValueAndVReg> ValAndVReg = getIConstantVRegValWithLookThrough(
304 VReg, MRI, /*LookThroughInstrs*/ false);
305 assert((!ValAndVReg || ValAndVReg->VReg == VReg) &&
306 "Value found while looking through instrs");
307 if (!ValAndVReg)
308 return std::nullopt;
309 return ValAndVReg->Value;
310}
311
313 const MachineRegisterInfo &MRI) {
314 MachineInstr *Const = MRI.getVRegDef(Reg);
315 assert((Const && Const->getOpcode() == TargetOpcode::G_CONSTANT) &&
316 "expected a G_CONSTANT on Reg");
317 return Const->getOperand(1).getCImm()->getValue();
318}
319
320std::optional<int64_t>
322 std::optional<APInt> Val = getIConstantVRegVal(VReg, MRI);
323 if (Val && Val->getBitWidth() <= 64)
324 return Val->getSExtValue();
325 return std::nullopt;
326}
327
328namespace {
329
330// This function is used in many places, and as such, it has some
331// micro-optimizations to try and make it as fast as it can be.
332//
333// - We use template arguments to avoid an indirect call caused by passing a
334// function_ref/std::function
335// - GetAPCstValue does not return std::optional<APInt> as that's expensive.
336// Instead it returns true/false and places the result in a pre-constructed
337// APInt.
338//
339// Please change this function carefully and benchmark your changes.
340template <bool (*IsConstantOpcode)(const MachineInstr *),
341 bool (*GetAPCstValue)(const MachineInstr *MI, APInt &)>
342std::optional<ValueAndVReg>
343getConstantVRegValWithLookThrough(Register VReg, const MachineRegisterInfo &MRI,
344 bool LookThroughInstrs = true,
345 bool LookThroughAnyExt = false) {
348
349 while ((MI = MRI.getVRegDef(VReg)) && !IsConstantOpcode(MI) &&
350 LookThroughInstrs) {
351 switch (MI->getOpcode()) {
352 case TargetOpcode::G_ANYEXT:
353 if (!LookThroughAnyExt)
354 return std::nullopt;
355 [[fallthrough]];
356 case TargetOpcode::G_TRUNC:
357 case TargetOpcode::G_SEXT:
358 case TargetOpcode::G_ZEXT:
359 SeenOpcodes.push_back(std::make_pair(
360 MI->getOpcode(),
361 MRI.getType(MI->getOperand(0).getReg()).getSizeInBits()));
362 VReg = MI->getOperand(1).getReg();
363 break;
364 case TargetOpcode::COPY:
365 VReg = MI->getOperand(1).getReg();
366 if (VReg.isPhysical())
367 return std::nullopt;
368 break;
369 case TargetOpcode::G_INTTOPTR:
370 VReg = MI->getOperand(1).getReg();
371 break;
372 default:
373 return std::nullopt;
374 }
375 }
376 if (!MI || !IsConstantOpcode(MI))
377 return std::nullopt;
378
379 APInt Val;
380 if (!GetAPCstValue(MI, Val))
381 return std::nullopt;
382 for (auto &Pair : reverse(SeenOpcodes)) {
383 switch (Pair.first) {
384 case TargetOpcode::G_TRUNC:
385 Val = Val.trunc(Pair.second);
386 break;
387 case TargetOpcode::G_ANYEXT:
388 case TargetOpcode::G_SEXT:
389 Val = Val.sext(Pair.second);
390 break;
391 case TargetOpcode::G_ZEXT:
392 Val = Val.zext(Pair.second);
393 break;
394 }
395 }
396
397 return ValueAndVReg{std::move(Val), VReg};
398}
399
400bool isIConstant(const MachineInstr *MI) {
401 if (!MI)
402 return false;
403 return MI->getOpcode() == TargetOpcode::G_CONSTANT;
404}
405
406bool isFConstant(const MachineInstr *MI) {
407 if (!MI)
408 return false;
409 return MI->getOpcode() == TargetOpcode::G_FCONSTANT;
410}
411
412bool isAnyConstant(const MachineInstr *MI) {
413 if (!MI)
414 return false;
415 unsigned Opc = MI->getOpcode();
416 return Opc == TargetOpcode::G_CONSTANT || Opc == TargetOpcode::G_FCONSTANT;
417}
418
419bool getCImmAsAPInt(const MachineInstr *MI, APInt &Result) {
420 const MachineOperand &CstVal = MI->getOperand(1);
421 if (!CstVal.isCImm())
422 return false;
423 Result = CstVal.getCImm()->getValue();
424 return true;
425}
426
427bool getCImmOrFPImmAsAPInt(const MachineInstr *MI, APInt &Result) {
428 const MachineOperand &CstVal = MI->getOperand(1);
429 if (CstVal.isCImm())
430 Result = CstVal.getCImm()->getValue();
431 else if (CstVal.isFPImm())
433 else
434 return false;
435 return true;
436}
437
438} // end anonymous namespace
439
441 Register VReg, const MachineRegisterInfo &MRI, bool LookThroughInstrs) {
442 return getConstantVRegValWithLookThrough<isIConstant, getCImmAsAPInt>(
443 VReg, MRI, LookThroughInstrs);
444}
445
447 Register VReg, const MachineRegisterInfo &MRI, bool LookThroughInstrs,
448 bool LookThroughAnyExt) {
449 return getConstantVRegValWithLookThrough<isAnyConstant,
450 getCImmOrFPImmAsAPInt>(
451 VReg, MRI, LookThroughInstrs, LookThroughAnyExt);
452}
453
454std::optional<FPValueAndVReg> llvm::getFConstantVRegValWithLookThrough(
455 Register VReg, const MachineRegisterInfo &MRI, bool LookThroughInstrs) {
456 auto Reg =
457 getConstantVRegValWithLookThrough<isFConstant, getCImmOrFPImmAsAPInt>(
458 VReg, MRI, LookThroughInstrs);
459 if (!Reg)
460 return std::nullopt;
461
462 unsigned Width = Reg->Value.getBitWidth();
463 LLT Ty = MRI.getType(VReg);
464 if (Ty.isValid())
465 Ty = Ty.getScalarType();
466 // An FP-typed VReg is the format its users read, which a looked-through
467 // G_ZEXT/G_TRUNC round trip can make differ from the G_FCONSTANT's.
468 if (Ty.isFloat() && Ty.getSizeInBits() == Width)
469 return FPValueAndVReg{APFloat(getFltSemanticForLLT(Ty), Reg->Value),
470 Reg->VReg};
471
472 // Width alone can't tell half from bfloat, or identify x87/PPC formats.
473 const fltSemantics &CstSem =
475 if (APFloat::getSizeInBits(CstSem) == Width)
476 return FPValueAndVReg{APFloat(CstSem, Reg->Value), Reg->VReg};
477
478 // Resized by a looked-through G_TRUNC/G_SEXT/G_ZEXT: only the width is left,
479 // and it only identifies IEEE formats.
480 if (Width != 16 && Width != 32 && Width != 64 && Width != 128)
481 return std::nullopt;
482 return FPValueAndVReg{
483 APFloat(getFltSemanticForLLT(LLT::scalar(Width)), Reg->Value), Reg->VReg};
484}
485
486const ConstantFP *
488 MachineInstr *MI = MRI.getVRegDef(VReg);
489 if (TargetOpcode::G_FCONSTANT != MI->getOpcode())
490 return nullptr;
491 return MI->getOperand(1).getFPImm();
492}
493
494std::optional<DefinitionAndSourceRegister>
496 Register DefSrcReg = Reg;
497 // This assumes that the code is in SSA form, so there should only be one
498 // definition.
499 auto DefIt = MRI.def_begin(Reg);
500 if (DefIt == MRI.def_end())
501 return {};
502 MachineOperand &DefOpnd = *DefIt;
503 MachineInstr *DefMI = DefOpnd.getParent();
504 auto DstTy = MRI.getType(DefOpnd.getReg());
505 if (!DstTy.isValid())
506 return std::nullopt;
507 unsigned Opc = DefMI->getOpcode();
508 while (Opc == TargetOpcode::COPY || isPreISelGenericOptimizationHint(Opc)) {
509 Register SrcReg = DefMI->getOperand(1).getReg();
510 auto SrcTy = MRI.getType(SrcReg);
511 if (!SrcTy.isValid())
512 break;
513 DefMI = MRI.getVRegDef(SrcReg);
514 DefSrcReg = SrcReg;
515 Opc = DefMI->getOpcode();
516 }
517 return DefinitionAndSourceRegister{DefMI, DefSrcReg};
518}
519
521 const MachineRegisterInfo &MRI) {
522 std::optional<DefinitionAndSourceRegister> DefSrcReg =
524 return DefSrcReg ? DefSrcReg->MI : nullptr;
525}
526
528 const MachineRegisterInfo &MRI) {
529 std::optional<DefinitionAndSourceRegister> DefSrcReg =
531 return DefSrcReg ? DefSrcReg->Reg : Register();
532}
533
536 MachineIRBuilder &MIRBuilder,
538 for (int i = 0; i < NumParts; ++i)
539 VRegs.push_back(MRI.createGenericVirtualRegister(Ty));
540 MIRBuilder.buildUnmerge(VRegs, Reg);
541}
542
543bool llvm::extractParts(Register Reg, LLT RegTy, LLT MainTy, LLT &LeftoverTy,
545 SmallVectorImpl<Register> &LeftoverRegs,
546 MachineIRBuilder &MIRBuilder,
548 assert(!LeftoverTy.isValid() && "this is an out argument");
549
550 unsigned RegSize = RegTy.getSizeInBits();
551 unsigned MainSize = MainTy.getSizeInBits();
552 unsigned NumParts = RegSize / MainSize;
553 unsigned LeftoverSize = RegSize - NumParts * MainSize;
554
555 // Use an unmerge when possible.
556 if (LeftoverSize == 0) {
557 for (unsigned I = 0; I < NumParts; ++I)
558 VRegs.push_back(MRI.createGenericVirtualRegister(MainTy));
559 MIRBuilder.buildUnmerge(VRegs, Reg);
560 return true;
561 }
562
563 // Try to use unmerge for irregular vector split where possible
564 // For example when splitting a <6 x i32> into <4 x i32> with <2 x i32>
565 // leftover, it becomes:
566 // <2 x i32> %2, <2 x i32>%3, <2 x i32> %4 = G_UNMERGE_VALUE <6 x i32> %1
567 // <4 x i32> %5 = G_CONCAT_VECTOR <2 x i32> %2, <2 x i32> %3
568 if (RegTy.isVector() && MainTy.isVector()) {
569 unsigned RegNumElts = RegTy.getNumElements();
570 unsigned MainNumElts = MainTy.getNumElements();
571 unsigned LeftoverNumElts = RegNumElts % MainNumElts;
572 // If can unmerge to LeftoverTy, do it
573 if (MainNumElts % LeftoverNumElts == 0 &&
574 RegNumElts % LeftoverNumElts == 0 &&
575 RegTy.getScalarSizeInBits() == MainTy.getScalarSizeInBits() &&
576 LeftoverNumElts > 1) {
577 LeftoverTy = LLT::fixed_vector(LeftoverNumElts, RegTy.getElementType());
578
579 // Unmerge the SrcReg to LeftoverTy vectors
580 SmallVector<Register, 4> UnmergeValues;
581 extractParts(Reg, LeftoverTy, RegNumElts / LeftoverNumElts, UnmergeValues,
582 MIRBuilder, MRI);
583
584 // Find how many LeftoverTy makes one MainTy
585 unsigned LeftoverPerMain = MainNumElts / LeftoverNumElts;
586 unsigned NumOfLeftoverVal =
587 ((RegNumElts % MainNumElts) / LeftoverNumElts);
588
589 // Create as many MainTy as possible using unmerged value
590 SmallVector<Register, 4> MergeValues;
591 for (unsigned I = 0; I < UnmergeValues.size() - NumOfLeftoverVal; I++) {
592 MergeValues.push_back(UnmergeValues[I]);
593 if (MergeValues.size() == LeftoverPerMain) {
594 VRegs.push_back(
595 MIRBuilder.buildMergeLikeInstr(MainTy, MergeValues).getReg(0));
596 MergeValues.clear();
597 }
598 }
599 // Populate LeftoverRegs with the leftovers
600 for (unsigned I = UnmergeValues.size() - NumOfLeftoverVal;
601 I < UnmergeValues.size(); I++) {
602 LeftoverRegs.push_back(UnmergeValues[I]);
603 }
604 return true;
605 }
606 }
607 // Perform irregular split. Leftover is last element of RegPieces.
608 if (MainTy.isVector()) {
609 SmallVector<Register, 8> RegPieces;
610 extractVectorParts(Reg, MainTy.getNumElements(), RegPieces, MIRBuilder,
611 MRI);
612 for (unsigned i = 0; i < RegPieces.size() - 1; ++i)
613 VRegs.push_back(RegPieces[i]);
614 LeftoverRegs.push_back(RegPieces[RegPieces.size() - 1]);
615 LeftoverTy = MRI.getType(LeftoverRegs[0]);
616 return true;
617 }
618
619 LeftoverTy = LLT::integer(LeftoverSize);
620 // For irregular sizes, extract the individual parts.
621 for (unsigned I = 0; I != NumParts; ++I) {
622 Register NewReg = MRI.createGenericVirtualRegister(MainTy);
623 VRegs.push_back(NewReg);
624 MIRBuilder.buildExtract(NewReg, Reg, MainSize * I);
625 }
626
627 for (unsigned Offset = MainSize * NumParts; Offset < RegSize;
628 Offset += LeftoverSize) {
629 Register NewReg = MRI.createGenericVirtualRegister(LeftoverTy);
630 LeftoverRegs.push_back(NewReg);
631 MIRBuilder.buildExtract(NewReg, Reg, Offset);
632 }
633
634 return true;
635}
636
637void llvm::extractVectorParts(Register Reg, unsigned NumElts,
639 MachineIRBuilder &MIRBuilder,
641 LLT RegTy = MRI.getType(Reg);
642 assert(RegTy.isVector() && "Expected a vector type");
643
644 LLT EltTy = RegTy.getElementType();
645 LLT NarrowTy = (NumElts == 1) ? EltTy : LLT::fixed_vector(NumElts, EltTy);
646 unsigned RegNumElts = RegTy.getNumElements();
647 unsigned LeftoverNumElts = RegNumElts % NumElts;
648 unsigned NumNarrowTyPieces = RegNumElts / NumElts;
649
650 // Perfect split without leftover
651 if (LeftoverNumElts == 0)
652 return extractParts(Reg, NarrowTy, NumNarrowTyPieces, VRegs, MIRBuilder,
653 MRI);
654
655 // Irregular split. Provide direct access to all elements for artifact
656 // combiner using unmerge to elements. Then build vectors with NumElts
657 // elements. Remaining element(s) will be (used to build vector) Leftover.
659 extractParts(Reg, EltTy, RegNumElts, Elts, MIRBuilder, MRI);
660
661 unsigned Offset = 0;
662 // Requested sub-vectors of NarrowTy.
663 for (unsigned i = 0; i < NumNarrowTyPieces; ++i, Offset += NumElts) {
664 ArrayRef<Register> Pieces(&Elts[Offset], NumElts);
665 VRegs.push_back(MIRBuilder.buildMergeLikeInstr(NarrowTy, Pieces).getReg(0));
666 }
667
668 // Leftover element(s).
669 if (LeftoverNumElts == 1) {
670 VRegs.push_back(Elts[Offset]);
671 } else {
672 LLT LeftoverTy = LLT::fixed_vector(LeftoverNumElts, EltTy);
673 ArrayRef<Register> Pieces(&Elts[Offset], LeftoverNumElts);
674 VRegs.push_back(
675 MIRBuilder.buildMergeLikeInstr(LeftoverTy, Pieces).getReg(0));
676 }
677}
678
680 const MachineRegisterInfo &MRI) {
682 return DefMI && DefMI->getOpcode() == Opcode ? DefMI : nullptr;
683}
684
685std::optional<APInt> llvm::ConstantFoldBinOp(unsigned Opcode,
686 const Register Op1,
687 const Register Op2,
688 const MachineRegisterInfo &MRI) {
689 auto MaybeOp2Cst = getAnyConstantVRegValWithLookThrough(Op2, MRI, false);
690 if (!MaybeOp2Cst)
691 return std::nullopt;
692
693 auto MaybeOp1Cst = getAnyConstantVRegValWithLookThrough(Op1, MRI, false);
694 if (!MaybeOp1Cst)
695 return std::nullopt;
696
697 const APInt &C1 = MaybeOp1Cst->Value;
698 const APInt &C2 = MaybeOp2Cst->Value;
699 switch (Opcode) {
700 default:
701 break;
702 case TargetOpcode::G_ADD:
703 return C1 + C2;
704 case TargetOpcode::G_PTR_ADD:
705 // Types can be of different width here.
706 // Result needs to be the same width as C1, so trunc or sext C2.
707 return C1 + C2.sextOrTrunc(C1.getBitWidth());
708 case TargetOpcode::G_AND:
709 return C1 & C2;
710 case TargetOpcode::G_ASHR:
711 return C1.ashr(C2);
712 case TargetOpcode::G_LSHR:
713 return C1.lshr(C2);
714 case TargetOpcode::G_MUL:
715 return C1 * C2;
716 case TargetOpcode::G_OR:
717 return C1 | C2;
718 case TargetOpcode::G_SHL:
719 return C1 << C2;
720 case TargetOpcode::G_SUB:
721 return C1 - C2;
722 case TargetOpcode::G_XOR:
723 return C1 ^ C2;
724 case TargetOpcode::G_UDIV:
725 if (!C2.getBoolValue())
726 break;
727 return C1.udiv(C2);
728 case TargetOpcode::G_SDIV:
729 if (!C2.getBoolValue())
730 break;
731 return C1.sdiv(C2);
732 case TargetOpcode::G_UREM:
733 if (!C2.getBoolValue())
734 break;
735 return C1.urem(C2);
736 case TargetOpcode::G_SREM:
737 if (!C2.getBoolValue())
738 break;
739 return C1.srem(C2);
740 case TargetOpcode::G_SMIN:
741 return APIntOps::smin(C1, C2);
742 case TargetOpcode::G_SMAX:
743 return APIntOps::smax(C1, C2);
744 case TargetOpcode::G_UMIN:
745 return APIntOps::umin(C1, C2);
746 case TargetOpcode::G_UMAX:
747 return APIntOps::umax(C1, C2);
748 }
749
750 return std::nullopt;
751}
752
753std::optional<APFloat>
754llvm::ConstantFoldFPBinOp(unsigned Opcode, const Register Op1,
755 const Register Op2, const MachineRegisterInfo &MRI) {
756 const ConstantFP *Op2Cst = getConstantFPVRegVal(Op2, MRI);
757 if (!Op2Cst)
758 return std::nullopt;
759
760 const ConstantFP *Op1Cst = getConstantFPVRegVal(Op1, MRI);
761 if (!Op1Cst)
762 return std::nullopt;
763
764 APFloat C1 = Op1Cst->getValueAPF();
765 const APFloat &C2 = Op2Cst->getValueAPF();
766 switch (Opcode) {
767 case TargetOpcode::G_FADD:
769 return C1;
770 case TargetOpcode::G_FSUB:
771 C1.subtract(C2, APFloat::rmNearestTiesToEven);
772 return C1;
773 case TargetOpcode::G_FMUL:
774 C1.multiply(C2, APFloat::rmNearestTiesToEven);
775 return C1;
776 case TargetOpcode::G_FDIV:
778 return C1;
779 case TargetOpcode::G_FREM:
780 C1.mod(C2);
781 return C1;
782 case TargetOpcode::G_FCOPYSIGN:
783 C1.copySign(C2);
784 return C1;
785 case TargetOpcode::G_FMINNUM:
786 return minnum(C1, C2);
787 case TargetOpcode::G_FMAXNUM:
788 return maxnum(C1, C2);
789 case TargetOpcode::G_FMINIMUM:
790 return minimum(C1, C2);
791 case TargetOpcode::G_FMAXIMUM:
792 return maximum(C1, C2);
793 case TargetOpcode::G_FMINIMUMNUM:
794 return minimumnum(C1, C2);
795 case TargetOpcode::G_FMAXIMUMNUM:
796 return maximumnum(C1, C2);
797 case TargetOpcode::G_FMINNUM_IEEE:
798 case TargetOpcode::G_FMAXNUM_IEEE:
799 // FIXME: These operations were unfortunately named. fminnum/fmaxnum do not
800 // follow the IEEE behavior for signaling nans and follow libm's fmin/fmax,
801 // and currently there isn't a nice wrapper in APFloat for the version with
802 // correct snan handling.
803 break;
804 default:
805 break;
806 }
807
808 return std::nullopt;
809}
810
812 const MachineRegisterInfo &MRI) {
813 if (auto *BV = getOpcodeDef<GBuildVector>(Reg, MRI))
814 return BV;
815
816 auto *Bitcast = getOpcodeDef(TargetOpcode::G_BITCAST, Reg, MRI);
817 if (!Bitcast)
818 return nullptr;
819
820 auto [Dst, DstTy, Src, SrcTy] = Bitcast->getFirst2RegLLTs();
821 if (!SrcTy.isVector() || !DstTy.isVector())
822 return nullptr;
823 if (SrcTy.getElementCount() != DstTy.getElementCount())
824 return nullptr;
825 if (SrcTy.getScalarSizeInBits() != DstTy.getScalarSizeInBits())
826 return nullptr;
827
828 return getOpcodeDef<GBuildVector>(Src, MRI);
829}
830
832llvm::ConstantFoldVectorBinop(unsigned Opcode, const Register Op1,
833 const Register Op2,
834 const MachineRegisterInfo &MRI) {
835 auto *SrcVec2 = getBuildVectorLikeDef(Op2, MRI);
836 if (!SrcVec2)
837 return SmallVector<APInt>();
838
839 auto *SrcVec1 = getBuildVectorLikeDef(Op1, MRI);
840 if (!SrcVec1)
841 return SmallVector<APInt>();
842
843 SmallVector<APInt> FoldedElements;
844 for (unsigned Idx = 0, E = SrcVec1->getNumSources(); Idx < E; ++Idx) {
845 auto MaybeCst = ConstantFoldBinOp(Opcode, SrcVec1->getSourceReg(Idx),
846 SrcVec2->getSourceReg(Idx), MRI);
847 if (!MaybeCst)
848 return SmallVector<APInt>();
849 FoldedElements.push_back(*MaybeCst);
850 }
851 return FoldedElements;
852}
853
855llvm::ConstantFoldVectorFPBinop(unsigned Opcode, const Register Op1,
856 const Register Op2,
857 const MachineRegisterInfo &MRI) {
858 // Unlike the integer fold, don't look through G_BITCAST: it may reinterpret
859 // the element bits in a different FP semantics format (e.g. bf16 to f16).
860 auto *SrcVec2 = getOpcodeDef<GBuildVector>(Op2, MRI);
861 if (!SrcVec2)
862 return {};
863
864 auto *SrcVec1 = getOpcodeDef<GBuildVector>(Op1, MRI);
865 if (!SrcVec1)
866 return {};
867
868 SmallVector<APFloat> FoldedElements;
869 for (unsigned Idx = 0, E = SrcVec1->getNumSources(); Idx < E; ++Idx) {
870 auto MaybeCst = ConstantFoldFPBinOp(Opcode, SrcVec1->getSourceReg(Idx),
871 SrcVec2->getSourceReg(Idx), MRI);
872 if (!MaybeCst)
873 return {};
874 FoldedElements.push_back(*MaybeCst);
875 }
876 return FoldedElements;
877}
878
880 const MachinePointerInfo &MPO) {
883 MachineFrameInfo &MFI = MF.getFrameInfo();
884 return commonAlignment(MFI.getObjectAlign(FSPV->getFrameIndex()),
885 MPO.Offset);
886 }
887
888 if (const Value *V = dyn_cast_if_present<const Value *>(MPO.V)) {
889 const Module *M = MF.getFunction().getParent();
890 return V->getPointerAlignment(M->getDataLayout());
891 }
892
893 return Align(1);
894}
895
897 const TargetInstrInfo &TII,
898 MCRegister PhysReg,
899 const TargetRegisterClass &RC,
900 const DebugLoc &DL, LLT RegTy) {
901 MachineBasicBlock &EntryMBB = MF.front();
903 Register LiveIn = MRI.getLiveInVirtReg(PhysReg);
904 if (LiveIn) {
905 MachineInstr *Def = MRI.getVRegDef(LiveIn);
906 if (Def) {
907 // FIXME: Should the verifier check this is in the entry block?
908 assert(Def->getParent() == &EntryMBB && "live-in copy not in entry block");
909 return LiveIn;
910 }
911
912 // It's possible the incoming argument register and copy was added during
913 // lowering, but later deleted due to being/becoming dead. If this happens,
914 // re-insert the copy.
915 } else {
916 // The live in register was not present, so add it.
917 LiveIn = MF.addLiveIn(PhysReg, &RC);
918 if (RegTy.isValid())
919 MRI.setType(LiveIn, RegTy);
920 }
921
922 BuildMI(EntryMBB, EntryMBB.begin(), DL, TII.get(TargetOpcode::COPY), LiveIn)
923 .addReg(PhysReg);
924 if (!EntryMBB.isLiveIn(PhysReg))
925 EntryMBB.addLiveIn(PhysReg);
926 return LiveIn;
927}
928
929std::optional<APInt> llvm::ConstantFoldExtOp(unsigned Opcode,
930 const Register Op1, uint64_t Imm,
931 const MachineRegisterInfo &MRI) {
932 auto MaybeOp1Cst = getIConstantVRegVal(Op1, MRI);
933 if (MaybeOp1Cst) {
934 switch (Opcode) {
935 default:
936 break;
937 case TargetOpcode::G_SEXT_INREG: {
938 LLT Ty = MRI.getType(Op1);
939 return MaybeOp1Cst->trunc(Imm).sext(Ty.getScalarSizeInBits());
940 }
941 }
942 }
943 return std::nullopt;
944}
945
946std::optional<APInt> llvm::ConstantFoldCastOp(unsigned Opcode, LLT DstTy,
947 const Register Op0,
948 const MachineRegisterInfo &MRI) {
949 std::optional<APInt> Val = getIConstantVRegVal(Op0, MRI);
950 if (!Val)
951 return Val;
952
953 const unsigned DstSize = DstTy.getScalarSizeInBits();
954
955 switch (Opcode) {
956 case TargetOpcode::G_SEXT:
957 return Val->sext(DstSize);
958 case TargetOpcode::G_ZEXT:
959 case TargetOpcode::G_ANYEXT:
960 // TODO: DAG considers target preference when constant folding any_extend.
961 return Val->zext(DstSize);
962 default:
963 break;
964 }
965
966 llvm_unreachable("unexpected cast opcode to constant fold");
967}
968
969std::optional<APFloat>
970llvm::ConstantFoldIntToFloat(unsigned Opcode, LLT DstTy, Register Src,
971 const MachineRegisterInfo &MRI) {
972 assert(Opcode == TargetOpcode::G_SITOFP || Opcode == TargetOpcode::G_UITOFP);
973 if (auto MaybeSrcVal = getIConstantVRegVal(Src, MRI)) {
974 APFloat DstVal(getFltSemanticForLLT(DstTy));
975 DstVal.convertFromAPInt(*MaybeSrcVal, Opcode == TargetOpcode::G_SITOFP,
977 return DstVal;
978 }
979 return std::nullopt;
980}
981
983llvm::ConstantFoldUnaryIntOp(unsigned Opcode, LLT DstTy, Register Src,
984 const MachineRegisterInfo &MRI) {
985 unsigned EltBits = DstTy.getScalarSizeInBits();
986 auto Fold = [Opcode, EltBits](const APInt &V) -> APInt {
987 switch (Opcode) {
988 case TargetOpcode::G_CTLZ:
989 case TargetOpcode::G_CTLZ_ZERO_POISON:
990 return APInt(EltBits, V.countl_zero());
991 case TargetOpcode::G_CTTZ:
992 case TargetOpcode::G_CTTZ_ZERO_POISON:
993 return APInt(EltBits, V.countr_zero());
994 case TargetOpcode::G_CTPOP:
995 return APInt(EltBits, V.popcount());
996 case TargetOpcode::G_ABS:
997 return V.abs();
998 case TargetOpcode::G_BSWAP:
999 return V.byteSwap();
1000 case TargetOpcode::G_BITREVERSE:
1001 return V.reverseBits();
1002 }
1003 llvm_unreachable("unexpected opcode in ConstantFoldUnaryIntOp");
1004 };
1005
1006 auto tryFoldScalar = [&](Register R) -> std::optional<APInt> {
1007 if (auto MaybeCst = getIConstantVRegVal(R, MRI))
1008 return Fold(*MaybeCst);
1009 return std::nullopt;
1010 };
1011 if (MRI.getType(Src).isVector()) {
1012 auto *BV = getOpcodeDef<GBuildVector>(Src, MRI);
1013 if (!BV)
1014 return {};
1016 for (unsigned SrcIdx = 0; SrcIdx < BV->getNumSources(); ++SrcIdx) {
1017 if (auto MaybeFold = tryFoldScalar(BV->getSourceReg(SrcIdx))) {
1018 Folded.emplace_back(std::move(*MaybeFold));
1019 continue;
1020 }
1021 return {};
1022 }
1023 return Folded;
1024 }
1025 if (auto MaybeCst = tryFoldScalar(Src))
1026 return {std::move(*MaybeCst)};
1027 return {};
1028}
1029
1031llvm::ConstantFoldUnaryFPOp(unsigned Opcode, LLT DstTy, Register Src,
1032 const MachineRegisterInfo &MRI) {
1033 LLT DstEltTy = DstTy.getScalarType();
1034 auto Fold = [Opcode, DstEltTy,
1035 &MRI](const APFloat &V) -> std::optional<APFloat> {
1036 APFloat Result(V);
1037 bool Unused;
1038 switch (Opcode) {
1039 case TargetOpcode::G_FNEG:
1040 Result.changeSign();
1041 return Result;
1042 case TargetOpcode::G_FABS:
1043 Result.clearSign();
1044 return Result;
1045 case TargetOpcode::G_FCEIL:
1046 Result.roundToIntegral(APFloat::rmTowardPositive);
1047 return Result;
1048 case TargetOpcode::G_FFLOOR:
1049 Result.roundToIntegral(APFloat::rmTowardNegative);
1050 return Result;
1051 case TargetOpcode::G_INTRINSIC_TRUNC:
1052 Result.roundToIntegral(APFloat::rmTowardZero);
1053 return Result;
1054 case TargetOpcode::G_INTRINSIC_ROUND:
1055 Result.roundToIntegral(APFloat::rmNearestTiesToAway);
1056 return Result;
1057 case TargetOpcode::G_INTRINSIC_ROUNDEVEN:
1058 case TargetOpcode::G_FRINT:
1059 case TargetOpcode::G_FNEARBYINT:
1060 Result.roundToIntegral(APFloat::rmNearestTiesToEven);
1061 return Result;
1062 case TargetOpcode::G_FPEXT:
1063 case TargetOpcode::G_FPTRUNC:
1064 Result.convert(getFltSemanticForLLT(DstEltTy),
1066 return Result;
1067 case TargetOpcode::G_FSQRT:
1068 case TargetOpcode::G_FLOG2: {
1069 // ConstantFoldFP only accepts IEEE-like formats up to double. fp128,
1070 // x86_fp80, and ppc_fp128 are not supported.
1071 const fltSemantics &FltSem = getFltSemanticForLLT(DstEltTy);
1072 if (!APFloat::isIEEELikeFP(FltSem) || APFloat::getSizeInBits(FltSem) > 64)
1073 return std::nullopt;
1075 MRI.getMF().getFunction().getContext(), FltSem);
1076 Constant *C = Opcode == TargetOpcode::G_FSQRT
1077 ? ConstantFoldFP(sqrt, V, Ty)
1078 : ConstantFoldFP(log2, V, Ty);
1079 if (!C)
1080 return std::nullopt;
1081 return cast<ConstantFP>(C)->getValueAPF();
1082 }
1083 default:
1084 llvm_unreachable("unexpected opcode in ConstantFoldUnaryFPOp");
1085 }
1086 };
1087
1088 auto tryFoldScalar = [&](Register R) -> std::optional<APFloat> {
1089 if (const ConstantFP *Cst = getConstantFPVRegVal(R, MRI))
1090 return Fold(Cst->getValueAPF());
1091 return std::nullopt;
1092 };
1093 if (MRI.getType(Src).isVector()) {
1094 auto *BV = getOpcodeDef<GBuildVector>(Src, MRI);
1095 if (!BV)
1096 return {};
1098 for (unsigned SrcIdx = 0; SrcIdx < BV->getNumSources(); ++SrcIdx) {
1099 if (auto MaybeFold = tryFoldScalar(BV->getSourceReg(SrcIdx))) {
1100 Folded.emplace_back(std::move(*MaybeFold));
1101 continue;
1102 }
1103 return {};
1104 }
1105 return Folded;
1106 }
1107 if (auto MaybeCst = tryFoldScalar(Src))
1108 return {std::move(*MaybeCst)};
1109 return {};
1110}
1111
1112std::optional<SmallVector<APInt>>
1113llvm::ConstantFoldICmp(unsigned Pred, const Register Op1, const Register Op2,
1114 unsigned DstScalarSizeInBits, unsigned ExtOp,
1115 const MachineRegisterInfo &MRI) {
1116 assert(ExtOp == TargetOpcode::G_SEXT || ExtOp == TargetOpcode::G_ZEXT ||
1117 ExtOp == TargetOpcode::G_ANYEXT);
1118
1119 const LLT Ty = MRI.getType(Op1);
1120
1121 auto GetICmpResultCst = [&](bool IsTrue) {
1122 if (IsTrue)
1123 return ExtOp == TargetOpcode::G_SEXT
1124 ? APInt::getAllOnes(DstScalarSizeInBits)
1125 : APInt::getOneBitSet(DstScalarSizeInBits, 0);
1126 return APInt::getZero(DstScalarSizeInBits);
1127 };
1128
1129 auto TryFoldScalar = [&](Register LHS, Register RHS) -> std::optional<APInt> {
1130 auto RHSCst = getIConstantVRegVal(RHS, MRI);
1131 if (!RHSCst)
1132 return std::nullopt;
1133 auto LHSCst = getIConstantVRegVal(LHS, MRI);
1134 if (!LHSCst)
1135 return std::nullopt;
1136
1137 switch (Pred) {
1139 return GetICmpResultCst(LHSCst->eq(*RHSCst));
1141 return GetICmpResultCst(LHSCst->ne(*RHSCst));
1143 return GetICmpResultCst(LHSCst->ugt(*RHSCst));
1145 return GetICmpResultCst(LHSCst->uge(*RHSCst));
1147 return GetICmpResultCst(LHSCst->ult(*RHSCst));
1149 return GetICmpResultCst(LHSCst->ule(*RHSCst));
1151 return GetICmpResultCst(LHSCst->sgt(*RHSCst));
1153 return GetICmpResultCst(LHSCst->sge(*RHSCst));
1155 return GetICmpResultCst(LHSCst->slt(*RHSCst));
1157 return GetICmpResultCst(LHSCst->sle(*RHSCst));
1158 default:
1159 return std::nullopt;
1160 }
1161 };
1162
1163 SmallVector<APInt> FoldedICmps;
1164
1165 if (Ty.isVector()) {
1166 // Try to constant fold each element.
1167 auto *BV1 = getOpcodeDef<GBuildVector>(Op1, MRI);
1168 auto *BV2 = getOpcodeDef<GBuildVector>(Op2, MRI);
1169 if (!BV1 || !BV2)
1170 return std::nullopt;
1171 assert(BV1->getNumSources() == BV2->getNumSources() && "Invalid vectors");
1172 for (unsigned I = 0; I < BV1->getNumSources(); ++I) {
1173 if (auto MaybeFold =
1174 TryFoldScalar(BV1->getSourceReg(I), BV2->getSourceReg(I))) {
1175 FoldedICmps.emplace_back(*MaybeFold);
1176 continue;
1177 }
1178 return std::nullopt;
1179 }
1180 return FoldedICmps;
1181 }
1182
1183 if (auto MaybeCst = TryFoldScalar(Op1, Op2)) {
1184 FoldedICmps.emplace_back(*MaybeCst);
1185 return FoldedICmps;
1186 }
1187
1188 return std::nullopt;
1189}
1190
1192 GISelValueTracking *VT, bool OrNegative,
1193 bool OrZero) {
1194 std::optional<DefinitionAndSourceRegister> DefSrcReg =
1196 if (!DefSrcReg)
1197 return false;
1198
1199 const MachineInstr &MI = *DefSrcReg->MI;
1200 const LLT Ty = MRI.getType(Reg);
1201
1202 auto IsPow2 = [OrNegative, OrZero](const APInt &V) {
1203 return V.isPowerOf2() || (OrNegative && V.isNegatedPowerOf2()) ||
1204 (OrZero && V.isZero());
1205 };
1206
1207 switch (MI.getOpcode()) {
1208 case TargetOpcode::G_CONSTANT: {
1209 unsigned BitWidth = Ty.getScalarSizeInBits();
1210 const ConstantInt *CI = MI.getOperand(1).getCImm();
1211 return IsPow2(CI->getValue().zextOrTrunc(BitWidth));
1212 }
1213 case TargetOpcode::G_SHL: {
1214 // A left-shift of a constant one will have exactly one bit set because
1215 // shifting the bit off the end is undefined. Otherwise, shifting a power
1216 // of two (or zero) yields a power of two, or zero, since the bit moves or
1217 // is shifted off the end. That is sufficient with OrZero set, otherwise
1218 // the result must also be known never to be zero.
1219
1220 // TODO: Constant splat
1221 if (auto ConstLHS = getIConstantVRegVal(MI.getOperand(1).getReg(), MRI)) {
1222 if (*ConstLHS == 1)
1223 return true;
1224 }
1225 if (OrZero || (VT && VT->isKnownNeverZero(Reg))) {
1226 if (isKnownToBeAPowerOfTwo(MI.getOperand(1).getReg(), MRI, VT, OrNegative,
1227 OrZero))
1228 return true;
1229 }
1230
1231 break;
1232 }
1233 case TargetOpcode::G_LSHR: {
1234 if (auto ConstLHS = getIConstantVRegVal(MI.getOperand(1).getReg(), MRI)) {
1235 if (ConstLHS->isSignMask())
1236 return true;
1237 }
1238 // As with G_SHL, the set bit is either moved or shifted off the end.
1239 // OrNegative is not propagated because a logical right shift fills with
1240 // zeros and thus does not preserve negated powers of two.
1241 if (OrZero || (VT && VT->isKnownNeverZero(Reg))) {
1242 if (isKnownToBeAPowerOfTwo(MI.getOperand(1).getReg(), MRI, VT,
1243 /*OrNegative=*/false, OrZero))
1244 return true;
1245 }
1246
1247 break;
1248 }
1249 case TargetOpcode::G_TRUNC: {
1250 // Truncation preserves the lower bits of the operand, so the set bit either
1251 // survives or is cut off, yielding zero.
1252 if (OrZero || (VT && VT->isKnownNeverZero(Reg))) {
1253 if (isKnownToBeAPowerOfTwo(MI.getOperand(1).getReg(), MRI, VT,
1254 /*OrNegative=*/false, OrZero))
1255 return true;
1256 }
1257
1258 break;
1259 }
1260 case TargetOpcode::G_BUILD_VECTOR: {
1261 // TODO: Probably should have a recursion depth guard since you could have
1262 // bitcasted vector elements.
1263 for (const MachineOperand &MO : llvm::drop_begin(MI.operands()))
1264 if (!isKnownToBeAPowerOfTwo(MO.getReg(), MRI, VT, OrNegative, OrZero))
1265 return false;
1266
1267 return true;
1268 }
1269 case TargetOpcode::G_BUILD_VECTOR_TRUNC: {
1270 // Only handle constants since we would need to know if number of leading
1271 // zeros is greater than the truncation amount.
1272 const unsigned BitWidth = Ty.getScalarSizeInBits();
1273 for (const MachineOperand &MO : llvm::drop_begin(MI.operands())) {
1274 auto Const = getIConstantVRegVal(MO.getReg(), MRI);
1275 if (!Const || !IsPow2(Const->zextOrTrunc(BitWidth)))
1276 return false;
1277 }
1278
1279 return true;
1280 }
1281 default:
1282 break;
1283 }
1284
1285 if (!VT)
1286 return false;
1287
1288 // More could be done here, though the above checks are enough
1289 // to handle some common cases.
1290
1291 // Fall back to computeKnownBits to catch other known cases.
1292 KnownBits Known = VT->getKnownBits(Reg);
1293 return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
1294}
1295
1299
1300LLT llvm::getLCMType(LLT OrigTy, LLT TargetTy) {
1301 if (OrigTy.getSizeInBits() == TargetTy.getSizeInBits())
1302 return OrigTy;
1303
1304 if (OrigTy.isVector() && TargetTy.isVector()) {
1305 LLT OrigElt = OrigTy.getElementType();
1306 LLT TargetElt = TargetTy.getElementType();
1307
1308 // TODO: The docstring for this function says the intention is to use this
1309 // function to build MERGE/UNMERGE instructions. It won't be the case that
1310 // we generate a MERGE/UNMERGE between fixed and scalable vector types. We
1311 // could implement getLCMType between the two in the future if there was a
1312 // need, but it is not worth it now as this function should not be used in
1313 // that way.
1314 assert(((OrigTy.isScalableVector() && !TargetTy.isFixedVector()) ||
1315 (OrigTy.isFixedVector() && !TargetTy.isScalableVector())) &&
1316 "getLCMType not implemented between fixed and scalable vectors.");
1317
1318 if (OrigElt.getSizeInBits() == TargetElt.getSizeInBits()) {
1319 int GCDMinElts = std::gcd(OrigTy.getElementCount().getKnownMinValue(),
1320 TargetTy.getElementCount().getKnownMinValue());
1321 // Prefer the original element type.
1322 ElementCount Mul = OrigTy.getElementCount() *
1323 TargetTy.getElementCount().getKnownMinValue();
1324 return LLT::vector(Mul.divideCoefficientBy(GCDMinElts),
1325 OrigTy.getElementType());
1326 }
1327 unsigned LCM = std::lcm(OrigTy.getSizeInBits().getKnownMinValue(),
1328 TargetTy.getSizeInBits().getKnownMinValue());
1329 return LLT::vector(
1330 ElementCount::get(LCM / OrigElt.getSizeInBits(), OrigTy.isScalable()),
1331 OrigElt);
1332 }
1333
1334 // One type is scalar, one type is vector
1335 if (OrigTy.isVector() || TargetTy.isVector()) {
1336 LLT VecTy = OrigTy.isVector() ? OrigTy : TargetTy;
1337 LLT ScalarTy = OrigTy.isVector() ? TargetTy : OrigTy;
1338 LLT EltTy = VecTy.getElementType();
1339 LLT OrigEltTy = OrigTy.isVector() ? OrigTy.getElementType() : OrigTy;
1340
1341 // Prefer scalar type from OrigTy.
1342 if (EltTy.getSizeInBits() == ScalarTy.getSizeInBits())
1343 return LLT::vector(VecTy.getElementCount(), OrigEltTy);
1344
1345 // Different size scalars. Create vector with the same total size.
1346 // LCM will take fixed/scalable from VecTy.
1347 unsigned LCM = std::lcm(EltTy.getSizeInBits().getFixedValue() *
1349 ScalarTy.getSizeInBits().getFixedValue());
1350 // Prefer type from OrigTy
1351 return LLT::vector(ElementCount::get(LCM / OrigEltTy.getSizeInBits(),
1352 VecTy.getElementCount().isScalable()),
1353 OrigEltTy);
1354 }
1355
1356 // At this point, both types are scalars of different size
1357 unsigned LCM = std::lcm(OrigTy.getSizeInBits().getFixedValue(),
1358 TargetTy.getSizeInBits().getFixedValue());
1359 // Preserve pointer types.
1360 if (LCM == OrigTy.getSizeInBits())
1361 return OrigTy;
1362 if (LCM == TargetTy.getSizeInBits())
1363 return TargetTy;
1364 return LLT::scalar(LCM);
1365}
1366
1367LLT llvm::getCoverTy(LLT OrigTy, LLT TargetTy) {
1368
1369 if ((OrigTy.isScalableVector() && TargetTy.isFixedVector()) ||
1370 (OrigTy.isFixedVector() && TargetTy.isScalableVector()))
1372 "getCoverTy not implemented between fixed and scalable vectors.");
1373
1374 if (!OrigTy.isVector() || !TargetTy.isVector() || OrigTy == TargetTy ||
1375 (OrigTy.getScalarSizeInBits() != TargetTy.getScalarSizeInBits()))
1376 return getLCMType(OrigTy, TargetTy);
1377
1378 unsigned OrigTyNumElts = OrigTy.getElementCount().getKnownMinValue();
1379 unsigned TargetTyNumElts = TargetTy.getElementCount().getKnownMinValue();
1380 if (OrigTyNumElts % TargetTyNumElts == 0)
1381 return OrigTy;
1382
1383 unsigned NumElts = alignTo(OrigTyNumElts, TargetTyNumElts);
1385 OrigTy.getElementType());
1386}
1387
1388LLT llvm::getGCDType(LLT OrigTy, LLT TargetTy) {
1389 if (OrigTy.getSizeInBits() == TargetTy.getSizeInBits())
1390 return OrigTy;
1391
1392 if (OrigTy.isVector() && TargetTy.isVector()) {
1393 LLT OrigElt = OrigTy.getElementType();
1394
1395 // TODO: The docstring for this function says the intention is to use this
1396 // function to build MERGE/UNMERGE instructions. It won't be the case that
1397 // we generate a MERGE/UNMERGE between fixed and scalable vector types. We
1398 // could implement getGCDType between the two in the future if there was a
1399 // need, but it is not worth it now as this function should not be used in
1400 // that way.
1401 assert(((OrigTy.isScalableVector() && !TargetTy.isFixedVector()) ||
1402 (OrigTy.isFixedVector() && !TargetTy.isScalableVector())) &&
1403 "getGCDType not implemented between fixed and scalable vectors.");
1404
1405 unsigned GCD = std::gcd(OrigTy.getSizeInBits().getKnownMinValue(),
1406 TargetTy.getSizeInBits().getKnownMinValue());
1407 if (GCD == OrigElt.getSizeInBits())
1409 OrigElt);
1410
1411 // Cannot produce original element type, but both have vscale in common.
1412 if (GCD < OrigElt.getSizeInBits())
1414 GCD);
1415
1416 return LLT::vector(
1418 OrigTy.isScalable()),
1419 OrigElt);
1420 }
1421
1422 // If one type is vector and the element size matches the scalar size, then
1423 // the gcd is the scalar type.
1424 if (OrigTy.isVector() &&
1425 OrigTy.getElementType().getSizeInBits() == TargetTy.getSizeInBits())
1426 return OrigTy.getElementType();
1427 if (TargetTy.isVector() &&
1428 TargetTy.getElementType().getSizeInBits() == OrigTy.getSizeInBits())
1429 return OrigTy;
1430
1431 // At this point, both types are either scalars of different type or one is a
1432 // vector and one is a scalar. If both types are scalars, the GCD type is the
1433 // GCD between the two scalar sizes. If one is vector and one is scalar, then
1434 // the GCD type is the GCD between the scalar and the vector element size.
1435 LLT OrigScalar = OrigTy.getScalarType();
1436 LLT TargetScalar = TargetTy.getScalarType();
1437 unsigned GCD = std::gcd(OrigScalar.getSizeInBits().getFixedValue(),
1438 TargetScalar.getSizeInBits().getFixedValue());
1439 return LLT::integer(GCD);
1440}
1441
1443 assert(MI.getOpcode() == TargetOpcode::G_SHUFFLE_VECTOR &&
1444 "Only G_SHUFFLE_VECTOR can have a splat index!");
1445 ArrayRef<int> Mask = MI.getOperand(3).getShuffleMask();
1446 auto FirstDefinedIdx = find_if(Mask, [](int Elt) { return Elt >= 0; });
1447
1448 // If all elements are undefined, this shuffle can be considered a splat.
1449 // Return 0 for better potential for callers to simplify.
1450 if (FirstDefinedIdx == Mask.end())
1451 return 0;
1452
1453 // Make sure all remaining elements are either undef or the same
1454 // as the first non-undef value.
1455 int SplatValue = *FirstDefinedIdx;
1456 if (any_of(make_range(std::next(FirstDefinedIdx), Mask.end()),
1457 [&SplatValue](int Elt) { return Elt >= 0 && Elt != SplatValue; }))
1458 return std::nullopt;
1459
1460 return SplatValue;
1461}
1462
1463static bool isBuildVectorOp(unsigned Opcode) {
1464 return Opcode == TargetOpcode::G_BUILD_VECTOR ||
1465 Opcode == TargetOpcode::G_BUILD_VECTOR_TRUNC;
1466}
1467
1468namespace {
1469
1470std::optional<ValueAndVReg> getAnyConstantSplat(Register VReg,
1471 const MachineRegisterInfo &MRI,
1472 bool AllowUndef) {
1474 if (!MI)
1475 return std::nullopt;
1476
1477 bool isConcatVectorsOp = MI->getOpcode() == TargetOpcode::G_CONCAT_VECTORS;
1478 if (!isBuildVectorOp(MI->getOpcode()) && !isConcatVectorsOp)
1479 return std::nullopt;
1480
1481 std::optional<ValueAndVReg> SplatValAndReg;
1482 for (MachineOperand &Op : MI->uses()) {
1483 Register Element = Op.getReg();
1484 // If we have a G_CONCAT_VECTOR, we recursively look into the
1485 // vectors that we're concatenating to see if they're splats.
1486 auto ElementValAndReg =
1487 isConcatVectorsOp
1488 ? getAnyConstantSplat(Element, MRI, AllowUndef)
1490
1491 // If AllowUndef, treat undef as value that will result in a constant splat.
1492 if (!ElementValAndReg) {
1493 if (AllowUndef && mi_match(Element, MRI, m_GImplicitDef()))
1494 continue;
1495 return std::nullopt;
1496 }
1497
1498 // Record splat value
1499 if (!SplatValAndReg)
1500 SplatValAndReg = ElementValAndReg;
1501
1502 // Different constant than the one already recorded, not a constant splat.
1503 if (SplatValAndReg->Value != ElementValAndReg->Value)
1504 return std::nullopt;
1505 }
1506
1507 return SplatValAndReg;
1508}
1509
1510} // end anonymous namespace
1511
1513 const MachineRegisterInfo &MRI,
1514 int64_t SplatValue, bool AllowUndef) {
1515 if (auto SplatValAndReg = getAnyConstantSplat(Reg, MRI, AllowUndef))
1516 return SplatValAndReg->Value.getSExtValue() == SplatValue;
1517
1518 return false;
1519}
1520
1522 const MachineRegisterInfo &MRI,
1523 const APInt &SplatValue,
1524 bool AllowUndef) {
1525 if (auto SplatValAndReg = getAnyConstantSplat(Reg, MRI, AllowUndef)) {
1526 if (SplatValAndReg->Value.getBitWidth() < SplatValue.getBitWidth())
1527 return APInt::isSameValue(
1528 SplatValAndReg->Value.sext(SplatValue.getBitWidth()), SplatValue);
1529 return APInt::isSameValue(
1530 SplatValAndReg->Value,
1531 SplatValue.sext(SplatValAndReg->Value.getBitWidth()));
1532 }
1533
1534 return false;
1535}
1536
1538 const MachineRegisterInfo &MRI,
1539 int64_t SplatValue, bool AllowUndef) {
1540 return isBuildVectorConstantSplat(MI.getOperand(0).getReg(), MRI, SplatValue,
1541 AllowUndef);
1542}
1543
1545 const MachineRegisterInfo &MRI,
1546 const APInt &SplatValue,
1547 bool AllowUndef) {
1548 return isBuildVectorConstantSplat(MI.getOperand(0).getReg(), MRI, SplatValue,
1549 AllowUndef);
1550}
1551
1552std::optional<APInt>
1554 if (auto SplatValAndReg =
1555 getAnyConstantSplat(Reg, MRI, /* AllowUndef */ false)) {
1556 if (std::optional<ValueAndVReg> ValAndVReg =
1557 getIConstantVRegValWithLookThrough(SplatValAndReg->VReg, MRI))
1558 return ValAndVReg->Value;
1559 }
1560
1561 return std::nullopt;
1562}
1563
1564std::optional<APInt>
1566 const MachineRegisterInfo &MRI) {
1567 return getIConstantSplatVal(MI.getOperand(0).getReg(), MRI);
1568}
1569
1570std::optional<int64_t>
1572 const MachineRegisterInfo &MRI) {
1573 if (auto SplatValAndReg =
1574 getAnyConstantSplat(Reg, MRI, /* AllowUndef */ false))
1575 return getIConstantVRegSExtVal(SplatValAndReg->VReg, MRI);
1576 return std::nullopt;
1577}
1578
1579std::optional<int64_t>
1581 const MachineRegisterInfo &MRI) {
1582 return getIConstantSplatSExtVal(MI.getOperand(0).getReg(), MRI);
1583}
1584
1585std::optional<FPValueAndVReg>
1587 bool AllowUndef) {
1588 if (auto SplatValAndReg = getAnyConstantSplat(VReg, MRI, AllowUndef))
1589 return getFConstantVRegValWithLookThrough(SplatValAndReg->VReg, MRI);
1590 return std::nullopt;
1591}
1592
1594 const MachineRegisterInfo &MRI,
1595 bool AllowUndef) {
1596 return isBuildVectorConstantSplat(MI, MRI, 0, AllowUndef);
1597}
1598
1600 const MachineRegisterInfo &MRI,
1601 bool AllowUndef) {
1602 return isBuildVectorConstantSplat(MI, MRI, -1, AllowUndef);
1603}
1604
1605std::optional<Register> llvm::getVectorSplat(const MachineInstr &MI,
1606 const MachineRegisterInfo &MRI) {
1607 unsigned Opc = MI.getOpcode();
1608 if (Opc == TargetOpcode::G_SPLAT_VECTOR)
1609 return MI.getOperand(1).getReg();
1610
1611 if (!isBuildVectorOp(Opc))
1612 return std::nullopt;
1613 auto Reg = MI.getOperand(1).getReg();
1614 if (any_of(drop_begin(MI.operands(), 2),
1615 [&Reg](const MachineOperand &Op) { return Op.getReg() != Reg; }))
1616 return std::nullopt;
1617 return Reg;
1618}
1619
1621 const MachineRegisterInfo &MRI,
1622 bool AllowFP = true,
1623 bool AllowOpaqueConstants = true) {
1624 switch (MI.getOpcode()) {
1625 case TargetOpcode::G_CONSTANT:
1626 case TargetOpcode::G_IMPLICIT_DEF:
1627 return true;
1628 case TargetOpcode::G_FCONSTANT:
1629 return AllowFP;
1630 case TargetOpcode::G_GLOBAL_VALUE:
1631 case TargetOpcode::G_FRAME_INDEX:
1632 case TargetOpcode::G_BLOCK_ADDR:
1633 case TargetOpcode::G_JUMP_TABLE:
1634 return AllowOpaqueConstants;
1635 default:
1636 return false;
1637 }
1638}
1639
1641 const MachineRegisterInfo &MRI) {
1642 Register Def = MI.getOperand(0).getReg();
1643 if (auto C = getIConstantVRegValWithLookThrough(Def, MRI))
1644 return true;
1646 if (!BV)
1647 return false;
1648 for (unsigned SrcIdx = 0; SrcIdx < BV->getNumSources(); ++SrcIdx) {
1651 continue;
1652 return false;
1653 }
1654 return true;
1655}
1656
1658 const MachineRegisterInfo &MRI,
1659 bool AllowFP, bool AllowOpaqueConstants) {
1660 if (isConstantScalar(MI, MRI, AllowFP, AllowOpaqueConstants))
1661 return true;
1662
1663 if (!isBuildVectorOp(MI.getOpcode()))
1664 return false;
1665
1666 const unsigned NumOps = MI.getNumOperands();
1667 for (unsigned I = 1; I != NumOps; ++I) {
1668 const MachineInstr *ElementDef = MRI.getVRegDef(MI.getOperand(I).getReg());
1669 if (!isConstantScalar(*ElementDef, MRI, AllowFP, AllowOpaqueConstants))
1670 return false;
1671 }
1672
1673 return true;
1674}
1675
1676std::optional<APInt>
1678 const MachineRegisterInfo &MRI) {
1679 if (auto C = getIConstantVRegValWithLookThrough(Def, MRI))
1680 return C->Value;
1681 auto MaybeCst = getIConstantSplatSExtVal(Def, MRI);
1682 if (!MaybeCst)
1683 return std::nullopt;
1684 const unsigned ScalarSize = MRI.getType(Def).getScalarSizeInBits();
1685 return APInt(ScalarSize, *MaybeCst, true);
1686}
1687
1688std::optional<APFloat>
1690 const MachineRegisterInfo &MRI) {
1691 if (auto FpConst = getFConstantVRegValWithLookThrough(Def, MRI))
1692 return FpConst->Value;
1693 auto MaybeCstFP = getFConstantSplat(Def, MRI, /*allowUndef=*/false);
1694 if (!MaybeCstFP)
1695 return std::nullopt;
1696 return MaybeCstFP->Value;
1697}
1698
1700 const MachineRegisterInfo &MRI, bool AllowUndefs) {
1701 switch (MI.getOpcode()) {
1702 case TargetOpcode::G_IMPLICIT_DEF:
1703 return AllowUndefs;
1704 case TargetOpcode::G_CONSTANT:
1705 return MI.getOperand(1).getCImm()->isNullValue();
1706 case TargetOpcode::G_FCONSTANT: {
1707 const ConstantFP *FPImm = MI.getOperand(1).getFPImm();
1708 return FPImm->isZero() && !FPImm->isNegative();
1709 }
1710 default:
1711 if (!AllowUndefs) // TODO: isBuildVectorAllZeros assumes undef is OK already
1712 return false;
1713 return isBuildVectorAllZeros(MI, MRI);
1714 }
1715}
1716
1718 const MachineRegisterInfo &MRI,
1719 bool AllowUndefs) {
1720 switch (MI.getOpcode()) {
1721 case TargetOpcode::G_IMPLICIT_DEF:
1722 return AllowUndefs;
1723 case TargetOpcode::G_CONSTANT:
1724 return MI.getOperand(1).getCImm()->isAllOnesValue();
1725 default:
1726 if (!AllowUndefs) // TODO: isBuildVectorAllOnes assumes undef is OK already
1727 return false;
1728 return isBuildVectorAllOnes(MI, MRI);
1729 }
1730}
1731
1733 const MachineRegisterInfo &MRI, Register Reg,
1734 llvm::function_ref<bool(const Constant *ConstVal)> Match,
1735 bool AllowUndefs) {
1736
1737 const MachineInstr *Def = getDefIgnoringCopies(Reg, MRI);
1738 if (AllowUndefs && Def->getOpcode() == TargetOpcode::G_IMPLICIT_DEF)
1739 return Match(nullptr);
1740
1741 // TODO: Also handle fconstant
1742 if (Def->getOpcode() == TargetOpcode::G_CONSTANT)
1743 return Match(Def->getOperand(1).getCImm());
1744
1745 if (Def->getOpcode() != TargetOpcode::G_BUILD_VECTOR)
1746 return false;
1747
1748 for (unsigned I = 1, E = Def->getNumOperands(); I != E; ++I) {
1749 Register SrcElt = Def->getOperand(I).getReg();
1750 const MachineInstr *SrcDef = getDefIgnoringCopies(SrcElt, MRI);
1751 if (AllowUndefs && SrcDef->getOpcode() == TargetOpcode::G_IMPLICIT_DEF) {
1752 if (!Match(nullptr))
1753 return false;
1754 continue;
1755 }
1756
1757 if (SrcDef->getOpcode() != TargetOpcode::G_CONSTANT ||
1758 !Match(SrcDef->getOperand(1).getCImm()))
1759 return false;
1760 }
1761
1762 return true;
1763}
1764
1765bool llvm::isConstTrueVal(const TargetLowering &TLI, int64_t Val, bool IsVector,
1766 bool IsFP) {
1767 switch (TLI.getBooleanContents(IsVector, IsFP)) {
1769 return Val & 0x1;
1771 return Val == 1;
1773 return Val == -1;
1774 }
1775 llvm_unreachable("Invalid boolean contents");
1776}
1777
1779 bool IsVector, bool IsFP) {
1780 switch (TLI.getBooleanContents(IsVector, IsFP)) {
1782 return ~Val & 0x1;
1785 return Val == 0;
1786 }
1787 llvm_unreachable("Invalid boolean contents");
1788}
1789
1790int64_t llvm::getICmpTrueVal(const TargetLowering &TLI, bool IsVector,
1791 bool IsFP) {
1792 switch (TLI.getBooleanContents(IsVector, IsFP)) {
1795 return 1;
1797 return -1;
1798 }
1799 llvm_unreachable("Invalid boolean contents");
1800}
1801
1803 LostDebugLocObserver *LocObserver,
1804 SmallInstListTy &DeadInstChain) {
1805 for (MachineOperand &Op : MI.uses()) {
1806 if (Op.isReg() && Op.getReg().isVirtual())
1807 DeadInstChain.insert(MRI.getVRegDef(Op.getReg()));
1808 }
1809 LLVM_DEBUG(dbgs() << MI << "Is dead; erasing.\n");
1810 DeadInstChain.remove(&MI);
1812 MI.eraseFromParent();
1813 if (LocObserver)
1814 LocObserver->checkpoint(false);
1815}
1816
1819 LostDebugLocObserver *LocObserver) {
1820 SmallInstListTy DeadInstChain;
1821 for (MachineInstr *MI : DeadInstrs)
1822 saveUsesAndErase(*MI, MRI, LocObserver, DeadInstChain);
1823
1824 while (!DeadInstChain.empty()) {
1825 MachineInstr *Inst = DeadInstChain.pop_back_val();
1826 if (!isTriviallyDead(*Inst, MRI))
1827 continue;
1828 saveUsesAndErase(*Inst, MRI, LocObserver, DeadInstChain);
1829 }
1830}
1831
1833 LostDebugLocObserver *LocObserver) {
1834 return eraseInstrs({&MI}, MRI, LocObserver);
1835}
1836
1838 for (auto &Def : MI.defs()) {
1839 assert(Def.isReg() && "Must be a reg");
1840
1842 for (auto &MOUse : MRI.use_operands(Def.getReg())) {
1843 MachineInstr *DbgValue = MOUse.getParent();
1844 // Ignore partially formed DBG_VALUEs.
1845 if (DbgValue->isNonListDebugValue() && DbgValue->getNumOperands() == 4) {
1846 DbgUsers.push_back(&MOUse);
1847 }
1848 }
1849
1850 if (!DbgUsers.empty()) {
1852 }
1853
1854 // MI is about to go away, so whatever could not be salvaged would be left
1855 // referring to a register without a definition.
1856 MRI.markUsesInDebugValueAsUndef(Def.getReg());
1857 }
1858}
1859
1861 switch (Opc) {
1862 case TargetOpcode::G_FABS:
1863 case TargetOpcode::G_FADD:
1864 case TargetOpcode::G_FCANONICALIZE:
1865 case TargetOpcode::G_FCEIL:
1866 case TargetOpcode::G_FCONSTANT:
1867 case TargetOpcode::G_FCOPYSIGN:
1868 case TargetOpcode::G_FCOS:
1869 case TargetOpcode::G_FDIV:
1870 case TargetOpcode::G_FEXP2:
1871 case TargetOpcode::G_FEXP:
1872 case TargetOpcode::G_FFLOOR:
1873 case TargetOpcode::G_FLOG10:
1874 case TargetOpcode::G_FLOG2:
1875 case TargetOpcode::G_FLOG:
1876 case TargetOpcode::G_FMA:
1877 case TargetOpcode::G_FMAD:
1878 case TargetOpcode::G_FMAXIMUM:
1879 case TargetOpcode::G_FMAXIMUMNUM:
1880 case TargetOpcode::G_FMAXNUM:
1881 case TargetOpcode::G_FMAXNUM_IEEE:
1882 case TargetOpcode::G_FMINIMUM:
1883 case TargetOpcode::G_FMINIMUMNUM:
1884 case TargetOpcode::G_FMINNUM:
1885 case TargetOpcode::G_FMINNUM_IEEE:
1886 case TargetOpcode::G_FMUL:
1887 case TargetOpcode::G_FNEARBYINT:
1888 case TargetOpcode::G_FNEG:
1889 case TargetOpcode::G_FPEXT:
1890 case TargetOpcode::G_FPEXTLOAD:
1891 case TargetOpcode::G_FPOW:
1892 case TargetOpcode::G_FPTRUNC:
1893 case TargetOpcode::G_FPTRUNCSTORE:
1894 case TargetOpcode::G_FREM:
1895 case TargetOpcode::G_FRINT:
1896 case TargetOpcode::G_FSIN:
1897 case TargetOpcode::G_FTAN:
1898 case TargetOpcode::G_FACOS:
1899 case TargetOpcode::G_FASIN:
1900 case TargetOpcode::G_FATAN:
1901 case TargetOpcode::G_FATAN2:
1902 case TargetOpcode::G_FCOSH:
1903 case TargetOpcode::G_FSINH:
1904 case TargetOpcode::G_FTANH:
1905 case TargetOpcode::G_FSQRT:
1906 case TargetOpcode::G_FSUB:
1907 case TargetOpcode::G_INTRINSIC_ROUND:
1908 case TargetOpcode::G_INTRINSIC_ROUNDEVEN:
1909 case TargetOpcode::G_INTRINSIC_TRUNC:
1910 return true;
1911 default:
1912 return false;
1913 }
1914}
1915
1916/// Shifts return poison if shiftwidth is larger than the bitwidth.
1917static bool shiftAmountKnownInRange(Register ShiftAmount,
1918 const MachineRegisterInfo &MRI) {
1919 LLT Ty = MRI.getType(ShiftAmount);
1920
1921 if (Ty.isScalableVector())
1922 return false; // Can't tell, just return false to be safe
1923
1924 if (Ty.isScalar()) {
1925 std::optional<ValueAndVReg> Val =
1927 if (!Val)
1928 return false;
1929 return Val->Value.ult(Ty.getScalarSizeInBits());
1930 }
1931
1932 GBuildVector *BV = getOpcodeDef<GBuildVector>(ShiftAmount, MRI);
1933 if (!BV)
1934 return false;
1935
1936 unsigned Sources = BV->getNumSources();
1937 for (unsigned I = 0; I < Sources; ++I) {
1938 std::optional<ValueAndVReg> Val =
1940 if (!Val)
1941 return false;
1942 if (!Val->Value.ult(Ty.getScalarSizeInBits()))
1943 return false;
1944 }
1945
1946 return true;
1947}
1948
1950 bool ConsiderFlagsAndMetadata,
1951 UndefPoisonKind Kind) {
1952 MachineInstr *RegDef = MRI.getVRegDef(Reg);
1953
1954 if (ConsiderFlagsAndMetadata && includesPoison(Kind))
1955 if (auto *GMI = dyn_cast<GenericMachineInstr>(RegDef))
1956 if (GMI->hasPoisonGeneratingFlags())
1957 return true;
1958
1959 // Check whether opcode is a poison/undef-generating operation.
1960 switch (RegDef->getOpcode()) {
1961 case TargetOpcode::G_BUILD_VECTOR:
1962 case TargetOpcode::G_CONSTANT_FOLD_BARRIER:
1963 return false;
1964 case TargetOpcode::G_SHL:
1965 case TargetOpcode::G_ASHR:
1966 case TargetOpcode::G_LSHR:
1967 return includesPoison(Kind) &&
1969 case TargetOpcode::G_FPTOSI:
1970 case TargetOpcode::G_FPTOUI:
1971 // fptosi/ui yields poison if the resulting value does not fit in the
1972 // destination type.
1973 return true;
1974 case TargetOpcode::G_CTLZ:
1975 case TargetOpcode::G_CTTZ:
1976 case TargetOpcode::G_CTLS:
1977 case TargetOpcode::G_ABS:
1978 case TargetOpcode::G_CTPOP:
1979 case TargetOpcode::G_BSWAP:
1980 case TargetOpcode::G_BITREVERSE:
1981 case TargetOpcode::G_FSHL:
1982 case TargetOpcode::G_FSHR:
1983 case TargetOpcode::G_SMAX:
1984 case TargetOpcode::G_SMIN:
1985 case TargetOpcode::G_SCMP:
1986 case TargetOpcode::G_UMAX:
1987 case TargetOpcode::G_UMIN:
1988 case TargetOpcode::G_UCMP:
1989 case TargetOpcode::G_PTRMASK:
1990 case TargetOpcode::G_SADDO:
1991 case TargetOpcode::G_SSUBO:
1992 case TargetOpcode::G_UADDO:
1993 case TargetOpcode::G_USUBO:
1994 case TargetOpcode::G_SMULO:
1995 case TargetOpcode::G_UMULO:
1996 case TargetOpcode::G_SADDSAT:
1997 case TargetOpcode::G_UADDSAT:
1998 case TargetOpcode::G_SSUBSAT:
1999 case TargetOpcode::G_USUBSAT:
2000 case TargetOpcode::G_SBFX:
2001 case TargetOpcode::G_UBFX:
2002 return false;
2003 case TargetOpcode::G_SSHLSAT:
2004 case TargetOpcode::G_USHLSAT:
2005 return includesPoison(Kind) &&
2007 case TargetOpcode::G_INSERT_VECTOR_ELT: {
2009 if (includesPoison(Kind)) {
2010 std::optional<ValueAndVReg> Index =
2011 getIConstantVRegValWithLookThrough(Insert->getIndexReg(), MRI);
2012 if (!Index)
2013 return true;
2014 LLT VecTy = MRI.getType(Insert->getVectorReg());
2015 return Index->Value.uge(VecTy.getElementCount().getKnownMinValue());
2016 }
2017 return false;
2018 }
2019 case TargetOpcode::G_EXTRACT_VECTOR_ELT: {
2021 if (includesPoison(Kind)) {
2022 std::optional<ValueAndVReg> Index =
2024 if (!Index)
2025 return true;
2026 LLT VecTy = MRI.getType(Extract->getVectorReg());
2027 return Index->Value.uge(VecTy.getElementCount().getKnownMinValue());
2028 }
2029 return false;
2030 }
2031 case TargetOpcode::G_SHUFFLE_VECTOR: {
2032 GShuffleVector *Shuffle = cast<GShuffleVector>(RegDef);
2033 ArrayRef<int> Mask = Shuffle->getMask();
2034 return includesPoison(Kind) && is_contained(Mask, -1);
2035 }
2036 case TargetOpcode::G_FNEG:
2037 case TargetOpcode::G_PHI:
2038 case TargetOpcode::G_SELECT:
2039 case TargetOpcode::G_UREM:
2040 case TargetOpcode::G_SREM:
2041 case TargetOpcode::G_FREEZE:
2042 case TargetOpcode::G_ICMP:
2043 case TargetOpcode::G_FCMP:
2044 case TargetOpcode::G_FADD:
2045 case TargetOpcode::G_FSUB:
2046 case TargetOpcode::G_FMUL:
2047 case TargetOpcode::G_FDIV:
2048 case TargetOpcode::G_FREM:
2049 case TargetOpcode::G_PTR_ADD:
2050 return false;
2051 default:
2052 return !isa<GCastOp>(RegDef) && !isa<GBinOp>(RegDef);
2053 }
2054}
2055
2057 const MachineRegisterInfo &MRI,
2058 unsigned Depth,
2059 UndefPoisonKind Kind) {
2061 return false;
2062
2063 MachineInstr *RegDef = MRI.getVRegDef(Reg);
2064
2065 switch (RegDef->getOpcode()) {
2066 case TargetOpcode::G_FREEZE:
2067 return true;
2068 case TargetOpcode::G_IMPLICIT_DEF:
2069 return !includesUndef(Kind);
2070 case TargetOpcode::G_CONSTANT:
2071 case TargetOpcode::G_FCONSTANT:
2072 return true;
2073 case TargetOpcode::G_BUILD_VECTOR: {
2074 GBuildVector *BV = cast<GBuildVector>(RegDef);
2075 unsigned NumSources = BV->getNumSources();
2076 for (unsigned I = 0; I < NumSources; ++I)
2078 Depth + 1, Kind))
2079 return false;
2080 return true;
2081 }
2082 case TargetOpcode::G_PHI: {
2083 GPhi *Phi = cast<GPhi>(RegDef);
2084 unsigned NumIncoming = Phi->getNumIncomingValues();
2085 for (unsigned I = 0; I < NumIncoming; ++I)
2086 if (!::isGuaranteedNotToBeUndefOrPoison(Phi->getIncomingValue(I), MRI,
2087 Depth + 1, Kind))
2088 return false;
2089 return true;
2090 }
2091 default: {
2092 auto MOCheck = [&](const MachineOperand &MO) {
2093 if (!MO.isReg())
2094 return true;
2095 return ::isGuaranteedNotToBeUndefOrPoison(MO.getReg(), MRI, Depth + 1,
2096 Kind);
2097 };
2099 /*ConsiderFlagsAndMetadata=*/true, Kind) &&
2100 all_of(RegDef->uses(), MOCheck);
2101 }
2102 }
2103}
2104
2106 bool ConsiderFlagsAndMetadata) {
2107 return ::canCreateUndefOrPoison(Reg, MRI, ConsiderFlagsAndMetadata,
2109}
2110
2112 bool ConsiderFlagsAndMetadata = true) {
2113 return ::canCreateUndefOrPoison(Reg, MRI, ConsiderFlagsAndMetadata,
2115}
2116
2118 const MachineRegisterInfo &MRI,
2119 unsigned Depth) {
2120 return ::isGuaranteedNotToBeUndefOrPoison(Reg, MRI, Depth,
2122}
2123
2125 const MachineRegisterInfo &MRI,
2126 unsigned Depth) {
2127 return ::isGuaranteedNotToBeUndefOrPoison(Reg, MRI, Depth,
2129}
2130
2132 const MachineRegisterInfo &MRI,
2133 unsigned Depth) {
2134 return ::isGuaranteedNotToBeUndefOrPoison(Reg, MRI, Depth,
2136}
2137
2139 if (Ty.isVector())
2140 return VectorType::get(IntegerType::get(C, Ty.getScalarSizeInBits()),
2141 Ty.getElementCount());
2142 return IntegerType::get(C, Ty.getSizeInBits());
2143}
2144
2146 switch (MI.getOpcode()) {
2147 default:
2148 return false;
2149 case TargetOpcode::G_ASSERT_ALIGN:
2150 case TargetOpcode::G_ASSERT_SEXT:
2151 case TargetOpcode::G_ASSERT_ZEXT:
2152 return true;
2153 }
2154}
2155
2157 assert(Kind == GIConstantKind::Scalar && "Expected scalar constant");
2158
2159 return Value;
2160}
2161
2162std::optional<GIConstant>
2165
2167 std::optional<ValueAndVReg> MayBeConstant =
2169 if (!MayBeConstant)
2170 return std::nullopt;
2171 return GIConstant(MayBeConstant->Value, GIConstantKind::ScalableVector);
2172 }
2173
2175 SmallVector<APInt> Values;
2176 unsigned NumSources = Build->getNumSources();
2177 for (unsigned I = 0; I < NumSources; ++I) {
2178 Register SrcReg = Build->getSourceReg(I);
2179 std::optional<ValueAndVReg> MayBeConstant =
2181 if (!MayBeConstant)
2182 return std::nullopt;
2183 Values.push_back(MayBeConstant->Value);
2184 }
2185 return GIConstant(Values);
2186 }
2187
2188 std::optional<ValueAndVReg> MayBeConstant =
2190 if (!MayBeConstant)
2191 return std::nullopt;
2192
2193 return GIConstant(MayBeConstant->Value, GIConstantKind::Scalar);
2194}
2195
2197 assert(Kind == GFConstantKind::Scalar && "Expected scalar constant");
2198
2199 return Values[0];
2200}
2201
2202std::optional<GFConstant>
2205
2207 std::optional<FPValueAndVReg> MayBeConstant =
2209 if (!MayBeConstant)
2210 return std::nullopt;
2211 return GFConstant(MayBeConstant->Value, GFConstantKind::ScalableVector);
2212 }
2213
2215 SmallVector<APFloat> Values;
2216 unsigned NumSources = Build->getNumSources();
2217 for (unsigned I = 0; I < NumSources; ++I) {
2218 Register SrcReg = Build->getSourceReg(I);
2219 std::optional<FPValueAndVReg> MayBeConstant =
2221 if (!MayBeConstant)
2222 return std::nullopt;
2223 Values.push_back(MayBeConstant->Value);
2224 }
2225 return GFConstant(Values);
2226 }
2227
2228 std::optional<FPValueAndVReg> MayBeConstant =
2230 if (!MayBeConstant)
2231 return std::nullopt;
2232
2233 return GFConstant(MayBeConstant->Value, GFConstantKind::Scalar);
2234}
2235
2236// Returns a list of types to use for memory op lowering in MemOps. A partial
2237// port of findOptimalMemOpLowering in TargetLowering.
2238static bool findGISelOptimalMemOpLowering(std::vector<LLT> &MemOps,
2239 unsigned Limit, const MemOp &Op,
2240 unsigned DstAS, unsigned SrcAS,
2241 const AttributeList &FuncAttributes,
2242 const TargetLowering &TLI) {
2243 if (Op.isMemcpyOrMemmoveWithFixedDstAlign() &&
2244 Op.getSrcAlign() < Op.getDstAlign())
2245 return false;
2246
2247 LLT Ty = TLI.getOptimalMemOpLLT(Op, FuncAttributes);
2248
2249 if (Ty == LLT()) {
2250 // Use the largest scalar type whose alignment constraints are satisfied.
2251 // We only need to check DstAlign here as SrcAlign is always greater or
2252 // equal to DstAlign (or zero).
2253 Ty = LLT::integer(64);
2254 if (Op.isFixedDstAlign())
2255 while (Op.getDstAlign() < Ty.getSizeInBytes() &&
2256 !TLI.allowsMisalignedMemoryAccesses(Ty, DstAS, Op.getDstAlign()))
2257 Ty = LLT::integer(Ty.getSizeInBytes());
2258 assert(Ty.getSizeInBits() > 0 && "Could not find valid type");
2259 // FIXME: check for the largest legal type we can load/store to.
2260 }
2261
2262 unsigned NumMemOps = 0;
2263 uint64_t Size = Op.size();
2264 while (Size) {
2265 unsigned TySize = Ty.getSizeInBytes();
2266 while (TySize > Size) {
2267 // For now, only use non-vector load / store's for the left-over pieces.
2268 LLT NewTy = Ty;
2269 // FIXME: check for mem op safety and legality of the types. Not all of
2270 // SDAGisms map cleanly to GISel concepts.
2271 if (NewTy.isVector())
2272 NewTy =
2273 NewTy.getSizeInBits() > 64 ? LLT::integer(64) : LLT::integer(32);
2274 NewTy = LLT::integer(llvm::bit_floor(NewTy.getSizeInBits() - 1));
2275 unsigned NewTySize = NewTy.getSizeInBytes();
2276 assert(NewTySize > 0 && "Could not find appropriate type");
2277
2278 // If the new LLT cannot cover all of the remaining bits, then consider
2279 // issuing a (or a pair of) unaligned and overlapping load / store.
2280 unsigned Fast;
2281 // Need to get a VT equivalent for allowMisalignedMemoryAccesses().
2282 MVT VT = getMVTForLLT(Ty);
2283 if (NumMemOps && !Op.isVolatile() && NewTySize < Size &&
2284 TLI.allowsMisalignedMemoryAccesses(
2285 VT, DstAS, Op.isFixedDstAlign() ? Op.getDstAlign() : Align(1),
2287 Fast)
2288 TySize = Size;
2289 else {
2290 Ty = NewTy;
2291 TySize = NewTySize;
2292 }
2293 }
2294
2295 if (++NumMemOps > Limit)
2296 return false;
2297
2298 MemOps.push_back(Ty);
2299 Size -= TySize;
2300 }
2301
2302 return true;
2303}
2304
2306 const MachineRegisterInfo &MRI, unsigned MaxLen,
2307 Register &Dst, Register &Src,
2308 uint64_t &KnownLen, Align &Alignment,
2309 bool &DstAlignCanChange,
2310 std::vector<LLT> &MemOps) {
2311 const unsigned Opc = MI.getOpcode();
2312 assert((Opc == TargetOpcode::G_MEMCPY ||
2313 Opc == TargetOpcode::G_MEMCPY_INLINE ||
2314 Opc == TargetOpcode::G_MEMMOVE || Opc == TargetOpcode::G_MEMSET ||
2315 Opc == TargetOpcode::G_MEMSET_INLINE) &&
2316 "Expected memcpy like instruction");
2317
2318 auto MMOIt = MI.memoperands_begin();
2319 const MachineMemOperand *MemOp = *MMOIt;
2320
2321 Align DstAlign = MemOp->getBaseAlign();
2322 Align SrcAlign;
2323 Alignment = DstAlign;
2324 Register Len;
2325 std::tie(Dst, Src, Len) = MI.getFirst3Regs();
2326
2327 if (Opc != TargetOpcode::G_MEMSET && Opc != TargetOpcode::G_MEMSET_INLINE) {
2328 assert(MMOIt != MI.memoperands_end() && "Expected a second MMO on MI");
2329 MemOp = *(++MMOIt);
2330 SrcAlign = MemOp->getBaseAlign();
2331 Alignment = std::min(DstAlign, SrcAlign);
2332 }
2333
2334 // See if this is a constant length copy.
2335 auto LenVRegAndVal = getIConstantVRegValWithLookThrough(Len, MRI);
2336 if (!LenVRegAndVal) {
2337 // FIXME: support dynamically sized G_MEMCPY_INLINE and G_MEMSET_INLINE
2338 assert(Opc != TargetOpcode::G_MEMCPY_INLINE &&
2339 Opc != TargetOpcode::G_MEMSET_INLINE &&
2340 "inline memcpy and memset with dynamic size are not yet supported");
2341 return false;
2342 }
2343
2344 KnownLen = LenVRegAndVal->Value.getZExtValue();
2345 DstAlignCanChange = false;
2346
2347 if (KnownLen == 0)
2348 return true;
2349
2350 if (Opc != TargetOpcode::G_MEMCPY_INLINE &&
2351 Opc != TargetOpcode::G_MEMSET_INLINE && MaxLen && KnownLen > MaxLen)
2352 return false;
2353
2354 bool IsVolatile = MemOp->isVolatile();
2355 const MachineFunction &MF = *MI.getParent()->getParent();
2356 const auto &TLI = *MF.getSubtarget().getTargetLowering();
2357 // On Darwin, -Os means optimize for size without hurting performance, so
2358 // only really optimize for size when -Oz (MinSize) is used.
2359 bool OptSize = MF.getTarget().getTargetTriple().isOSDarwin()
2360 ? MF.getFunction().hasMinSize()
2361 : MF.getFunction().hasOptSize();
2362
2363 const MachineFrameInfo &MFI = MF.getFrameInfo();
2364 MachineInstr *FIDef = getOpcodeDef(TargetOpcode::G_FRAME_INDEX, Dst, MRI);
2365 if (FIDef && !MFI.isFixedObjectIndex(FIDef->getOperand(1).getIndex()))
2366 DstAlignCanChange = true;
2367
2368 const auto &DstMMO = **MI.memoperands_begin();
2369 MachinePointerInfo DstPtrInfo = DstMMO.getPointerInfo();
2370
2371 switch (Opc) {
2372 case TargetOpcode::G_MEMCPY_INLINE:
2373 case TargetOpcode::G_MEMCPY: {
2374 const auto &SrcMMO = **std::next(MI.memoperands_begin());
2375 MachinePointerInfo SrcPtrInfo = SrcMMO.getPointerInfo();
2376 uint64_t Limit = Opc == TargetOpcode::G_MEMCPY_INLINE
2377 ? std::numeric_limits<uint64_t>::max()
2378 : TLI.getMaxStoresPerMemcpy(OptSize);
2380 MemOps, Limit,
2381 MemOp::Copy(KnownLen, DstAlignCanChange, std::min(DstAlign, SrcAlign),
2382 SrcAlign, IsVolatile),
2383 DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
2384 MF.getFunction().getAttributes(), TLI);
2385 }
2386 case TargetOpcode::G_MEMMOVE: {
2387 const auto &SrcMMO = **std::next(MI.memoperands_begin());
2388 MachinePointerInfo SrcPtrInfo = SrcMMO.getPointerInfo();
2389 unsigned Limit = TLI.getMaxStoresPerMemmove(OptSize);
2391 MemOps, Limit,
2392 MemOp::Move(KnownLen, DstAlignCanChange, std::min(DstAlign, SrcAlign),
2393 SrcAlign, IsVolatile),
2394 DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
2395 MF.getFunction().getAttributes(), TLI);
2396 }
2397 case TargetOpcode::G_MEMSET:
2398 case TargetOpcode::G_MEMSET_INLINE: {
2399 unsigned Limit = Opc == TargetOpcode::G_MEMSET_INLINE
2400 ? std::numeric_limits<unsigned>::max()
2401 : TLI.getMaxStoresPerMemset(OptSize);
2402 auto ValVRegAndVal = getIConstantVRegValWithLookThrough(Src, MRI);
2403 bool IsZeroVal = ValVRegAndVal && ValVRegAndVal->Value == 0;
2405 MemOps, Limit,
2406 MemOp::Set(KnownLen, DstAlignCanChange, DstAlign,
2407 /*IsZeroMemset=*/IsZeroVal,
2408 /*IsVolatile=*/IsVolatile),
2409 DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes(), TLI);
2410 }
2411 default:
2412 llvm_unreachable("Unexpected memcpy-family opcode");
2413 }
2414}
MachineInstrBuilder MachineInstrBuilder & DefMI
unsigned NumParts
const TargetLowering & TLI
unsigned RegSize
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
uint64_t Imm
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static bool findGISelOptimalMemOpLowering(std::vector< LLT > &MemOps, unsigned Limit, const MemOp &Op, unsigned DstAS, unsigned SrcAS, const AttributeList &FuncAttributes, const TargetLowering &TLI)
Definition Utils.cpp:2238
static void reportGISelDiagnostic(DiagnosticSeverity Severity, MachineFunction &MF, MachineOptimizationRemarkEmitter &MORE, MachineOptimizationRemarkMissed &R)
Definition Utils.cpp:241
static bool shiftAmountKnownInRange(Register ShiftAmount, const MachineRegisterInfo &MRI)
Shifts return poison if shiftwidth is larger than the bitwidth.
Definition Utils.cpp:1917
static bool isBuildVectorOp(unsigned Opcode)
Definition Utils.cpp:1463
static bool isConstantScalar(const MachineInstr &MI, const MachineRegisterInfo &MRI, bool AllowFP=true, bool AllowOpaqueConstants=true)
Definition Utils.cpp:1620
static GBuildVector * getBuildVectorLikeDef(Register Reg, const MachineRegisterInfo &MRI)
Definition Utils.cpp:811
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This contains common code to allow clients to notify changes to machine instr.
Provides analysis for querying information about KnownBits during GISel passes.
Declares convenience wrapper classes for interpreting MachineInstr instances as specific generic oper...
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
Tracks DebugLocs between checkpoints and verifies that they are transferred.
Implement a low-level type suitable for MachineInstr level instruction selection.
#define I(x, y, z)
Definition MD5.cpp:57
Contains matchers for matching SSA Machine Instructions.
This file declares the MachineIRBuilder class.
===- MachineOptimizationRemarkEmitter.h - Opt Diagnostics -*- C++ -*-—===//
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
uint64_t IntrinsicInst * II
MachineBasicBlock * Folded
int64_t C1
MachineRegisterInfo & MRI
const char * Msg
#define LLVM_DEBUG(...)
Definition Debug.h:119
This file describes how to lower LLVM code to machine code.
Target-Independent Code Generator Pass Configuration Options pass.
This file contains the UndefPoisonKind enum and helper functions.
static const char PassName[]
Class recording the (high level) value of a variable.
static constexpr roundingMode rmTowardZero
Definition APFloat.h:365
static LLVM_ABI unsigned getSizeInBits(const fltSemantics &Sem)
Returns the size of the floating point number (in bits) in the given semantics.
Definition APFloat.cpp:399
static constexpr roundingMode rmTowardNegative
Definition APFloat.h:364
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:361
static constexpr roundingMode rmTowardPositive
Definition APFloat.h:363
static LLVM_ABI bool isIEEELikeFP(const fltSemantics &)
Definition APFloat.cpp:376
static constexpr roundingMode rmNearestTiesToAway
Definition APFloat.h:366
const fltSemantics & getSemantics() const
Definition APFloat.h:1591
opStatus convertFromAPInt(const APInt &Input, bool IsSigned, roundingMode RM)
Definition APFloat.h:1451
APInt bitcastToAPInt() const
Definition APFloat.h:1475
Class for arbitrary precision integers.
Definition APInt.h:78
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:230
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1057
LLVM_ABI APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
Definition APInt.cpp:1078
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
Definition APInt.cpp:970
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
static bool isSameValue(const APInt &I1, const APInt &I2, bool SignedCompare=false)
Determine if two APInts have the same value, after zero-extending or sign-extending (if SignedCompare...
Definition APInt.h:550
LLVM_ABI APInt sext(unsigned width) const
Sign extend to a new width.
Definition APInt.cpp:1030
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:235
Represent the analysis usage information of a pass.
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ 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_SGE
signed greater or equal
Definition InstrTypes.h:768
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
ConstantFP - Floating Point Values [float, double].
Definition Constants.h:420
const APFloat & getValueAPF() const
Definition Constants.h:463
bool isNegative() const
Return true if the sign bit is set.
Definition Constants.h:476
bool isZero() const
Return true if the value is positive or negative zero.
Definition Constants.h:467
This is the shared class of boolean and integer constants.
Definition Constants.h:87
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
This is an important base class in LLVM.
Definition Constant.h:44
A debug info location.
Definition DebugLoc.h:126
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:306
static constexpr ElementCount get(ScalarTy MinVal, bool Scalable)
Definition TypeSize.h:312
bool hasOptSize() const
Optimize this function for size (-Os) or minimum size (-Oz).
Definition Function.h:699
bool hasMinSize() const
Optimize this function for minimum size (-Oz).
Definition Function.h:696
AttributeList getAttributes() const
Return the attribute list for this Function.
Definition Function.h:329
Represents a G_BUILD_VECTOR.
Represents an extract vector element.
static LLVM_ABI std::optional< GFConstant > getConstant(Register Const, const MachineRegisterInfo &MRI)
Definition Utils.cpp:2203
GFConstant(ArrayRef< APFloat > Values)
Definition Utils.h:676
LLVM_ABI APFloat getScalarValue() const
Returns the value, if this constant is a scalar.
Definition Utils.cpp:2196
LLVM_ABI APInt getScalarValue() const
Returns the value, if this constant is a scalar.
Definition Utils.cpp:2156
static LLVM_ABI std::optional< GIConstant > getConstant(Register Const, const MachineRegisterInfo &MRI)
Definition Utils.cpp:2163
GIConstant(ArrayRef< APInt > Values)
Definition Utils.h:635
Abstract class that contains various methods for clients to notify about changes.
KnownBits getKnownBits(Register R)
bool isKnownNeverZero(Register R, unsigned Depth=0)
Return true if the value defined by R is provably never zero.
void insert(MachineInstr *I)
Add the specified instruction to the worklist if it isn't already in it.
MachineInstr * pop_back_val()
void remove(const MachineInstr *I)
Remove I from the worklist if it exists.
Represents an insert vector element.
Register getSourceReg(unsigned I) const
Returns the I'th source register.
unsigned getNumSources() const
Returns the number of source registers.
Represents a G_PHI.
Represents a G_SHUFFLE_VECTOR.
ArrayRef< int > getMask() const
Represents a splat vector.
Module * getParent()
Get the module that this global value is contained inside of...
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:338
constexpr bool isScalableVector() const
Returns true if the LLT is a scalable vector.
constexpr unsigned getScalarSizeInBits() const
static constexpr LLT vector(ElementCount EC, unsigned ScalarSizeInBits)
Get a low-level vector of some number of elements and element width.
LLT getScalarType() const
static constexpr LLT scalar(unsigned SizeInBits)
Get a low-level scalar or aggregate "bag of bits".
constexpr bool isValid() const
constexpr uint16_t getNumElements() const
Returns the number of elements in a vector LLT.
constexpr bool isVector() const
constexpr bool isScalable() const
Returns true if the LLT is a scalable vector.
constexpr TypeSize getSizeInBits() const
Returns the total size of the type. Must only be called on sized types.
constexpr ElementCount getElementCount() const
static constexpr LLT fixed_vector(unsigned NumElements, unsigned ScalarSizeInBits)
Get a low-level fixed-width vector of some number of elements and element width.
constexpr bool isFixedVector() const
Returns true if the LLT is a fixed vector.
static LLT integer(unsigned SizeInBits)
constexpr TypeSize getSizeInBytes() const
Returns the total size of the type in bytes, i.e.
LLT getElementType() const
Returns the vector's element type. Only valid for vector types.
static constexpr LLT scalarOrVector(ElementCount EC, LLT ScalarTy)
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
void checkpoint(bool CheckDebugLocs=true)
Call this to indicate that it's a good point to assess whether locations have been lost.
Describe properties that are true of each instruction in the target description file.
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
Machine Value Type.
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
MachineInstrBundleIterator< MachineInstr > iterator
LLVM_ABI bool isLiveIn(MCRegister Reg, LaneBitmask LaneMask=LaneBitmask::getAll()) const
Return true if the specified register is in the live in set.
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
Align getObjectAlign(int ObjectIdx) const
Return the alignment of the specified stack object.
bool isFixedObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a fixed stack object.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
GISelChangeObserver * getObserver() const
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
const MachineFunctionProperties & getProperties() const
Get the function properties.
const MachineBasicBlock & front() const
Register addLiveIn(MCRegister PReg, const TargetRegisterClass *RC)
addLiveIn - Add the specified physical register as a live-in value and create a corresponding virtual...
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
Helper class to build MachineInstr.
MachineInstrBuilder buildUnmerge(ArrayRef< LLT > Res, const SrcOp &Op)
Build and insert Res0, ... = G_UNMERGE_VALUES Op.
MachineInstrBuilder buildExtract(const DstOp &Res, const SrcOp &Src, uint64_t Index)
Build and insert Res0, ... = G_EXTRACT Src, Idx0.
MachineInstrBuilder buildMergeLikeInstr(const DstOp &Res, ArrayRef< Register > Ops)
Build and insert Res = G_MERGE_VALUES Op0, ... or Res = G_BUILD_VECTOR Op0, ... or Res = G_CONCAT_VEC...
Register getReg(unsigned Idx) const
Get the register for the operand index.
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
const MachineBasicBlock * getParent() const
mop_range uses()
Returns all operands which may be register uses.
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
const MachineOperand & getOperand(unsigned i) const
A description of a memory reference used in the backend.
MachineOperand class - Representation of each machine instruction operand.
const ConstantInt * getCImm() const
bool isCImm() const
isCImm - Test if this is a MO_CImmediate operand.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
Register getReg() const
getReg - Returns the register number.
const ConstantFP * getFPImm() const
bool isFPImm() const
isFPImm - Tests if this is a MO_FPImmediate operand.
Diagnostic information for missed-optimization remarks.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
Holds all the information related to register banks.
static const TargetRegisterClass * constrainGenericRegister(Register Reg, const TargetRegisterClass &RC, MachineRegisterInfo &MRI)
Constrain the (possibly generic) virtual register Reg to RC.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition Register.h:83
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
TargetInstrInfo - Interface to description of machine instruction set.
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
const Triple & getTargetTriple() const
TargetOptions Options
GlobalISelAbortMode GlobalISelAbort
EnableGlobalISelAbort - Control abort behaviour when global instruction selection fails to lower/sele...
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetLowering * getTargetLowering() const
bool isOSDarwin() const
Is this a "Darwin" OS (macOS, iOS, tvOS, watchOS, DriverKit, XROS, or bridgeOS).
Definition Triple.h:724
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI Type * getFloatingPointTy(LLVMContext &C, const fltSemantics &S)
Definition Type.cpp:115
LLVM Value Representation.
Definition Value.h:75
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:201
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:169
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:166
An efficient, type-erasing, non-owning reference to a callable.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
const APInt & smin(const APInt &A, const APInt &B)
Determine the smaller of two APInts considered to be signed.
Definition APInt.h:2274
const APInt & smax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be signed.
Definition APInt.h:2279
const APInt & umin(const APInt &A, const APInt &B)
Determine the smaller of two APInts considered to be unsigned.
Definition APInt.h:2284
const APInt & umax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be unsigned.
Definition APInt.h:2289
ImplicitDefMatch m_GImplicitDef()
bool mi_match(Reg R, const MachineRegisterInfo &MRI, Pattern &&P)
DiagnosticInfoMIROptimization::MachineArgument MNV
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI Register getFunctionLiveInPhysReg(MachineFunction &MF, const TargetInstrInfo &TII, MCRegister PhysReg, const TargetRegisterClass &RC, const DebugLoc &DL, LLT RegTy=LLT())
Return a virtual register corresponding to the incoming argument register PhysReg.
Definition Utils.cpp:896
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
LLVM_ABI std::optional< SmallVector< APInt > > ConstantFoldICmp(unsigned Pred, const Register Op1, const Register Op2, unsigned DstScalarSizeInBits, unsigned ExtOp, const MachineRegisterInfo &MRI)
Definition Utils.cpp:1113
LLVM_ABI std::optional< APInt > isConstantOrConstantSplatVector(Register Def, const MachineRegisterInfo &MRI)
Determines if Def defines a constant integer or a splat vector of constant integers.
Definition Utils.cpp:1677
@ Offset
Definition DWP.cpp:577
LLVM_ABI bool isBuildVectorAllZeros(const MachineInstr &MI, const MachineRegisterInfo &MRI, bool AllowUndef=false)
Return true if the specified instruction is a G_BUILD_VECTOR or G_BUILD_VECTOR_TRUNC where all of the...
Definition Utils.cpp:1593
LLVM_ABI Type * getTypeForLLT(LLT Ty, LLVMContext &C)
Get the type back from LLT.
Definition Utils.cpp:2138
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
LLVM_ABI Register constrainOperandRegClass(const MachineFunction &MF, const TargetRegisterInfo &TRI, MachineRegisterInfo &MRI, const TargetInstrInfo &TII, const RegisterBankInfo &RBI, MachineInstr &InsertPt, const TargetRegisterClass &RegClass, MachineOperand &RegMO)
Constrain the Register operand OpIdx, so that it is now constrained to the TargetRegisterClass passed...
Definition Utils.cpp:64
LLVM_ABI MachineInstr * getOpcodeDef(unsigned Opcode, Register Reg, const MachineRegisterInfo &MRI)
See if Reg is defined by an single def instruction that is Opcode.
Definition Utils.cpp:679
static double log2(double V)
LLVM_ABI std::optional< APFloat > isConstantOrConstantSplatVectorFP(Register Def, const MachineRegisterInfo &MRI)
Determines if Def defines a float constant integer or a splat vector of float constant integers.
Definition Utils.cpp:1689
LLVM_ABI const ConstantFP * getConstantFPVRegVal(Register VReg, const MachineRegisterInfo &MRI)
Definition Utils.cpp:487
LLVM_ABI bool canCreatePoison(const Operator *Op, bool ConsiderFlagsAndMetadata=true)
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
LLVM_ABI std::optional< APInt > getIConstantVRegVal(Register VReg, const MachineRegisterInfo &MRI)
If VReg is defined by a G_CONSTANT, return the corresponding value.
Definition Utils.cpp:301
LLVM_ABI std::optional< APFloat > ConstantFoldIntToFloat(unsigned Opcode, LLT DstTy, Register Src, const MachineRegisterInfo &MRI)
Definition Utils.cpp:970
LLVM_ABI std::optional< APInt > getIConstantSplatVal(const Register Reg, const MachineRegisterInfo &MRI)
Definition Utils.cpp:1553
LLVM_ABI bool isAllOnesOrAllOnesSplat(const MachineInstr &MI, const MachineRegisterInfo &MRI, bool AllowUndefs=false)
Return true if the value is a constant -1 integer or a splatted vector of a constant -1 integer (with...
Definition Utils.cpp:1717
@ Known
Known to have no common set bits.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI const llvm::fltSemantics & getFltSemanticForLLT(LLT Ty)
Get the appropriate floating point arithmetic semantic based on the bit size of the given scalar LLT.
LLVM_ABI std::optional< APFloat > ConstantFoldFPBinOp(unsigned Opcode, const Register Op1, const Register Op2, const MachineRegisterInfo &MRI)
Definition Utils.cpp:754
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:1837
LLVM_ABI void constrainSelectedInstRegOperands(MachineInstr &I, const TargetInstrInfo &TII, const TargetRegisterInfo &TRI, const RegisterBankInfo &RBI)
Mutate the newly-selected instruction I to constrain its (possibly generic) virtual register operands...
Definition Utils.cpp:163
bool isPreISelGenericOpcode(unsigned Opcode)
Check whether the given Opcode is a generic opcode that is not supposed to appear after ISel.
LLVM_ABI bool matchUnaryPredicate(const MachineRegisterInfo &MRI, Register Reg, llvm::function_ref< bool(const Constant *ConstVal)> Match, bool AllowUndefs=false)
Attempt to match a unary predicate against a scalar/splat constant or every element of a constant G_B...
Definition Utils.cpp:1732
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
LLVM_ABI std::optional< APInt > ConstantFoldExtOp(unsigned Opcode, const Register Op1, uint64_t Imm, const MachineRegisterInfo &MRI)
Definition Utils.cpp:929
LLVM_ABI MVT getMVTForLLT(LLT Ty)
Get a rough equivalent of an MVT for a given LLT.
LLVM_READONLY APFloat maximum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2019 maximum semantics.
Definition APFloat.h:1816
GISelWorkList< 4 > SmallInstListTy
Definition Utils.h:555
LLVM_ABI bool isNullOrNullSplat(const MachineInstr &MI, const MachineRegisterInfo &MRI, bool AllowUndefs=false)
Return true if the value is a constant 0 integer or a splatted vector of a constant 0 integer (with n...
Definition Utils.cpp:1699
LLVM_ABI MachineInstr * getDefIgnoringCopies(Register Reg, const MachineRegisterInfo &MRI)
Find the def instruction for Reg, folding away any trivial copies.
Definition Utils.cpp:520
bool isPreISelGenericOptimizationHint(unsigned Opcode)
LLVM_ABI void reportGISelWarning(MachineFunction &MF, MachineOptimizationRemarkEmitter &MORE, MachineOptimizationRemarkMissed &R)
Report an ISel warning as a missed optimization remark to the LLVMContext's diagnostic stream.
Definition Utils.cpp:259
LLVM_ABI bool isGuaranteedNotToBeUndef(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be undef, but may be poison.
LLVM_ABI bool isConstTrueVal(const TargetLowering &TLI, int64_t Val, bool IsVector, bool IsFP)
Returns true if given the TargetLowering's boolean contents information, the value Val contains a tru...
Definition Utils.cpp:1765
LLVM_ABI LLVM_READNONE LLT getLCMType(LLT OrigTy, LLT TargetTy)
Return the least common multiple type of OrigTy and TargetTy, by changing the number of vector elemen...
Definition Utils.cpp:1300
LLVM_ABI bool isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL, bool OrZero=false, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Return true if the given value is known to have exactly one bit set when defined.
LLVM_ABI std::optional< int64_t > getIConstantVRegSExtVal(Register VReg, const MachineRegisterInfo &MRI)
If VReg is defined by a G_CONSTANT fits in int64_t returns it.
Definition Utils.cpp:321
LLVM_ABI std::optional< APInt > ConstantFoldBinOp(unsigned Opcode, const Register Op1, const Register Op2, const MachineRegisterInfo &MRI)
Definition Utils.cpp:685
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
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 const APInt & getIConstantFromReg(Register VReg, const MachineRegisterInfo &MRI)
VReg is defined by a G_CONSTANT, return the corresponding value.
Definition Utils.cpp:312
LLVM_READONLY APFloat maxnum(const APFloat &A, const APFloat &B)
Implements IEEE-754 2008 maxNum semantics.
Definition APFloat.h:1771
LLVM_ABI bool isConstantOrConstantVector(const MachineInstr &MI, const MachineRegisterInfo &MRI, bool AllowFP=true, bool AllowOpaqueConstants=true)
Return true if the specified instruction is known to be a constant, or a vector of constants.
Definition Utils.cpp:1657
constexpr unsigned MaxAnalysisRecursionDepth
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
LLVM_ABI bool canReplaceReg(Register DstReg, Register SrcReg, MachineRegisterInfo &MRI)
Check if DstReg can be replaced with SrcReg depending on the register constraints.
Definition Utils.cpp:207
LLVM_READONLY APFloat minimumnum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2019 minimumNumber semantics.
Definition APFloat.h:1802
LLVM_ABI void saveUsesAndErase(MachineInstr &MI, MachineRegisterInfo &MRI, LostDebugLocObserver *LocObserver, SmallInstListTy &DeadInstChain)
Definition Utils.cpp:1802
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void reportGISelFailure(MachineFunction &MF, MachineOptimizationRemarkEmitter &MORE, MachineOptimizationRemarkMissed &R)
Report an ISel error as a missed optimization remark to the LLVMContext's diagnostic stream.
Definition Utils.cpp:265
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:149
LLVM_ABI std::optional< ValueAndVReg > getAnyConstantVRegValWithLookThrough(Register VReg, const MachineRegisterInfo &MRI, bool LookThroughInstrs=true, bool LookThroughAnyExt=false)
If VReg is defined by a statically evaluable chain of instructions rooted on a G_CONSTANT or G_FCONST...
Definition Utils.cpp:446
LLVM_ABI bool isBuildVectorAllOnes(const MachineInstr &MI, const MachineRegisterInfo &MRI, bool AllowUndef=false)
Return true if the specified instruction is a G_BUILD_VECTOR or G_BUILD_VECTOR_TRUNC where all of the...
Definition Utils.cpp:1599
LLVM_ABI bool canCreateUndefOrPoison(const Operator *Op, bool ConsiderFlagsAndMetadata=true)
canCreateUndefOrPoison returns true if Op can create undef or poison from non-undef & non-poison oper...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI SmallVector< APInt > ConstantFoldVectorBinop(unsigned Opcode, const Register Op1, const Register Op2, const MachineRegisterInfo &MRI)
Tries to constant fold a vector binop with sources Op1 and Op2.
Definition Utils.cpp:832
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_ABI std::optional< FPValueAndVReg > getFConstantSplat(Register VReg, const MachineRegisterInfo &MRI, bool AllowUndef=true)
Returns a floating point scalar constant of a build vector splat if it exists.
Definition Utils.cpp:1586
bool includesPoison(UndefPoisonKind Kind)
Returns true if Kind includes the Poison bit.
Definition UndefPoison.h:27
LLVM_ABI std::optional< APInt > ConstantFoldCastOp(unsigned Opcode, LLT DstTy, const Register Op0, const MachineRegisterInfo &MRI)
Definition Utils.cpp:946
LLVM_ABI void extractParts(Register Reg, LLT Ty, int NumParts, SmallVectorImpl< Register > &VRegs, MachineIRBuilder &MIRBuilder, MachineRegisterInfo &MRI)
Helper function to split a wide generic register into bitwise blocks with the given Type (which impli...
Definition Utils.cpp:534
LLVM_ABI void getSelectionDAGFallbackAnalysisUsage(AnalysisUsage &AU)
Modify analysis usage so it preserves passes required for the SelectionDAG fallback.
Definition Utils.cpp:1296
LLVM_ABI bool canLowerMemCpyFamily(const MachineInstr &MI, const MachineRegisterInfo &MRI, unsigned MaxLen, Register &Dst, Register &Src, uint64_t &KnownLen, Align &Alignment, bool &DstAlignCanChange, std::vector< LLT > &MemOps)
Matcher for memcpy-like instructions.
Definition Utils.cpp:2305
LLVM_ABI LLVM_READNONE LLT getCoverTy(LLT OrigTy, LLT TargetTy)
Return smallest type that covers both OrigTy and TargetTy and is multiple of TargetTy.
Definition Utils.cpp:1367
bool includesUndef(UndefPoisonKind Kind)
Returns true if Kind includes the Undef bit.
Definition UndefPoison.h:33
LLVM_READONLY APFloat minnum(const APFloat &A, const APFloat &B)
Implements IEEE-754 2008 minNum semantics.
Definition APFloat.h:1752
LLVM_ABI SmallVector< APFloat > ConstantFoldUnaryFPOp(unsigned Opcode, LLT DstTy, Register Src, const MachineRegisterInfo &MRI)
Tries to constant fold a unary floating-point operation on Src.
Definition Utils.cpp:1031
LLVM_ABI unsigned getInverseGMinMaxOpcode(unsigned MinMaxOpc)
Returns the inverse opcode of MinMaxOpc, which is a generic min/max opcode like G_SMIN.
Definition Utils.cpp:286
LLVM_ABI SmallVector< APFloat > ConstantFoldVectorFPBinop(unsigned Opcode, const Register Op1, const Register Op2, const MachineRegisterInfo &MRI)
Tries to constant fold a vector floating-point binop with sources Op1 and Op2.
Definition Utils.cpp:855
@ Mul
Product of integers.
@ Fast
Assign the register banks as fast as possible (default).
bool isTargetSpecificOpcode(unsigned Opcode)
Check whether the given Opcode is a target-specific opcode.
DWARFExpression::Operation Op
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.
LLVM_ABI std::optional< FPValueAndVReg > getFConstantVRegValWithLookThrough(Register VReg, const MachineRegisterInfo &MRI, bool LookThroughInstrs=true)
If VReg is defined by a statically evaluable chain of instructions rooted on a G_FCONSTANT returns it...
Definition Utils.cpp:454
LLVM_ABI bool isConstFalseVal(const TargetLowering &TLI, int64_t Val, bool IsVector, bool IsFP)
Definition Utils.cpp:1778
constexpr unsigned BitWidth
LLVM_ABI bool isBuildVectorConstantSplat(const Register Reg, const MachineRegisterInfo &MRI, int64_t SplatValue, bool AllowUndef)
Return true if the specified register is defined by G_BUILD_VECTOR or G_BUILD_VECTOR_TRUNC where all ...
Definition Utils.cpp:1512
LLVM_ABI void eraseInstr(MachineInstr &MI, MachineRegisterInfo &MRI, LostDebugLocObserver *LocObserver=nullptr)
Definition Utils.cpp:1832
DiagnosticSeverity
Defines the different supported severity of a diagnostic.
LLVM_ABI Register constrainRegToClass(MachineRegisterInfo &MRI, const TargetInstrInfo &TII, const RegisterBankInfo &RBI, Register Reg, const TargetRegisterClass &RegClass)
Try to constrain Reg to the specified register class.
Definition Utils.cpp:54
LLVM_ABI int64_t getICmpTrueVal(const TargetLowering &TLI, bool IsVector, bool IsFP)
Returns an integer representing true, as defined by the TargetBooleanContents.
Definition Utils.cpp:1790
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI std::optional< ValueAndVReg > getIConstantVRegValWithLookThrough(Register VReg, const MachineRegisterInfo &MRI, bool LookThroughInstrs=true)
If VReg is defined by a statically evaluable chain of instructions rooted on a G_CONSTANT returns its...
Definition Utils.cpp:440
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1788
UndefPoisonKind
Enumeration to track whether we are interested in Undef, Poison, or both.
Definition UndefPoison.h:20
LLVM_ABI bool isPreISelGenericFloatingPointOpcode(unsigned Opc)
Returns whether opcode Opc is a pre-isel generic floating-point opcode, having only floating-point op...
Definition Utils.cpp:1860
LLVM_ABI std::optional< DefinitionAndSourceRegister > getDefSrcRegIgnoringCopies(Register Reg, const MachineRegisterInfo &MRI)
Find the def instruction for Reg, and underlying value Register folding away any copies.
Definition Utils.cpp:495
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
LLVM_ABI SmallVector< APInt > ConstantFoldUnaryIntOp(unsigned Opcode, LLT DstTy, Register Src, const MachineRegisterInfo &MRI)
Tries to constant fold a unary integer operation (G_CTLZ, G_CTTZ, G_CTPOP and their _ZERO_POISON vari...
Definition Utils.cpp:983
LLVM_ABI std::optional< Register > getVectorSplat(const MachineInstr &MI, const MachineRegisterInfo &MRI)
Definition Utils.cpp:1605
LLVM_ABI void eraseInstrs(ArrayRef< MachineInstr * > DeadInstrs, MachineRegisterInfo &MRI, LostDebugLocObserver *LocObserver=nullptr)
Definition Utils.cpp:1817
LLVM_ABI void salvageDebugInfoForDbgValue(const MachineRegisterInfo &MRI, MachineInstr &MI, ArrayRef< MachineOperand * > DbgUsers)
Assuming the instruction MI is going to be deleted, attempt to salvage debug users of MI by writing t...
LLVM_ABI Register getSrcRegIgnoringCopies(Register Reg, const MachineRegisterInfo &MRI)
Find the source register for Reg, folding away any trivial copies.
Definition Utils.cpp:527
LLVM_ABI LLVM_READNONE LLT getGCDType(LLT OrigTy, LLT TargetTy)
Return a type where the total size is the greatest common divisor of OrigTy and TargetTy.
Definition Utils.cpp:1388
LLVM_ABI bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be poison, but may be undef.
T bit_floor(T Value)
Returns the largest integral power of two no greater than Value if Value is nonzero.
Definition bit.h:347
LLVM_READONLY APFloat minimum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2019 minimum semantics.
Definition APFloat.h:1789
LLVM_READONLY APFloat maximumnum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2019 maximumNumber semantics.
Definition APFloat.h:1829
LLVM_ABI std::optional< int64_t > getIConstantSplatSExtVal(const Register Reg, const MachineRegisterInfo &MRI)
Definition Utils.cpp:1571
LLVM_ABI bool isAssertMI(const MachineInstr &MI)
Returns true if the instruction MI is one of the assert instructions.
Definition Utils.cpp:2145
LLVM_ABI void extractVectorParts(Register Reg, unsigned NumElts, SmallVectorImpl< Register > &VRegs, MachineIRBuilder &MIRBuilder, MachineRegisterInfo &MRI)
Version which handles irregular sub-vector splits.
Definition Utils.cpp:637
LLVM_ABI Constant * ConstantFoldFP(double(*NativeFP)(double), const APFloat &V, Type *Ty, DenormalMode DenormMode=DenormalMode::getIEEE())
Evaluate NativeFP on V using the host libm, then convert the result to Ty.
LLVM_ABI int getSplatIndex(ArrayRef< int > Mask)
If all non-negative Mask elements are the same value, return that value.
LLVM_ABI bool isTriviallyDead(const MachineInstr &MI, const MachineRegisterInfo &MRI)
Check whether an instruction MI is dead: it only defines dead virtual registers, and doesn't have oth...
Definition Utils.cpp:228
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
LLVM_ABI Align inferAlignFromPtrInfo(MachineFunction &MF, const MachinePointerInfo &MPO)
Definition Utils.cpp:879
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
#define MORE()
Definition regcomp.c:247
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
Simple struct used to hold a Register value and the instruction which defines it.
Definition Utils.h:249
This class contains a discriminated union of information about pointers in memory operands,...
LLVM_ABI unsigned getAddrSpace() const
Return the LLVM IR address space number that this pointer points into.
int64_t Offset
Offset - This is an offset from the base Value*.
PointerUnion< const Value *, const PseudoSourceValue * > V
This is the IR pointer value for the access, or it is null if unknown.
static MemOp Set(uint64_t Size, bool DstAlignCanChange, Align DstAlign, bool IsZeroMemset, bool IsVolatile)
static MemOp Copy(uint64_t Size, bool DstAlignCanChange, Align DstAlign, Align SrcAlign, bool IsVolatile, bool MemcpyStrSrc=false)
static MemOp Move(uint64_t Size, bool DstAlignCanChange, Align DstAlign, Align SrcAlign, bool IsVolatile)
bool isVolatile() const
Simple struct used to hold a constant integer value and a virtual register.
Definition Utils.h:194