LLVM 23.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"
36#include "llvm/IR/Constants.h"
40#include <limits>
41#include <numeric>
42#include <optional>
43#include <tuple>
44
45#define DEBUG_TYPE "globalisel-utils"
46
47using namespace llvm;
48using namespace MIPatternMatch;
49
51 const TargetInstrInfo &TII,
52 const RegisterBankInfo &RBI, Register Reg,
53 const TargetRegisterClass &RegClass) {
54 if (!RBI.constrainGenericRegister(Reg, RegClass, MRI))
55 return MRI.createVirtualRegister(&RegClass);
56
57 return Reg;
58}
59
61 const MachineFunction &MF, const TargetRegisterInfo &TRI,
63 const RegisterBankInfo &RBI, MachineInstr &InsertPt,
64 const TargetRegisterClass &RegClass, MachineOperand &RegMO) {
65 Register Reg = RegMO.getReg();
66 // Assume physical registers are properly constrained.
67 assert(Reg.isVirtual() && "PhysReg not implemented");
68
69 // Save the old register class to check whether
70 // the change notifications will be required.
71 // TODO: A better approach would be to pass
72 // the observers to constrainRegToClass().
73 auto *OldRegClass = MRI.getRegClassOrNull(Reg);
74 Register ConstrainedReg = constrainRegToClass(MRI, TII, RBI, Reg, RegClass);
75 // If we created a new virtual register because the class is not compatible
76 // then create a copy between the new and the old register.
77 if (ConstrainedReg != Reg) {
78 MachineBasicBlock::iterator InsertIt(&InsertPt);
79 MachineBasicBlock &MBB = *InsertPt.getParent();
80 // FIXME: The copy needs to have the classes constrained for its operands.
81 // Use operand's regbank to get the class for old register (Reg).
82 if (RegMO.isUse()) {
83 BuildMI(MBB, InsertIt, InsertPt.getDebugLoc(),
84 TII.get(TargetOpcode::COPY), ConstrainedReg)
85 .addReg(Reg);
86 } else {
87 assert(RegMO.isDef() && "Must be a definition");
88 BuildMI(MBB, std::next(InsertIt), InsertPt.getDebugLoc(),
89 TII.get(TargetOpcode::COPY), Reg)
90 .addReg(ConstrainedReg);
91 }
92 if (GISelChangeObserver *Observer = MF.getObserver()) {
93 Observer->changingInstr(*RegMO.getParent());
94 }
95 RegMO.setReg(ConstrainedReg);
96 if (GISelChangeObserver *Observer = MF.getObserver()) {
97 Observer->changedInstr(*RegMO.getParent());
98 }
99 } else if (OldRegClass != MRI.getRegClassOrNull(Reg)) {
100 if (GISelChangeObserver *Observer = MF.getObserver()) {
101 if (!RegMO.isDef()) {
102 MachineInstr *RegDef = MRI.getVRegDef(Reg);
103 Observer->changedInstr(*RegDef);
104 }
105 Observer->changingAllUsesOfReg(MRI, Reg);
106 Observer->finishedChangingAllUsesOfReg();
107 }
108 }
109 return ConstrainedReg;
110}
111
113 const MachineFunction &MF, const TargetRegisterInfo &TRI,
115 const RegisterBankInfo &RBI, MachineInstr &InsertPt, const MCInstrDesc &II,
116 MachineOperand &RegMO, unsigned OpIdx) {
117 Register Reg = RegMO.getReg();
118 // Assume physical registers are properly constrained.
119 assert(Reg.isVirtual() && "PhysReg not implemented");
120
121 const TargetRegisterClass *OpRC = TII.getRegClass(II, OpIdx);
122 // Some of the target independent instructions, like COPY, may not impose any
123 // register class constraints on some of their operands: If it's a use, we can
124 // skip constraining as the instruction defining the register would constrain
125 // it.
126
127 if (OpRC) {
128 // Obtain the RC from incoming regbank if it is a proper sub-class. Operands
129 // can have multiple regbanks for a superclass that combine different
130 // register types (E.g., AMDGPU's VGPR and AGPR). The regbank ambiguity
131 // resolved by targets during regbankselect should not be overridden.
132 if (const auto *SubRC = TRI.getCommonSubClass(
133 OpRC, TRI.getConstrainedRegClassForOperand(RegMO, MRI)))
134 OpRC = SubRC;
135
136 OpRC = TRI.getAllocatableClass(OpRC);
137 }
138
139 if (!OpRC) {
140 assert((!isTargetSpecificOpcode(II.getOpcode()) || RegMO.isUse()) &&
141 "Register class constraint is required unless either the "
142 "instruction is target independent or the operand is a use");
143 // FIXME: Just bailing out like this here could be not enough, unless we
144 // expect the users of this function to do the right thing for PHIs and
145 // COPY:
146 // v1 = COPY v0
147 // v2 = COPY v1
148 // v1 here may end up not being constrained at all. Please notice that to
149 // reproduce the issue we likely need a destination pattern of a selection
150 // rule producing such extra copies, not just an input GMIR with them as
151 // every existing target using selectImpl handles copies before calling it
152 // and they never reach this function.
153 return Reg;
154 }
155 return constrainOperandRegClass(MF, TRI, MRI, TII, RBI, InsertPt, *OpRC,
156 RegMO);
157}
158
160 const TargetInstrInfo &TII,
161 const TargetRegisterInfo &TRI,
162 const RegisterBankInfo &RBI) {
163 assert(!isPreISelGenericOpcode(I.getOpcode()) &&
164 "A selected instruction is expected");
165 MachineBasicBlock &MBB = *I.getParent();
166 MachineFunction &MF = *MBB.getParent();
168
169 for (unsigned OpI = 0, OpE = I.getNumExplicitOperands(); OpI != OpE; ++OpI) {
170 MachineOperand &MO = I.getOperand(OpI);
171
172 // There's nothing to be done on non-register operands.
173 if (!MO.isReg())
174 continue;
175
176 LLVM_DEBUG(dbgs() << "Converting operand: " << MO << '\n');
177
178 Register Reg = MO.getReg();
179 // Physical registers don't need to be constrained.
180 if (Reg.isPhysical())
181 continue;
182
183 // Register operands with a value of 0 (e.g. predicate operands) don't need
184 // to be constrained.
185 if (Reg == 0)
186 continue;
187
188 // If the operand is a vreg, we should constrain its regclass, and only
189 // insert COPYs if that's impossible.
190 // constrainOperandRegClass does that for us.
191 constrainOperandRegClass(MF, TRI, MRI, TII, RBI, I, I.getDesc(), MO, OpI);
192
193 // Tie uses to defs as indicated in MCInstrDesc if this hasn't already been
194 // done.
195 if (MO.isUse()) {
196 int DefIdx = I.getDesc().getOperandConstraint(OpI, MCOI::TIED_TO);
197 if (DefIdx != -1 && !I.isRegTiedToUseOperand(DefIdx))
198 I.tieOperands(DefIdx, OpI);
199 }
200 }
201}
202
204 MachineRegisterInfo &MRI) {
205 // Give up if either DstReg or SrcReg is a physical register.
206 if (DstReg.isPhysical() || SrcReg.isPhysical())
207 return false;
208 // Give up if the types don't match.
209 if (MRI.getType(DstReg) != MRI.getType(SrcReg))
210 return false;
211 // Replace if either DstReg has no constraints or the register
212 // constraints match.
213 const auto &DstRBC = MRI.getRegClassOrRegBank(DstReg);
214 if (!DstRBC || DstRBC == MRI.getRegClassOrRegBank(SrcReg))
215 return true;
216
217 // Otherwise match if the Src is already a regclass that is covered by the Dst
218 // RegBank.
219 return isa<const RegisterBank *>(DstRBC) && MRI.getRegClassOrNull(SrcReg) &&
220 cast<const RegisterBank *>(DstRBC)->covers(
221 *MRI.getRegClassOrNull(SrcReg));
222}
223
225 const MachineRegisterInfo &MRI) {
226 // Instructions without side-effects are dead iff they only define dead regs.
227 // This function is hot and this loop returns early in the common case,
228 // so only perform additional checks before this if absolutely necessary.
229 for (const auto &MO : MI.all_defs()) {
230 Register Reg = MO.getReg();
231 if (Reg.isPhysical() || !MRI.use_nodbg_empty(Reg))
232 return false;
233 }
234 return MI.wouldBeTriviallyDead();
235}
236
238 MachineFunction &MF,
241 bool IsGlobalISelAbortEnabled =
243 bool IsFatal = Severity == DS_Error && IsGlobalISelAbortEnabled;
244 // Print the function name explicitly if we don't have a debug location (which
245 // makes the diagnostic less useful) or if we're going to emit a raw error.
246 if (!R.getLocation().isValid() || IsFatal)
247 R << (" (in function: " + MF.getName() + ")").str();
248
249 if (IsFatal)
250 reportFatalUsageError(Twine(R.getMsg()));
251 else
252 MORE.emit(R);
253}
254
260
267
270 const char *PassName, StringRef Msg,
271 const MachineInstr &MI) {
272 MachineOptimizationRemarkMissed R(PassName, "GISelFailure: ",
273 MI.getDebugLoc(), MI.getParent());
274 R << Msg;
275 // Printing MI is expensive; only do it if expensive remarks are enabled.
277 MORE.allowExtraAnalysis(PassName))
278 R << ": " << ore::MNV("Inst", MI);
279 reportGISelFailure(MF, MORE, R);
280}
281
282unsigned llvm::getInverseGMinMaxOpcode(unsigned MinMaxOpc) {
283 switch (MinMaxOpc) {
284 case TargetOpcode::G_SMIN:
285 return TargetOpcode::G_SMAX;
286 case TargetOpcode::G_SMAX:
287 return TargetOpcode::G_SMIN;
288 case TargetOpcode::G_UMIN:
289 return TargetOpcode::G_UMAX;
290 case TargetOpcode::G_UMAX:
291 return TargetOpcode::G_UMIN;
292 default:
293 llvm_unreachable("unrecognized opcode");
294 }
295}
296
297std::optional<APInt> llvm::getIConstantVRegVal(Register VReg,
298 const MachineRegisterInfo &MRI) {
299 std::optional<ValueAndVReg> ValAndVReg = getIConstantVRegValWithLookThrough(
300 VReg, MRI, /*LookThroughInstrs*/ false);
301 assert((!ValAndVReg || ValAndVReg->VReg == VReg) &&
302 "Value found while looking through instrs");
303 if (!ValAndVReg)
304 return std::nullopt;
305 return ValAndVReg->Value;
306}
307
309 const MachineRegisterInfo &MRI) {
310 MachineInstr *Const = MRI.getVRegDef(Reg);
311 assert((Const && Const->getOpcode() == TargetOpcode::G_CONSTANT) &&
312 "expected a G_CONSTANT on Reg");
313 return Const->getOperand(1).getCImm()->getValue();
314}
315
316std::optional<int64_t>
318 std::optional<APInt> Val = getIConstantVRegVal(VReg, MRI);
319 if (Val && Val->getBitWidth() <= 64)
320 return Val->getSExtValue();
321 return std::nullopt;
322}
323
324namespace {
325
326// This function is used in many places, and as such, it has some
327// micro-optimizations to try and make it as fast as it can be.
328//
329// - We use template arguments to avoid an indirect call caused by passing a
330// function_ref/std::function
331// - GetAPCstValue does not return std::optional<APInt> as that's expensive.
332// Instead it returns true/false and places the result in a pre-constructed
333// APInt.
334//
335// Please change this function carefully and benchmark your changes.
336template <bool (*IsConstantOpcode)(const MachineInstr *),
337 bool (*GetAPCstValue)(const MachineInstr *MI, APInt &)>
338std::optional<ValueAndVReg>
339getConstantVRegValWithLookThrough(Register VReg, const MachineRegisterInfo &MRI,
340 bool LookThroughInstrs = true,
341 bool LookThroughAnyExt = false) {
344
345 while ((MI = MRI.getVRegDef(VReg)) && !IsConstantOpcode(MI) &&
346 LookThroughInstrs) {
347 switch (MI->getOpcode()) {
348 case TargetOpcode::G_ANYEXT:
349 if (!LookThroughAnyExt)
350 return std::nullopt;
351 [[fallthrough]];
352 case TargetOpcode::G_TRUNC:
353 case TargetOpcode::G_SEXT:
354 case TargetOpcode::G_ZEXT:
355 SeenOpcodes.push_back(std::make_pair(
356 MI->getOpcode(),
357 MRI.getType(MI->getOperand(0).getReg()).getSizeInBits()));
358 VReg = MI->getOperand(1).getReg();
359 break;
360 case TargetOpcode::COPY:
361 VReg = MI->getOperand(1).getReg();
362 if (VReg.isPhysical())
363 return std::nullopt;
364 break;
365 case TargetOpcode::G_INTTOPTR:
366 VReg = MI->getOperand(1).getReg();
367 break;
368 default:
369 return std::nullopt;
370 }
371 }
372 if (!MI || !IsConstantOpcode(MI))
373 return std::nullopt;
374
375 APInt Val;
376 if (!GetAPCstValue(MI, Val))
377 return std::nullopt;
378 for (auto &Pair : reverse(SeenOpcodes)) {
379 switch (Pair.first) {
380 case TargetOpcode::G_TRUNC:
381 Val = Val.trunc(Pair.second);
382 break;
383 case TargetOpcode::G_ANYEXT:
384 case TargetOpcode::G_SEXT:
385 Val = Val.sext(Pair.second);
386 break;
387 case TargetOpcode::G_ZEXT:
388 Val = Val.zext(Pair.second);
389 break;
390 }
391 }
392
393 return ValueAndVReg{std::move(Val), VReg};
394}
395
396bool isIConstant(const MachineInstr *MI) {
397 if (!MI)
398 return false;
399 return MI->getOpcode() == TargetOpcode::G_CONSTANT;
400}
401
402bool isFConstant(const MachineInstr *MI) {
403 if (!MI)
404 return false;
405 return MI->getOpcode() == TargetOpcode::G_FCONSTANT;
406}
407
408bool isAnyConstant(const MachineInstr *MI) {
409 if (!MI)
410 return false;
411 unsigned Opc = MI->getOpcode();
412 return Opc == TargetOpcode::G_CONSTANT || Opc == TargetOpcode::G_FCONSTANT;
413}
414
415bool getCImmAsAPInt(const MachineInstr *MI, APInt &Result) {
416 const MachineOperand &CstVal = MI->getOperand(1);
417 if (!CstVal.isCImm())
418 return false;
419 Result = CstVal.getCImm()->getValue();
420 return true;
421}
422
423bool getCImmOrFPImmAsAPInt(const MachineInstr *MI, APInt &Result) {
424 const MachineOperand &CstVal = MI->getOperand(1);
425 if (CstVal.isCImm())
426 Result = CstVal.getCImm()->getValue();
427 else if (CstVal.isFPImm())
429 else
430 return false;
431 return true;
432}
433
434} // end anonymous namespace
435
437 Register VReg, const MachineRegisterInfo &MRI, bool LookThroughInstrs) {
438 return getConstantVRegValWithLookThrough<isIConstant, getCImmAsAPInt>(
439 VReg, MRI, LookThroughInstrs);
440}
441
443 Register VReg, const MachineRegisterInfo &MRI, bool LookThroughInstrs,
444 bool LookThroughAnyExt) {
445 return getConstantVRegValWithLookThrough<isAnyConstant,
446 getCImmOrFPImmAsAPInt>(
447 VReg, MRI, LookThroughInstrs, LookThroughAnyExt);
448}
449
450std::optional<FPValueAndVReg> llvm::getFConstantVRegValWithLookThrough(
451 Register VReg, const MachineRegisterInfo &MRI, bool LookThroughInstrs) {
452 auto Reg =
453 getConstantVRegValWithLookThrough<isFConstant, getCImmOrFPImmAsAPInt>(
454 VReg, MRI, LookThroughInstrs);
455 if (!Reg)
456 return std::nullopt;
457
458 APFloat FloatVal(getFltSemanticForLLT(LLT::scalar(Reg->Value.getBitWidth())),
459 Reg->Value);
460 return FPValueAndVReg{FloatVal, Reg->VReg};
461}
462
463const ConstantFP *
465 MachineInstr *MI = MRI.getVRegDef(VReg);
466 if (TargetOpcode::G_FCONSTANT != MI->getOpcode())
467 return nullptr;
468 return MI->getOperand(1).getFPImm();
469}
470
471std::optional<DefinitionAndSourceRegister>
473 Register DefSrcReg = Reg;
474 // This assumes that the code is in SSA form, so there should only be one
475 // definition.
476 auto DefIt = MRI.def_begin(Reg);
477 if (DefIt == MRI.def_end())
478 return {};
479 MachineOperand &DefOpnd = *DefIt;
480 MachineInstr *DefMI = DefOpnd.getParent();
481 auto DstTy = MRI.getType(DefOpnd.getReg());
482 if (!DstTy.isValid())
483 return std::nullopt;
484 unsigned Opc = DefMI->getOpcode();
485 while (Opc == TargetOpcode::COPY || isPreISelGenericOptimizationHint(Opc)) {
486 Register SrcReg = DefMI->getOperand(1).getReg();
487 auto SrcTy = MRI.getType(SrcReg);
488 if (!SrcTy.isValid())
489 break;
490 DefMI = MRI.getVRegDef(SrcReg);
491 DefSrcReg = SrcReg;
492 Opc = DefMI->getOpcode();
493 }
494 return DefinitionAndSourceRegister{DefMI, DefSrcReg};
495}
496
498 const MachineRegisterInfo &MRI) {
499 std::optional<DefinitionAndSourceRegister> DefSrcReg =
501 return DefSrcReg ? DefSrcReg->MI : nullptr;
502}
503
505 const MachineRegisterInfo &MRI) {
506 std::optional<DefinitionAndSourceRegister> DefSrcReg =
508 return DefSrcReg ? DefSrcReg->Reg : Register();
509}
510
511void llvm::extractParts(Register Reg, LLT Ty, int NumParts,
513 MachineIRBuilder &MIRBuilder,
514 MachineRegisterInfo &MRI) {
515 for (int i = 0; i < NumParts; ++i)
517 MIRBuilder.buildUnmerge(VRegs, Reg);
518}
519
520bool llvm::extractParts(Register Reg, LLT RegTy, LLT MainTy, LLT &LeftoverTy,
522 SmallVectorImpl<Register> &LeftoverRegs,
523 MachineIRBuilder &MIRBuilder,
524 MachineRegisterInfo &MRI) {
525 assert(!LeftoverTy.isValid() && "this is an out argument");
526
527 unsigned RegSize = RegTy.getSizeInBits();
528 unsigned MainSize = MainTy.getSizeInBits();
529 unsigned NumParts = RegSize / MainSize;
530 unsigned LeftoverSize = RegSize - NumParts * MainSize;
531
532 // Use an unmerge when possible.
533 if (LeftoverSize == 0) {
534 for (unsigned I = 0; I < NumParts; ++I)
535 VRegs.push_back(MRI.createGenericVirtualRegister(MainTy));
536 MIRBuilder.buildUnmerge(VRegs, Reg);
537 return true;
538 }
539
540 // Try to use unmerge for irregular vector split where possible
541 // For example when splitting a <6 x i32> into <4 x i32> with <2 x i32>
542 // leftover, it becomes:
543 // <2 x i32> %2, <2 x i32>%3, <2 x i32> %4 = G_UNMERGE_VALUE <6 x i32> %1
544 // <4 x i32> %5 = G_CONCAT_VECTOR <2 x i32> %2, <2 x i32> %3
545 if (RegTy.isVector() && MainTy.isVector()) {
546 unsigned RegNumElts = RegTy.getNumElements();
547 unsigned MainNumElts = MainTy.getNumElements();
548 unsigned LeftoverNumElts = RegNumElts % MainNumElts;
549 // If can unmerge to LeftoverTy, do it
550 if (MainNumElts % LeftoverNumElts == 0 &&
551 RegNumElts % LeftoverNumElts == 0 &&
552 RegTy.getScalarSizeInBits() == MainTy.getScalarSizeInBits() &&
553 LeftoverNumElts > 1) {
554 LeftoverTy = LLT::fixed_vector(LeftoverNumElts, RegTy.getElementType());
555
556 // Unmerge the SrcReg to LeftoverTy vectors
557 SmallVector<Register, 4> UnmergeValues;
558 extractParts(Reg, LeftoverTy, RegNumElts / LeftoverNumElts, UnmergeValues,
559 MIRBuilder, MRI);
560
561 // Find how many LeftoverTy makes one MainTy
562 unsigned LeftoverPerMain = MainNumElts / LeftoverNumElts;
563 unsigned NumOfLeftoverVal =
564 ((RegNumElts % MainNumElts) / LeftoverNumElts);
565
566 // Create as many MainTy as possible using unmerged value
567 SmallVector<Register, 4> MergeValues;
568 for (unsigned I = 0; I < UnmergeValues.size() - NumOfLeftoverVal; I++) {
569 MergeValues.push_back(UnmergeValues[I]);
570 if (MergeValues.size() == LeftoverPerMain) {
571 VRegs.push_back(
572 MIRBuilder.buildMergeLikeInstr(MainTy, MergeValues).getReg(0));
573 MergeValues.clear();
574 }
575 }
576 // Populate LeftoverRegs with the leftovers
577 for (unsigned I = UnmergeValues.size() - NumOfLeftoverVal;
578 I < UnmergeValues.size(); I++) {
579 LeftoverRegs.push_back(UnmergeValues[I]);
580 }
581 return true;
582 }
583 }
584 // Perform irregular split. Leftover is last element of RegPieces.
585 if (MainTy.isVector()) {
586 SmallVector<Register, 8> RegPieces;
587 extractVectorParts(Reg, MainTy.getNumElements(), RegPieces, MIRBuilder,
588 MRI);
589 for (unsigned i = 0; i < RegPieces.size() - 1; ++i)
590 VRegs.push_back(RegPieces[i]);
591 LeftoverRegs.push_back(RegPieces[RegPieces.size() - 1]);
592 LeftoverTy = MRI.getType(LeftoverRegs[0]);
593 return true;
594 }
595
596 LeftoverTy = LLT::integer(LeftoverSize);
597 // For irregular sizes, extract the individual parts.
598 for (unsigned I = 0; I != NumParts; ++I) {
599 Register NewReg = MRI.createGenericVirtualRegister(MainTy);
600 VRegs.push_back(NewReg);
601 MIRBuilder.buildExtract(NewReg, Reg, MainSize * I);
602 }
603
604 for (unsigned Offset = MainSize * NumParts; Offset < RegSize;
605 Offset += LeftoverSize) {
606 Register NewReg = MRI.createGenericVirtualRegister(LeftoverTy);
607 LeftoverRegs.push_back(NewReg);
608 MIRBuilder.buildExtract(NewReg, Reg, Offset);
609 }
610
611 return true;
612}
613
614void llvm::extractVectorParts(Register Reg, unsigned NumElts,
616 MachineIRBuilder &MIRBuilder,
617 MachineRegisterInfo &MRI) {
618 LLT RegTy = MRI.getType(Reg);
619 assert(RegTy.isVector() && "Expected a vector type");
620
621 LLT EltTy = RegTy.getElementType();
622 LLT NarrowTy = (NumElts == 1) ? EltTy : LLT::fixed_vector(NumElts, EltTy);
623 unsigned RegNumElts = RegTy.getNumElements();
624 unsigned LeftoverNumElts = RegNumElts % NumElts;
625 unsigned NumNarrowTyPieces = RegNumElts / NumElts;
626
627 // Perfect split without leftover
628 if (LeftoverNumElts == 0)
629 return extractParts(Reg, NarrowTy, NumNarrowTyPieces, VRegs, MIRBuilder,
630 MRI);
631
632 // Irregular split. Provide direct access to all elements for artifact
633 // combiner using unmerge to elements. Then build vectors with NumElts
634 // elements. Remaining element(s) will be (used to build vector) Leftover.
636 extractParts(Reg, EltTy, RegNumElts, Elts, MIRBuilder, MRI);
637
638 unsigned Offset = 0;
639 // Requested sub-vectors of NarrowTy.
640 for (unsigned i = 0; i < NumNarrowTyPieces; ++i, Offset += NumElts) {
641 ArrayRef<Register> Pieces(&Elts[Offset], NumElts);
642 VRegs.push_back(MIRBuilder.buildMergeLikeInstr(NarrowTy, Pieces).getReg(0));
643 }
644
645 // Leftover element(s).
646 if (LeftoverNumElts == 1) {
647 VRegs.push_back(Elts[Offset]);
648 } else {
649 LLT LeftoverTy = LLT::fixed_vector(LeftoverNumElts, EltTy);
650 ArrayRef<Register> Pieces(&Elts[Offset], LeftoverNumElts);
651 VRegs.push_back(
652 MIRBuilder.buildMergeLikeInstr(LeftoverTy, Pieces).getReg(0));
653 }
654}
655
657 const MachineRegisterInfo &MRI) {
659 return DefMI && DefMI->getOpcode() == Opcode ? DefMI : nullptr;
660}
661
662APFloat llvm::getAPFloatFromSize(double Val, unsigned Size) {
663 if (Size == 32)
664 return APFloat(float(Val));
665 if (Size == 64)
666 return APFloat(Val);
667 if (Size != 16)
668 llvm_unreachable("Unsupported FPConstant size");
669 bool Ignored;
670 APFloat APF(Val);
672 return APF;
673}
674
675std::optional<APInt> llvm::ConstantFoldBinOp(unsigned Opcode,
676 const Register Op1,
677 const Register Op2,
678 const MachineRegisterInfo &MRI) {
679 auto MaybeOp2Cst = getAnyConstantVRegValWithLookThrough(Op2, MRI, false);
680 if (!MaybeOp2Cst)
681 return std::nullopt;
682
683 auto MaybeOp1Cst = getAnyConstantVRegValWithLookThrough(Op1, MRI, false);
684 if (!MaybeOp1Cst)
685 return std::nullopt;
686
687 const APInt &C1 = MaybeOp1Cst->Value;
688 const APInt &C2 = MaybeOp2Cst->Value;
689 switch (Opcode) {
690 default:
691 break;
692 case TargetOpcode::G_ADD:
693 return C1 + C2;
694 case TargetOpcode::G_PTR_ADD:
695 // Types can be of different width here.
696 // Result needs to be the same width as C1, so trunc or sext C2.
697 return C1 + C2.sextOrTrunc(C1.getBitWidth());
698 case TargetOpcode::G_AND:
699 return C1 & C2;
700 case TargetOpcode::G_ASHR:
701 return C1.ashr(C2);
702 case TargetOpcode::G_LSHR:
703 return C1.lshr(C2);
704 case TargetOpcode::G_MUL:
705 return C1 * C2;
706 case TargetOpcode::G_OR:
707 return C1 | C2;
708 case TargetOpcode::G_SHL:
709 return C1 << C2;
710 case TargetOpcode::G_SUB:
711 return C1 - C2;
712 case TargetOpcode::G_XOR:
713 return C1 ^ C2;
714 case TargetOpcode::G_UDIV:
715 if (!C2.getBoolValue())
716 break;
717 return C1.udiv(C2);
718 case TargetOpcode::G_SDIV:
719 if (!C2.getBoolValue())
720 break;
721 return C1.sdiv(C2);
722 case TargetOpcode::G_UREM:
723 if (!C2.getBoolValue())
724 break;
725 return C1.urem(C2);
726 case TargetOpcode::G_SREM:
727 if (!C2.getBoolValue())
728 break;
729 return C1.srem(C2);
730 case TargetOpcode::G_SMIN:
731 return APIntOps::smin(C1, C2);
732 case TargetOpcode::G_SMAX:
733 return APIntOps::smax(C1, C2);
734 case TargetOpcode::G_UMIN:
735 return APIntOps::umin(C1, C2);
736 case TargetOpcode::G_UMAX:
737 return APIntOps::umax(C1, C2);
738 }
739
740 return std::nullopt;
741}
742
743std::optional<APFloat>
744llvm::ConstantFoldFPBinOp(unsigned Opcode, const Register Op1,
745 const Register Op2, const MachineRegisterInfo &MRI) {
746 const ConstantFP *Op2Cst = getConstantFPVRegVal(Op2, MRI);
747 if (!Op2Cst)
748 return std::nullopt;
749
750 const ConstantFP *Op1Cst = getConstantFPVRegVal(Op1, MRI);
751 if (!Op1Cst)
752 return std::nullopt;
753
754 APFloat C1 = Op1Cst->getValueAPF();
755 const APFloat &C2 = Op2Cst->getValueAPF();
756 switch (Opcode) {
757 case TargetOpcode::G_FADD:
759 return C1;
760 case TargetOpcode::G_FSUB:
762 return C1;
763 case TargetOpcode::G_FMUL:
765 return C1;
766 case TargetOpcode::G_FDIV:
768 return C1;
769 case TargetOpcode::G_FREM:
770 C1.mod(C2);
771 return C1;
772 case TargetOpcode::G_FCOPYSIGN:
773 C1.copySign(C2);
774 return C1;
775 case TargetOpcode::G_FMINNUM:
776 return minnum(C1, C2);
777 case TargetOpcode::G_FMAXNUM:
778 return maxnum(C1, C2);
779 case TargetOpcode::G_FMINIMUM:
780 return minimum(C1, C2);
781 case TargetOpcode::G_FMAXIMUM:
782 return maximum(C1, C2);
783 case TargetOpcode::G_FMINIMUMNUM:
784 return minimumnum(C1, C2);
785 case TargetOpcode::G_FMAXIMUMNUM:
786 return maximumnum(C1, C2);
787 case TargetOpcode::G_FMINNUM_IEEE:
788 case TargetOpcode::G_FMAXNUM_IEEE:
789 // FIXME: These operations were unfortunately named. fminnum/fmaxnum do not
790 // follow the IEEE behavior for signaling nans and follow libm's fmin/fmax,
791 // and currently there isn't a nice wrapper in APFloat for the version with
792 // correct snan handling.
793 break;
794 default:
795 break;
796 }
797
798 return std::nullopt;
799}
800
802 const MachineRegisterInfo &MRI) {
803 if (auto *BV = getOpcodeDef<GBuildVector>(Reg, MRI))
804 return BV;
805
806 auto *Bitcast = getOpcodeDef(TargetOpcode::G_BITCAST, Reg, MRI);
807 if (!Bitcast)
808 return nullptr;
809
810 auto [Dst, DstTy, Src, SrcTy] = Bitcast->getFirst2RegLLTs();
811 if (!SrcTy.isVector() || !DstTy.isVector())
812 return nullptr;
813 if (SrcTy.getElementCount() != DstTy.getElementCount())
814 return nullptr;
815 if (SrcTy.getScalarSizeInBits() != DstTy.getScalarSizeInBits())
816 return nullptr;
817
818 return getOpcodeDef<GBuildVector>(Src, MRI);
819}
820
822llvm::ConstantFoldVectorBinop(unsigned Opcode, const Register Op1,
823 const Register Op2,
824 const MachineRegisterInfo &MRI) {
825 auto *SrcVec2 = getBuildVectorLikeDef(Op2, MRI);
826 if (!SrcVec2)
827 return SmallVector<APInt>();
828
829 auto *SrcVec1 = getBuildVectorLikeDef(Op1, MRI);
830 if (!SrcVec1)
831 return SmallVector<APInt>();
832
833 SmallVector<APInt> FoldedElements;
834 for (unsigned Idx = 0, E = SrcVec1->getNumSources(); Idx < E; ++Idx) {
835 auto MaybeCst = ConstantFoldBinOp(Opcode, SrcVec1->getSourceReg(Idx),
836 SrcVec2->getSourceReg(Idx), MRI);
837 if (!MaybeCst)
838 return SmallVector<APInt>();
839 FoldedElements.push_back(*MaybeCst);
840 }
841 return FoldedElements;
842}
843
845 const MachinePointerInfo &MPO) {
848 MachineFrameInfo &MFI = MF.getFrameInfo();
849 return commonAlignment(MFI.getObjectAlign(FSPV->getFrameIndex()),
850 MPO.Offset);
851 }
852
853 if (const Value *V = dyn_cast_if_present<const Value *>(MPO.V)) {
854 const Module *M = MF.getFunction().getParent();
855 return V->getPointerAlignment(M->getDataLayout());
856 }
857
858 return Align(1);
859}
860
862 const TargetInstrInfo &TII,
863 MCRegister PhysReg,
864 const TargetRegisterClass &RC,
865 const DebugLoc &DL, LLT RegTy) {
866 MachineBasicBlock &EntryMBB = MF.front();
868 Register LiveIn = MRI.getLiveInVirtReg(PhysReg);
869 if (LiveIn) {
870 MachineInstr *Def = MRI.getVRegDef(LiveIn);
871 if (Def) {
872 // FIXME: Should the verifier check this is in the entry block?
873 assert(Def->getParent() == &EntryMBB && "live-in copy not in entry block");
874 return LiveIn;
875 }
876
877 // It's possible the incoming argument register and copy was added during
878 // lowering, but later deleted due to being/becoming dead. If this happens,
879 // re-insert the copy.
880 } else {
881 // The live in register was not present, so add it.
882 LiveIn = MF.addLiveIn(PhysReg, &RC);
883 if (RegTy.isValid())
884 MRI.setType(LiveIn, RegTy);
885 }
886
887 BuildMI(EntryMBB, EntryMBB.begin(), DL, TII.get(TargetOpcode::COPY), LiveIn)
888 .addReg(PhysReg);
889 if (!EntryMBB.isLiveIn(PhysReg))
890 EntryMBB.addLiveIn(PhysReg);
891 return LiveIn;
892}
893
894std::optional<APInt> llvm::ConstantFoldExtOp(unsigned Opcode,
895 const Register Op1, uint64_t Imm,
896 const MachineRegisterInfo &MRI) {
897 auto MaybeOp1Cst = getIConstantVRegVal(Op1, MRI);
898 if (MaybeOp1Cst) {
899 switch (Opcode) {
900 default:
901 break;
902 case TargetOpcode::G_SEXT_INREG: {
903 LLT Ty = MRI.getType(Op1);
904 return MaybeOp1Cst->trunc(Imm).sext(Ty.getScalarSizeInBits());
905 }
906 }
907 }
908 return std::nullopt;
909}
910
911std::optional<APInt> llvm::ConstantFoldCastOp(unsigned Opcode, LLT DstTy,
912 const Register Op0,
913 const MachineRegisterInfo &MRI) {
914 std::optional<APInt> Val = getIConstantVRegVal(Op0, MRI);
915 if (!Val)
916 return Val;
917
918 const unsigned DstSize = DstTy.getScalarSizeInBits();
919
920 switch (Opcode) {
921 case TargetOpcode::G_SEXT:
922 return Val->sext(DstSize);
923 case TargetOpcode::G_ZEXT:
924 case TargetOpcode::G_ANYEXT:
925 // TODO: DAG considers target preference when constant folding any_extend.
926 return Val->zext(DstSize);
927 default:
928 break;
929 }
930
931 llvm_unreachable("unexpected cast opcode to constant fold");
932}
933
934std::optional<APFloat>
935llvm::ConstantFoldIntToFloat(unsigned Opcode, LLT DstTy, Register Src,
936 const MachineRegisterInfo &MRI) {
937 assert(Opcode == TargetOpcode::G_SITOFP || Opcode == TargetOpcode::G_UITOFP);
938 if (auto MaybeSrcVal = getIConstantVRegVal(Src, MRI)) {
939 APFloat DstVal(getFltSemanticForLLT(DstTy));
940 DstVal.convertFromAPInt(*MaybeSrcVal, Opcode == TargetOpcode::G_SITOFP,
942 return DstVal;
943 }
944 return std::nullopt;
945}
946
948llvm::ConstantFoldUnaryIntOp(unsigned Opcode, LLT DstTy, Register Src,
949 const MachineRegisterInfo &MRI) {
950 unsigned EltBits = DstTy.getScalarSizeInBits();
951 auto Fold = [Opcode, EltBits](const APInt &V) -> APInt {
952 switch (Opcode) {
953 case TargetOpcode::G_CTLZ:
954 case TargetOpcode::G_CTLZ_ZERO_POISON:
955 return APInt(EltBits, V.countl_zero());
956 case TargetOpcode::G_CTTZ:
957 case TargetOpcode::G_CTTZ_ZERO_POISON:
958 return APInt(EltBits, V.countr_zero());
959 case TargetOpcode::G_CTPOP:
960 return APInt(EltBits, V.popcount());
961 case TargetOpcode::G_ABS:
962 return V.abs();
963 case TargetOpcode::G_BSWAP:
964 return V.byteSwap();
965 case TargetOpcode::G_BITREVERSE:
966 return V.reverseBits();
967 }
968 llvm_unreachable("unexpected opcode in ConstantFoldUnaryIntOp");
969 };
970
971 auto tryFoldScalar = [&](Register R) -> std::optional<APInt> {
972 if (auto MaybeCst = getIConstantVRegVal(R, MRI))
973 return Fold(*MaybeCst);
974 return std::nullopt;
975 };
976 if (MRI.getType(Src).isVector()) {
977 auto *BV = getOpcodeDef<GBuildVector>(Src, MRI);
978 if (!BV)
979 return {};
980 SmallVector<APInt> Folded;
981 for (unsigned SrcIdx = 0; SrcIdx < BV->getNumSources(); ++SrcIdx) {
982 if (auto MaybeFold = tryFoldScalar(BV->getSourceReg(SrcIdx))) {
983 Folded.emplace_back(std::move(*MaybeFold));
984 continue;
985 }
986 return {};
987 }
988 return Folded;
989 }
990 if (auto MaybeCst = tryFoldScalar(Src))
991 return {std::move(*MaybeCst)};
992 return {};
993}
994
995std::optional<SmallVector<APInt>>
996llvm::ConstantFoldICmp(unsigned Pred, const Register Op1, const Register Op2,
997 unsigned DstScalarSizeInBits, unsigned ExtOp,
998 const MachineRegisterInfo &MRI) {
999 assert(ExtOp == TargetOpcode::G_SEXT || ExtOp == TargetOpcode::G_ZEXT ||
1000 ExtOp == TargetOpcode::G_ANYEXT);
1001
1002 const LLT Ty = MRI.getType(Op1);
1003
1004 auto GetICmpResultCst = [&](bool IsTrue) {
1005 if (IsTrue)
1006 return ExtOp == TargetOpcode::G_SEXT
1007 ? APInt::getAllOnes(DstScalarSizeInBits)
1008 : APInt::getOneBitSet(DstScalarSizeInBits, 0);
1009 return APInt::getZero(DstScalarSizeInBits);
1010 };
1011
1012 auto TryFoldScalar = [&](Register LHS, Register RHS) -> std::optional<APInt> {
1013 auto RHSCst = getIConstantVRegVal(RHS, MRI);
1014 if (!RHSCst)
1015 return std::nullopt;
1016 auto LHSCst = getIConstantVRegVal(LHS, MRI);
1017 if (!LHSCst)
1018 return std::nullopt;
1019
1020 switch (Pred) {
1022 return GetICmpResultCst(LHSCst->eq(*RHSCst));
1024 return GetICmpResultCst(LHSCst->ne(*RHSCst));
1026 return GetICmpResultCst(LHSCst->ugt(*RHSCst));
1028 return GetICmpResultCst(LHSCst->uge(*RHSCst));
1030 return GetICmpResultCst(LHSCst->ult(*RHSCst));
1032 return GetICmpResultCst(LHSCst->ule(*RHSCst));
1034 return GetICmpResultCst(LHSCst->sgt(*RHSCst));
1036 return GetICmpResultCst(LHSCst->sge(*RHSCst));
1038 return GetICmpResultCst(LHSCst->slt(*RHSCst));
1040 return GetICmpResultCst(LHSCst->sle(*RHSCst));
1041 default:
1042 return std::nullopt;
1043 }
1044 };
1045
1046 SmallVector<APInt> FoldedICmps;
1047
1048 if (Ty.isVector()) {
1049 // Try to constant fold each element.
1050 auto *BV1 = getOpcodeDef<GBuildVector>(Op1, MRI);
1051 auto *BV2 = getOpcodeDef<GBuildVector>(Op2, MRI);
1052 if (!BV1 || !BV2)
1053 return std::nullopt;
1054 assert(BV1->getNumSources() == BV2->getNumSources() && "Invalid vectors");
1055 for (unsigned I = 0; I < BV1->getNumSources(); ++I) {
1056 if (auto MaybeFold =
1057 TryFoldScalar(BV1->getSourceReg(I), BV2->getSourceReg(I))) {
1058 FoldedICmps.emplace_back(*MaybeFold);
1059 continue;
1060 }
1061 return std::nullopt;
1062 }
1063 return FoldedICmps;
1064 }
1065
1066 if (auto MaybeCst = TryFoldScalar(Op1, Op2)) {
1067 FoldedICmps.emplace_back(*MaybeCst);
1068 return FoldedICmps;
1069 }
1070
1071 return std::nullopt;
1072}
1073
1075 GISelValueTracking *VT, bool OrNegative) {
1076 std::optional<DefinitionAndSourceRegister> DefSrcReg =
1078 if (!DefSrcReg)
1079 return false;
1080
1081 const MachineInstr &MI = *DefSrcReg->MI;
1082 const LLT Ty = MRI.getType(Reg);
1083
1084 auto IsPow2 = [OrNegative](const APInt &V) {
1085 return V.isPowerOf2() || (OrNegative && V.isNegatedPowerOf2());
1086 };
1087
1088 switch (MI.getOpcode()) {
1089 case TargetOpcode::G_CONSTANT: {
1090 unsigned BitWidth = Ty.getScalarSizeInBits();
1091 const ConstantInt *CI = MI.getOperand(1).getCImm();
1092 return IsPow2(CI->getValue().zextOrTrunc(BitWidth));
1093 }
1094 case TargetOpcode::G_SHL: {
1095 // A left-shift of a constant one will have exactly one bit set because
1096 // shifting the bit off the end is undefined.
1097
1098 // TODO: Constant splat
1099 if (auto ConstLHS = getIConstantVRegVal(MI.getOperand(1).getReg(), MRI)) {
1100 if (*ConstLHS == 1)
1101 return true;
1102 }
1103
1104 break;
1105 }
1106 case TargetOpcode::G_LSHR: {
1107 if (auto ConstLHS = getIConstantVRegVal(MI.getOperand(1).getReg(), MRI)) {
1108 if (ConstLHS->isSignMask())
1109 return true;
1110 }
1111
1112 break;
1113 }
1114 case TargetOpcode::G_BUILD_VECTOR: {
1115 // TODO: Probably should have a recursion depth guard since you could have
1116 // bitcasted vector elements.
1117 for (const MachineOperand &MO : llvm::drop_begin(MI.operands()))
1118 if (!isKnownToBeAPowerOfTwo(MO.getReg(), MRI, VT, OrNegative))
1119 return false;
1120
1121 return true;
1122 }
1123 case TargetOpcode::G_BUILD_VECTOR_TRUNC: {
1124 // Only handle constants since we would need to know if number of leading
1125 // zeros is greater than the truncation amount.
1126 const unsigned BitWidth = Ty.getScalarSizeInBits();
1127 for (const MachineOperand &MO : llvm::drop_begin(MI.operands())) {
1128 auto Const = getIConstantVRegVal(MO.getReg(), MRI);
1129 if (!Const || !IsPow2(Const->zextOrTrunc(BitWidth)))
1130 return false;
1131 }
1132
1133 return true;
1134 }
1135 default:
1136 break;
1137 }
1138
1139 if (!VT)
1140 return false;
1141
1142 // More could be done here, though the above checks are enough
1143 // to handle some common cases.
1144
1145 // Fall back to computeKnownBits to catch other known cases.
1146 KnownBits Known = VT->getKnownBits(Reg);
1147 return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
1148}
1149
1153
1154LLT llvm::getLCMType(LLT OrigTy, LLT TargetTy) {
1155 if (OrigTy.getSizeInBits() == TargetTy.getSizeInBits())
1156 return OrigTy;
1157
1158 if (OrigTy.isVector() && TargetTy.isVector()) {
1159 LLT OrigElt = OrigTy.getElementType();
1160 LLT TargetElt = TargetTy.getElementType();
1161
1162 // TODO: The docstring for this function says the intention is to use this
1163 // function to build MERGE/UNMERGE instructions. It won't be the case that
1164 // we generate a MERGE/UNMERGE between fixed and scalable vector types. We
1165 // could implement getLCMType between the two in the future if there was a
1166 // need, but it is not worth it now as this function should not be used in
1167 // that way.
1168 assert(((OrigTy.isScalableVector() && !TargetTy.isFixedVector()) ||
1169 (OrigTy.isFixedVector() && !TargetTy.isScalableVector())) &&
1170 "getLCMType not implemented between fixed and scalable vectors.");
1171
1172 if (OrigElt.getSizeInBits() == TargetElt.getSizeInBits()) {
1173 int GCDMinElts = std::gcd(OrigTy.getElementCount().getKnownMinValue(),
1174 TargetTy.getElementCount().getKnownMinValue());
1175 // Prefer the original element type.
1177 TargetTy.getElementCount().getKnownMinValue());
1178 return LLT::vector(Mul.divideCoefficientBy(GCDMinElts),
1179 OrigTy.getElementType());
1180 }
1181 unsigned LCM = std::lcm(OrigTy.getSizeInBits().getKnownMinValue(),
1182 TargetTy.getSizeInBits().getKnownMinValue());
1183 return LLT::vector(
1184 ElementCount::get(LCM / OrigElt.getSizeInBits(), OrigTy.isScalable()),
1185 OrigElt);
1186 }
1187
1188 // One type is scalar, one type is vector
1189 if (OrigTy.isVector() || TargetTy.isVector()) {
1190 LLT VecTy = OrigTy.isVector() ? OrigTy : TargetTy;
1191 LLT ScalarTy = OrigTy.isVector() ? TargetTy : OrigTy;
1192 LLT EltTy = VecTy.getElementType();
1193 LLT OrigEltTy = OrigTy.isVector() ? OrigTy.getElementType() : OrigTy;
1194
1195 // Prefer scalar type from OrigTy.
1196 if (EltTy.getSizeInBits() == ScalarTy.getSizeInBits())
1197 return LLT::vector(VecTy.getElementCount(), OrigEltTy);
1198
1199 // Different size scalars. Create vector with the same total size.
1200 // LCM will take fixed/scalable from VecTy.
1201 unsigned LCM = std::lcm(EltTy.getSizeInBits().getFixedValue() *
1203 ScalarTy.getSizeInBits().getFixedValue());
1204 // Prefer type from OrigTy
1205 return LLT::vector(ElementCount::get(LCM / OrigEltTy.getSizeInBits(),
1206 VecTy.getElementCount().isScalable()),
1207 OrigEltTy);
1208 }
1209
1210 // At this point, both types are scalars of different size
1211 unsigned LCM = std::lcm(OrigTy.getSizeInBits().getFixedValue(),
1212 TargetTy.getSizeInBits().getFixedValue());
1213 // Preserve pointer types.
1214 if (LCM == OrigTy.getSizeInBits())
1215 return OrigTy;
1216 if (LCM == TargetTy.getSizeInBits())
1217 return TargetTy;
1218 return LLT::scalar(LCM);
1219}
1220
1221LLT llvm::getCoverTy(LLT OrigTy, LLT TargetTy) {
1222
1223 if ((OrigTy.isScalableVector() && TargetTy.isFixedVector()) ||
1224 (OrigTy.isFixedVector() && TargetTy.isScalableVector()))
1226 "getCoverTy not implemented between fixed and scalable vectors.");
1227
1228 if (!OrigTy.isVector() || !TargetTy.isVector() || OrigTy == TargetTy ||
1229 (OrigTy.getScalarSizeInBits() != TargetTy.getScalarSizeInBits()))
1230 return getLCMType(OrigTy, TargetTy);
1231
1232 unsigned OrigTyNumElts = OrigTy.getElementCount().getKnownMinValue();
1233 unsigned TargetTyNumElts = TargetTy.getElementCount().getKnownMinValue();
1234 if (OrigTyNumElts % TargetTyNumElts == 0)
1235 return OrigTy;
1236
1237 unsigned NumElts = alignTo(OrigTyNumElts, TargetTyNumElts);
1239 OrigTy.getElementType());
1240}
1241
1242LLT llvm::getGCDType(LLT OrigTy, LLT TargetTy) {
1243 if (OrigTy.getSizeInBits() == TargetTy.getSizeInBits())
1244 return OrigTy;
1245
1246 if (OrigTy.isVector() && TargetTy.isVector()) {
1247 LLT OrigElt = OrigTy.getElementType();
1248
1249 // TODO: The docstring for this function says the intention is to use this
1250 // function to build MERGE/UNMERGE instructions. It won't be the case that
1251 // we generate a MERGE/UNMERGE between fixed and scalable vector types. We
1252 // could implement getGCDType between the two in the future if there was a
1253 // need, but it is not worth it now as this function should not be used in
1254 // that way.
1255 assert(((OrigTy.isScalableVector() && !TargetTy.isFixedVector()) ||
1256 (OrigTy.isFixedVector() && !TargetTy.isScalableVector())) &&
1257 "getGCDType not implemented between fixed and scalable vectors.");
1258
1259 unsigned GCD = std::gcd(OrigTy.getSizeInBits().getKnownMinValue(),
1260 TargetTy.getSizeInBits().getKnownMinValue());
1261 if (GCD == OrigElt.getSizeInBits())
1263 OrigElt);
1264
1265 // Cannot produce original element type, but both have vscale in common.
1266 if (GCD < OrigElt.getSizeInBits())
1268 GCD);
1269
1270 return LLT::vector(
1272 OrigTy.isScalable()),
1273 OrigElt);
1274 }
1275
1276 // If one type is vector and the element size matches the scalar size, then
1277 // the gcd is the scalar type.
1278 if (OrigTy.isVector() &&
1279 OrigTy.getElementType().getSizeInBits() == TargetTy.getSizeInBits())
1280 return OrigTy.getElementType();
1281 if (TargetTy.isVector() &&
1282 TargetTy.getElementType().getSizeInBits() == OrigTy.getSizeInBits())
1283 return OrigTy;
1284
1285 // At this point, both types are either scalars of different type or one is a
1286 // vector and one is a scalar. If both types are scalars, the GCD type is the
1287 // GCD between the two scalar sizes. If one is vector and one is scalar, then
1288 // the GCD type is the GCD between the scalar and the vector element size.
1289 LLT OrigScalar = OrigTy.getScalarType();
1290 LLT TargetScalar = TargetTy.getScalarType();
1291 unsigned GCD = std::gcd(OrigScalar.getSizeInBits().getFixedValue(),
1292 TargetScalar.getSizeInBits().getFixedValue());
1293 return LLT::integer(GCD);
1294}
1295
1297 assert(MI.getOpcode() == TargetOpcode::G_SHUFFLE_VECTOR &&
1298 "Only G_SHUFFLE_VECTOR can have a splat index!");
1299 ArrayRef<int> Mask = MI.getOperand(3).getShuffleMask();
1300 auto FirstDefinedIdx = find_if(Mask, [](int Elt) { return Elt >= 0; });
1301
1302 // If all elements are undefined, this shuffle can be considered a splat.
1303 // Return 0 for better potential for callers to simplify.
1304 if (FirstDefinedIdx == Mask.end())
1305 return 0;
1306
1307 // Make sure all remaining elements are either undef or the same
1308 // as the first non-undef value.
1309 int SplatValue = *FirstDefinedIdx;
1310 if (any_of(make_range(std::next(FirstDefinedIdx), Mask.end()),
1311 [&SplatValue](int Elt) { return Elt >= 0 && Elt != SplatValue; }))
1312 return std::nullopt;
1313
1314 return SplatValue;
1315}
1316
1317static bool isBuildVectorOp(unsigned Opcode) {
1318 return Opcode == TargetOpcode::G_BUILD_VECTOR ||
1319 Opcode == TargetOpcode::G_BUILD_VECTOR_TRUNC;
1320}
1321
1322namespace {
1323
1324std::optional<ValueAndVReg> getAnyConstantSplat(Register VReg,
1325 const MachineRegisterInfo &MRI,
1326 bool AllowUndef) {
1327 MachineInstr *MI = getDefIgnoringCopies(VReg, MRI);
1328 if (!MI)
1329 return std::nullopt;
1330
1331 bool isConcatVectorsOp = MI->getOpcode() == TargetOpcode::G_CONCAT_VECTORS;
1332 if (!isBuildVectorOp(MI->getOpcode()) && !isConcatVectorsOp)
1333 return std::nullopt;
1334
1335 std::optional<ValueAndVReg> SplatValAndReg;
1336 for (MachineOperand &Op : MI->uses()) {
1337 Register Element = Op.getReg();
1338 // If we have a G_CONCAT_VECTOR, we recursively look into the
1339 // vectors that we're concatenating to see if they're splats.
1340 auto ElementValAndReg =
1341 isConcatVectorsOp
1342 ? getAnyConstantSplat(Element, MRI, AllowUndef)
1344
1345 // If AllowUndef, treat undef as value that will result in a constant splat.
1346 if (!ElementValAndReg) {
1347 if (AllowUndef && isa<GImplicitDef>(MRI.getVRegDef(Element)))
1348 continue;
1349 return std::nullopt;
1350 }
1351
1352 // Record splat value
1353 if (!SplatValAndReg)
1354 SplatValAndReg = ElementValAndReg;
1355
1356 // Different constant than the one already recorded, not a constant splat.
1357 if (SplatValAndReg->Value != ElementValAndReg->Value)
1358 return std::nullopt;
1359 }
1360
1361 return SplatValAndReg;
1362}
1363
1364} // end anonymous namespace
1365
1367 const MachineRegisterInfo &MRI,
1368 int64_t SplatValue, bool AllowUndef) {
1369 if (auto SplatValAndReg = getAnyConstantSplat(Reg, MRI, AllowUndef))
1370 return SplatValAndReg->Value.getSExtValue() == SplatValue;
1371
1372 return false;
1373}
1374
1376 const MachineRegisterInfo &MRI,
1377 const APInt &SplatValue,
1378 bool AllowUndef) {
1379 if (auto SplatValAndReg = getAnyConstantSplat(Reg, MRI, AllowUndef)) {
1380 if (SplatValAndReg->Value.getBitWidth() < SplatValue.getBitWidth())
1381 return APInt::isSameValue(
1382 SplatValAndReg->Value.sext(SplatValue.getBitWidth()), SplatValue);
1383 return APInt::isSameValue(
1384 SplatValAndReg->Value,
1385 SplatValue.sext(SplatValAndReg->Value.getBitWidth()));
1386 }
1387
1388 return false;
1389}
1390
1392 const MachineRegisterInfo &MRI,
1393 int64_t SplatValue, bool AllowUndef) {
1394 return isBuildVectorConstantSplat(MI.getOperand(0).getReg(), MRI, SplatValue,
1395 AllowUndef);
1396}
1397
1399 const MachineRegisterInfo &MRI,
1400 const APInt &SplatValue,
1401 bool AllowUndef) {
1402 return isBuildVectorConstantSplat(MI.getOperand(0).getReg(), MRI, SplatValue,
1403 AllowUndef);
1404}
1405
1406std::optional<APInt>
1408 if (auto SplatValAndReg =
1409 getAnyConstantSplat(Reg, MRI, /* AllowUndef */ false)) {
1410 if (std::optional<ValueAndVReg> ValAndVReg =
1411 getIConstantVRegValWithLookThrough(SplatValAndReg->VReg, MRI))
1412 return ValAndVReg->Value;
1413 }
1414
1415 return std::nullopt;
1416}
1417
1418std::optional<APInt>
1420 const MachineRegisterInfo &MRI) {
1421 return getIConstantSplatVal(MI.getOperand(0).getReg(), MRI);
1422}
1423
1424std::optional<int64_t>
1426 const MachineRegisterInfo &MRI) {
1427 if (auto SplatValAndReg =
1428 getAnyConstantSplat(Reg, MRI, /* AllowUndef */ false))
1429 return getIConstantVRegSExtVal(SplatValAndReg->VReg, MRI);
1430 return std::nullopt;
1431}
1432
1433std::optional<int64_t>
1435 const MachineRegisterInfo &MRI) {
1436 return getIConstantSplatSExtVal(MI.getOperand(0).getReg(), MRI);
1437}
1438
1439std::optional<FPValueAndVReg>
1441 bool AllowUndef) {
1442 if (auto SplatValAndReg = getAnyConstantSplat(VReg, MRI, AllowUndef))
1443 return getFConstantVRegValWithLookThrough(SplatValAndReg->VReg, MRI);
1444 return std::nullopt;
1445}
1446
1448 const MachineRegisterInfo &MRI,
1449 bool AllowUndef) {
1450 return isBuildVectorConstantSplat(MI, MRI, 0, AllowUndef);
1451}
1452
1454 const MachineRegisterInfo &MRI,
1455 bool AllowUndef) {
1456 return isBuildVectorConstantSplat(MI, MRI, -1, AllowUndef);
1457}
1458
1459std::optional<RegOrConstant>
1461 unsigned Opc = MI.getOpcode();
1462 if (!isBuildVectorOp(Opc))
1463 return std::nullopt;
1464 if (auto Splat = getIConstantSplatSExtVal(MI, MRI))
1465 return RegOrConstant(*Splat);
1466 auto Reg = MI.getOperand(1).getReg();
1467 if (any_of(drop_begin(MI.operands(), 2),
1468 [&Reg](const MachineOperand &Op) { return Op.getReg() != Reg; }))
1469 return std::nullopt;
1470 return RegOrConstant(Reg);
1471}
1472
1474 const MachineRegisterInfo &MRI,
1475 bool AllowFP = true,
1476 bool AllowOpaqueConstants = true) {
1477 switch (MI.getOpcode()) {
1478 case TargetOpcode::G_CONSTANT:
1479 case TargetOpcode::G_IMPLICIT_DEF:
1480 return true;
1481 case TargetOpcode::G_FCONSTANT:
1482 return AllowFP;
1483 case TargetOpcode::G_GLOBAL_VALUE:
1484 case TargetOpcode::G_FRAME_INDEX:
1485 case TargetOpcode::G_BLOCK_ADDR:
1486 case TargetOpcode::G_JUMP_TABLE:
1487 return AllowOpaqueConstants;
1488 default:
1489 return false;
1490 }
1491}
1492
1494 const MachineRegisterInfo &MRI) {
1495 Register Def = MI.getOperand(0).getReg();
1496 if (auto C = getIConstantVRegValWithLookThrough(Def, MRI))
1497 return true;
1499 if (!BV)
1500 return false;
1501 for (unsigned SrcIdx = 0; SrcIdx < BV->getNumSources(); ++SrcIdx) {
1502 if (getIConstantVRegValWithLookThrough(BV->getSourceReg(SrcIdx), MRI) ||
1503 getOpcodeDef<GImplicitDef>(BV->getSourceReg(SrcIdx), MRI))
1504 continue;
1505 return false;
1506 }
1507 return true;
1508}
1509
1511 const MachineRegisterInfo &MRI,
1512 bool AllowFP, bool AllowOpaqueConstants) {
1513 if (isConstantScalar(MI, MRI, AllowFP, AllowOpaqueConstants))
1514 return true;
1515
1516 if (!isBuildVectorOp(MI.getOpcode()))
1517 return false;
1518
1519 const unsigned NumOps = MI.getNumOperands();
1520 for (unsigned I = 1; I != NumOps; ++I) {
1521 const MachineInstr *ElementDef = MRI.getVRegDef(MI.getOperand(I).getReg());
1522 if (!isConstantScalar(*ElementDef, MRI, AllowFP, AllowOpaqueConstants))
1523 return false;
1524 }
1525
1526 return true;
1527}
1528
1529std::optional<APInt>
1531 const MachineRegisterInfo &MRI) {
1532 Register Def = MI.getOperand(0).getReg();
1533 if (auto C = getIConstantVRegValWithLookThrough(Def, MRI))
1534 return C->Value;
1535 auto MaybeCst = getIConstantSplatSExtVal(MI, MRI);
1536 if (!MaybeCst)
1537 return std::nullopt;
1538 const unsigned ScalarSize = MRI.getType(Def).getScalarSizeInBits();
1539 return APInt(ScalarSize, *MaybeCst, true);
1540}
1541
1542std::optional<APFloat>
1544 const MachineRegisterInfo &MRI) {
1545 Register Def = MI.getOperand(0).getReg();
1546 if (auto FpConst = getFConstantVRegValWithLookThrough(Def, MRI))
1547 return FpConst->Value;
1548 auto MaybeCstFP = getFConstantSplat(Def, MRI, /*allowUndef=*/false);
1549 if (!MaybeCstFP)
1550 return std::nullopt;
1551 return MaybeCstFP->Value;
1552}
1553
1555 const MachineRegisterInfo &MRI, bool AllowUndefs) {
1556 switch (MI.getOpcode()) {
1557 case TargetOpcode::G_IMPLICIT_DEF:
1558 return AllowUndefs;
1559 case TargetOpcode::G_CONSTANT:
1560 return MI.getOperand(1).getCImm()->isNullValue();
1561 case TargetOpcode::G_FCONSTANT: {
1562 const ConstantFP *FPImm = MI.getOperand(1).getFPImm();
1563 return FPImm->isZero() && !FPImm->isNegative();
1564 }
1565 default:
1566 if (!AllowUndefs) // TODO: isBuildVectorAllZeros assumes undef is OK already
1567 return false;
1568 return isBuildVectorAllZeros(MI, MRI);
1569 }
1570}
1571
1573 const MachineRegisterInfo &MRI,
1574 bool AllowUndefs) {
1575 switch (MI.getOpcode()) {
1576 case TargetOpcode::G_IMPLICIT_DEF:
1577 return AllowUndefs;
1578 case TargetOpcode::G_CONSTANT:
1579 return MI.getOperand(1).getCImm()->isAllOnesValue();
1580 default:
1581 if (!AllowUndefs) // TODO: isBuildVectorAllOnes assumes undef is OK already
1582 return false;
1583 return isBuildVectorAllOnes(MI, MRI);
1584 }
1585}
1586
1588 const MachineRegisterInfo &MRI, Register Reg,
1589 std::function<bool(const Constant *ConstVal)> Match, bool AllowUndefs) {
1590
1591 const MachineInstr *Def = getDefIgnoringCopies(Reg, MRI);
1592 if (AllowUndefs && Def->getOpcode() == TargetOpcode::G_IMPLICIT_DEF)
1593 return Match(nullptr);
1594
1595 // TODO: Also handle fconstant
1596 if (Def->getOpcode() == TargetOpcode::G_CONSTANT)
1597 return Match(Def->getOperand(1).getCImm());
1598
1599 if (Def->getOpcode() != TargetOpcode::G_BUILD_VECTOR)
1600 return false;
1601
1602 for (unsigned I = 1, E = Def->getNumOperands(); I != E; ++I) {
1603 Register SrcElt = Def->getOperand(I).getReg();
1604 const MachineInstr *SrcDef = getDefIgnoringCopies(SrcElt, MRI);
1605 if (AllowUndefs && SrcDef->getOpcode() == TargetOpcode::G_IMPLICIT_DEF) {
1606 if (!Match(nullptr))
1607 return false;
1608 continue;
1609 }
1610
1611 if (SrcDef->getOpcode() != TargetOpcode::G_CONSTANT ||
1612 !Match(SrcDef->getOperand(1).getCImm()))
1613 return false;
1614 }
1615
1616 return true;
1617}
1618
1619bool llvm::isConstTrueVal(const TargetLowering &TLI, int64_t Val, bool IsVector,
1620 bool IsFP) {
1621 switch (TLI.getBooleanContents(IsVector, IsFP)) {
1623 return Val & 0x1;
1625 return Val == 1;
1627 return Val == -1;
1628 }
1629 llvm_unreachable("Invalid boolean contents");
1630}
1631
1632bool llvm::isConstFalseVal(const TargetLowering &TLI, int64_t Val,
1633 bool IsVector, bool IsFP) {
1634 switch (TLI.getBooleanContents(IsVector, IsFP)) {
1636 return ~Val & 0x1;
1639 return Val == 0;
1640 }
1641 llvm_unreachable("Invalid boolean contents");
1642}
1643
1644int64_t llvm::getICmpTrueVal(const TargetLowering &TLI, bool IsVector,
1645 bool IsFP) {
1646 switch (TLI.getBooleanContents(IsVector, IsFP)) {
1649 return 1;
1651 return -1;
1652 }
1653 llvm_unreachable("Invalid boolean contents");
1654}
1655
1657 LostDebugLocObserver *LocObserver,
1658 SmallInstListTy &DeadInstChain) {
1659 for (MachineOperand &Op : MI.uses()) {
1660 if (Op.isReg() && Op.getReg().isVirtual())
1661 DeadInstChain.insert(MRI.getVRegDef(Op.getReg()));
1662 }
1663 LLVM_DEBUG(dbgs() << MI << "Is dead; erasing.\n");
1664 DeadInstChain.remove(&MI);
1665 MI.eraseFromParent();
1666 if (LocObserver)
1667 LocObserver->checkpoint(false);
1668}
1669
1672 LostDebugLocObserver *LocObserver) {
1673 SmallInstListTy DeadInstChain;
1674 for (MachineInstr *MI : DeadInstrs)
1675 saveUsesAndErase(*MI, MRI, LocObserver, DeadInstChain);
1676
1677 while (!DeadInstChain.empty()) {
1678 MachineInstr *Inst = DeadInstChain.pop_back_val();
1679 if (!isTriviallyDead(*Inst, MRI))
1680 continue;
1681 saveUsesAndErase(*Inst, MRI, LocObserver, DeadInstChain);
1682 }
1683}
1684
1686 LostDebugLocObserver *LocObserver) {
1687 return eraseInstrs({&MI}, MRI, LocObserver);
1688}
1689
1691 for (auto &Def : MI.defs()) {
1692 assert(Def.isReg() && "Must be a reg");
1693
1695 for (auto &MOUse : MRI.use_operands(Def.getReg())) {
1696 MachineInstr *DbgValue = MOUse.getParent();
1697 // Ignore partially formed DBG_VALUEs.
1698 if (DbgValue->isNonListDebugValue() && DbgValue->getNumOperands() == 4) {
1699 DbgUsers.push_back(&MOUse);
1700 }
1701 }
1702
1703 if (!DbgUsers.empty()) {
1704 salvageDebugInfoForDbgValue(MRI, MI, DbgUsers);
1705 }
1706 }
1707}
1708
1710 switch (Opc) {
1711 case TargetOpcode::G_FABS:
1712 case TargetOpcode::G_FADD:
1713 case TargetOpcode::G_FCANONICALIZE:
1714 case TargetOpcode::G_FCEIL:
1715 case TargetOpcode::G_FCONSTANT:
1716 case TargetOpcode::G_FCOPYSIGN:
1717 case TargetOpcode::G_FCOS:
1718 case TargetOpcode::G_FDIV:
1719 case TargetOpcode::G_FEXP2:
1720 case TargetOpcode::G_FEXP:
1721 case TargetOpcode::G_FFLOOR:
1722 case TargetOpcode::G_FLOG10:
1723 case TargetOpcode::G_FLOG2:
1724 case TargetOpcode::G_FLOG:
1725 case TargetOpcode::G_FMA:
1726 case TargetOpcode::G_FMAD:
1727 case TargetOpcode::G_FMAXIMUM:
1728 case TargetOpcode::G_FMAXIMUMNUM:
1729 case TargetOpcode::G_FMAXNUM:
1730 case TargetOpcode::G_FMAXNUM_IEEE:
1731 case TargetOpcode::G_FMINIMUM:
1732 case TargetOpcode::G_FMINIMUMNUM:
1733 case TargetOpcode::G_FMINNUM:
1734 case TargetOpcode::G_FMINNUM_IEEE:
1735 case TargetOpcode::G_FMUL:
1736 case TargetOpcode::G_FNEARBYINT:
1737 case TargetOpcode::G_FNEG:
1738 case TargetOpcode::G_FPEXT:
1739 case TargetOpcode::G_FPEXTLOAD:
1740 case TargetOpcode::G_FPOW:
1741 case TargetOpcode::G_FPTRUNC:
1742 case TargetOpcode::G_FPTRUNCSTORE:
1743 case TargetOpcode::G_FREM:
1744 case TargetOpcode::G_FRINT:
1745 case TargetOpcode::G_FSIN:
1746 case TargetOpcode::G_FTAN:
1747 case TargetOpcode::G_FACOS:
1748 case TargetOpcode::G_FASIN:
1749 case TargetOpcode::G_FATAN:
1750 case TargetOpcode::G_FATAN2:
1751 case TargetOpcode::G_FCOSH:
1752 case TargetOpcode::G_FSINH:
1753 case TargetOpcode::G_FTANH:
1754 case TargetOpcode::G_FSQRT:
1755 case TargetOpcode::G_FSUB:
1756 case TargetOpcode::G_INTRINSIC_ROUND:
1757 case TargetOpcode::G_INTRINSIC_ROUNDEVEN:
1758 case TargetOpcode::G_INTRINSIC_TRUNC:
1759 return true;
1760 default:
1761 return false;
1762 }
1763}
1764
1765/// Shifts return poison if shiftwidth is larger than the bitwidth.
1766static bool shiftAmountKnownInRange(Register ShiftAmount,
1767 const MachineRegisterInfo &MRI) {
1768 LLT Ty = MRI.getType(ShiftAmount);
1769
1770 if (Ty.isScalableVector())
1771 return false; // Can't tell, just return false to be safe
1772
1773 if (Ty.isScalar()) {
1774 std::optional<ValueAndVReg> Val =
1775 getIConstantVRegValWithLookThrough(ShiftAmount, MRI);
1776 if (!Val)
1777 return false;
1778 return Val->Value.ult(Ty.getScalarSizeInBits());
1779 }
1780
1781 GBuildVector *BV = getOpcodeDef<GBuildVector>(ShiftAmount, MRI);
1782 if (!BV)
1783 return false;
1784
1785 unsigned Sources = BV->getNumSources();
1786 for (unsigned I = 0; I < Sources; ++I) {
1787 std::optional<ValueAndVReg> Val =
1789 if (!Val)
1790 return false;
1791 if (!Val->Value.ult(Ty.getScalarSizeInBits()))
1792 return false;
1793 }
1794
1795 return true;
1796}
1797
1799 bool ConsiderFlagsAndMetadata,
1800 UndefPoisonKind Kind) {
1801 MachineInstr *RegDef = MRI.getVRegDef(Reg);
1802
1803 if (ConsiderFlagsAndMetadata && includesPoison(Kind))
1804 if (auto *GMI = dyn_cast<GenericMachineInstr>(RegDef))
1805 if (GMI->hasPoisonGeneratingFlags())
1806 return true;
1807
1808 // Check whether opcode is a poison/undef-generating operation.
1809 switch (RegDef->getOpcode()) {
1810 case TargetOpcode::G_BUILD_VECTOR:
1811 case TargetOpcode::G_CONSTANT_FOLD_BARRIER:
1812 return false;
1813 case TargetOpcode::G_SHL:
1814 case TargetOpcode::G_ASHR:
1815 case TargetOpcode::G_LSHR:
1816 return includesPoison(Kind) &&
1817 !shiftAmountKnownInRange(RegDef->getOperand(2).getReg(), MRI);
1818 case TargetOpcode::G_FPTOSI:
1819 case TargetOpcode::G_FPTOUI:
1820 // fptosi/ui yields poison if the resulting value does not fit in the
1821 // destination type.
1822 return true;
1823 case TargetOpcode::G_CTLZ:
1824 case TargetOpcode::G_CTTZ:
1825 case TargetOpcode::G_CTLS:
1826 case TargetOpcode::G_ABS:
1827 case TargetOpcode::G_CTPOP:
1828 case TargetOpcode::G_BSWAP:
1829 case TargetOpcode::G_BITREVERSE:
1830 case TargetOpcode::G_FSHL:
1831 case TargetOpcode::G_FSHR:
1832 case TargetOpcode::G_SMAX:
1833 case TargetOpcode::G_SMIN:
1834 case TargetOpcode::G_SCMP:
1835 case TargetOpcode::G_UMAX:
1836 case TargetOpcode::G_UMIN:
1837 case TargetOpcode::G_UCMP:
1838 case TargetOpcode::G_PTRMASK:
1839 case TargetOpcode::G_SADDO:
1840 case TargetOpcode::G_SSUBO:
1841 case TargetOpcode::G_UADDO:
1842 case TargetOpcode::G_USUBO:
1843 case TargetOpcode::G_SMULO:
1844 case TargetOpcode::G_UMULO:
1845 case TargetOpcode::G_SADDSAT:
1846 case TargetOpcode::G_UADDSAT:
1847 case TargetOpcode::G_SSUBSAT:
1848 case TargetOpcode::G_USUBSAT:
1849 case TargetOpcode::G_SBFX:
1850 case TargetOpcode::G_UBFX:
1851 return false;
1852 case TargetOpcode::G_SSHLSAT:
1853 case TargetOpcode::G_USHLSAT:
1854 return includesPoison(Kind) &&
1855 !shiftAmountKnownInRange(RegDef->getOperand(2).getReg(), MRI);
1856 case TargetOpcode::G_INSERT_VECTOR_ELT: {
1858 if (includesPoison(Kind)) {
1859 std::optional<ValueAndVReg> Index =
1860 getIConstantVRegValWithLookThrough(Insert->getIndexReg(), MRI);
1861 if (!Index)
1862 return true;
1863 LLT VecTy = MRI.getType(Insert->getVectorReg());
1864 return Index->Value.uge(VecTy.getElementCount().getKnownMinValue());
1865 }
1866 return false;
1867 }
1868 case TargetOpcode::G_EXTRACT_VECTOR_ELT: {
1870 if (includesPoison(Kind)) {
1871 std::optional<ValueAndVReg> Index =
1873 if (!Index)
1874 return true;
1875 LLT VecTy = MRI.getType(Extract->getVectorReg());
1876 return Index->Value.uge(VecTy.getElementCount().getKnownMinValue());
1877 }
1878 return false;
1879 }
1880 case TargetOpcode::G_SHUFFLE_VECTOR: {
1881 GShuffleVector *Shuffle = cast<GShuffleVector>(RegDef);
1882 ArrayRef<int> Mask = Shuffle->getMask();
1883 return includesPoison(Kind) && is_contained(Mask, -1);
1884 }
1885 case TargetOpcode::G_FNEG:
1886 case TargetOpcode::G_PHI:
1887 case TargetOpcode::G_SELECT:
1888 case TargetOpcode::G_UREM:
1889 case TargetOpcode::G_SREM:
1890 case TargetOpcode::G_FREEZE:
1891 case TargetOpcode::G_ICMP:
1892 case TargetOpcode::G_FCMP:
1893 case TargetOpcode::G_FADD:
1894 case TargetOpcode::G_FSUB:
1895 case TargetOpcode::G_FMUL:
1896 case TargetOpcode::G_FDIV:
1897 case TargetOpcode::G_FREM:
1898 case TargetOpcode::G_PTR_ADD:
1899 return false;
1900 default:
1901 return !isa<GCastOp>(RegDef) && !isa<GBinOp>(RegDef);
1902 }
1903}
1904
1906 const MachineRegisterInfo &MRI,
1907 unsigned Depth,
1908 UndefPoisonKind Kind) {
1910 return false;
1911
1912 MachineInstr *RegDef = MRI.getVRegDef(Reg);
1913
1914 switch (RegDef->getOpcode()) {
1915 case TargetOpcode::G_FREEZE:
1916 return true;
1917 case TargetOpcode::G_IMPLICIT_DEF:
1918 return !includesUndef(Kind);
1919 case TargetOpcode::G_CONSTANT:
1920 case TargetOpcode::G_FCONSTANT:
1921 return true;
1922 case TargetOpcode::G_BUILD_VECTOR: {
1923 GBuildVector *BV = cast<GBuildVector>(RegDef);
1924 unsigned NumSources = BV->getNumSources();
1925 for (unsigned I = 0; I < NumSources; ++I)
1927 Depth + 1, Kind))
1928 return false;
1929 return true;
1930 }
1931 case TargetOpcode::G_PHI: {
1932 GPhi *Phi = cast<GPhi>(RegDef);
1933 unsigned NumIncoming = Phi->getNumIncomingValues();
1934 for (unsigned I = 0; I < NumIncoming; ++I)
1935 if (!::isGuaranteedNotToBeUndefOrPoison(Phi->getIncomingValue(I), MRI,
1936 Depth + 1, Kind))
1937 return false;
1938 return true;
1939 }
1940 default: {
1941 auto MOCheck = [&](const MachineOperand &MO) {
1942 if (!MO.isReg())
1943 return true;
1944 return ::isGuaranteedNotToBeUndefOrPoison(MO.getReg(), MRI, Depth + 1,
1945 Kind);
1946 };
1947 return !::canCreateUndefOrPoison(Reg, MRI,
1948 /*ConsiderFlagsAndMetadata=*/true, Kind) &&
1949 all_of(RegDef->uses(), MOCheck);
1950 }
1951 }
1952}
1953
1955 bool ConsiderFlagsAndMetadata) {
1956 return ::canCreateUndefOrPoison(Reg, MRI, ConsiderFlagsAndMetadata,
1958}
1959
1961 bool ConsiderFlagsAndMetadata = true) {
1962 return ::canCreateUndefOrPoison(Reg, MRI, ConsiderFlagsAndMetadata,
1964}
1965
1967 const MachineRegisterInfo &MRI,
1968 unsigned Depth) {
1969 return ::isGuaranteedNotToBeUndefOrPoison(Reg, MRI, Depth,
1971}
1972
1974 const MachineRegisterInfo &MRI,
1975 unsigned Depth) {
1976 return ::isGuaranteedNotToBeUndefOrPoison(Reg, MRI, Depth,
1978}
1979
1981 const MachineRegisterInfo &MRI,
1982 unsigned Depth) {
1983 return ::isGuaranteedNotToBeUndefOrPoison(Reg, MRI, Depth,
1985}
1986
1988 if (Ty.isVector())
1989 return VectorType::get(IntegerType::get(C, Ty.getScalarSizeInBits()),
1990 Ty.getElementCount());
1991 return IntegerType::get(C, Ty.getSizeInBits());
1992}
1993
1995 switch (MI.getOpcode()) {
1996 default:
1997 return false;
1998 case TargetOpcode::G_ASSERT_ALIGN:
1999 case TargetOpcode::G_ASSERT_SEXT:
2000 case TargetOpcode::G_ASSERT_ZEXT:
2001 return true;
2002 }
2003}
2004
2006 assert(Kind == GIConstantKind::Scalar && "Expected scalar constant");
2007
2008 return Value;
2009}
2010
2011std::optional<GIConstant>
2014
2016 std::optional<ValueAndVReg> MayBeConstant =
2017 getIConstantVRegValWithLookThrough(Splat->getScalarReg(), MRI);
2018 if (!MayBeConstant)
2019 return std::nullopt;
2020 return GIConstant(MayBeConstant->Value, GIConstantKind::ScalableVector);
2021 }
2022
2024 SmallVector<APInt> Values;
2025 unsigned NumSources = Build->getNumSources();
2026 for (unsigned I = 0; I < NumSources; ++I) {
2027 Register SrcReg = Build->getSourceReg(I);
2028 std::optional<ValueAndVReg> MayBeConstant =
2030 if (!MayBeConstant)
2031 return std::nullopt;
2032 Values.push_back(MayBeConstant->Value);
2033 }
2034 return GIConstant(Values);
2035 }
2036
2037 std::optional<ValueAndVReg> MayBeConstant =
2039 if (!MayBeConstant)
2040 return std::nullopt;
2041
2042 return GIConstant(MayBeConstant->Value, GIConstantKind::Scalar);
2043}
2044
2046 assert(Kind == GFConstantKind::Scalar && "Expected scalar constant");
2047
2048 return Values[0];
2049}
2050
2051std::optional<GFConstant>
2054
2056 std::optional<FPValueAndVReg> MayBeConstant =
2057 getFConstantVRegValWithLookThrough(Splat->getScalarReg(), MRI);
2058 if (!MayBeConstant)
2059 return std::nullopt;
2060 return GFConstant(MayBeConstant->Value, GFConstantKind::ScalableVector);
2061 }
2062
2064 SmallVector<APFloat> Values;
2065 unsigned NumSources = Build->getNumSources();
2066 for (unsigned I = 0; I < NumSources; ++I) {
2067 Register SrcReg = Build->getSourceReg(I);
2068 std::optional<FPValueAndVReg> MayBeConstant =
2070 if (!MayBeConstant)
2071 return std::nullopt;
2072 Values.push_back(MayBeConstant->Value);
2073 }
2074 return GFConstant(Values);
2075 }
2076
2077 std::optional<FPValueAndVReg> MayBeConstant =
2079 if (!MayBeConstant)
2080 return std::nullopt;
2081
2082 return GFConstant(MayBeConstant->Value, GFConstantKind::Scalar);
2083}
2084
2085// Returns a list of types to use for memory op lowering in MemOps. A partial
2086// port of findOptimalMemOpLowering in TargetLowering.
2087static bool findGISelOptimalMemOpLowering(std::vector<LLT> &MemOps,
2088 unsigned Limit, const MemOp &Op,
2089 unsigned DstAS, unsigned SrcAS,
2090 const AttributeList &FuncAttributes,
2091 const TargetLowering &TLI) {
2092 if (Op.isMemcpyWithFixedDstAlign() && Op.getSrcAlign() < Op.getDstAlign())
2093 return false;
2094
2095 LLT Ty = TLI.getOptimalMemOpLLT(Op, FuncAttributes);
2096
2097 if (Ty == LLT()) {
2098 // Use the largest scalar type whose alignment constraints are satisfied.
2099 // We only need to check DstAlign here as SrcAlign is always greater or
2100 // equal to DstAlign (or zero).
2101 Ty = LLT::integer(64);
2102 if (Op.isFixedDstAlign())
2103 while (Op.getDstAlign() < Ty.getSizeInBytes() &&
2104 !TLI.allowsMisalignedMemoryAccesses(Ty, DstAS, Op.getDstAlign()))
2105 Ty = LLT::integer(Ty.getSizeInBytes());
2106 assert(Ty.getSizeInBits() > 0 && "Could not find valid type");
2107 // FIXME: check for the largest legal type we can load/store to.
2108 }
2109
2110 unsigned NumMemOps = 0;
2111 uint64_t Size = Op.size();
2112 while (Size) {
2113 unsigned TySize = Ty.getSizeInBytes();
2114 while (TySize > Size) {
2115 // For now, only use non-vector load / store's for the left-over pieces.
2116 LLT NewTy = Ty;
2117 // FIXME: check for mem op safety and legality of the types. Not all of
2118 // SDAGisms map cleanly to GISel concepts.
2119 if (NewTy.isVector())
2120 NewTy =
2121 NewTy.getSizeInBits() > 64 ? LLT::integer(64) : LLT::integer(32);
2122 NewTy = LLT::integer(llvm::bit_floor(NewTy.getSizeInBits() - 1));
2123 unsigned NewTySize = NewTy.getSizeInBytes();
2124 assert(NewTySize > 0 && "Could not find appropriate type");
2125
2126 // If the new LLT cannot cover all of the remaining bits, then consider
2127 // issuing a (or a pair of) unaligned and overlapping load / store.
2128 unsigned Fast;
2129 // Need to get a VT equivalent for allowMisalignedMemoryAccesses().
2130 MVT VT = getMVTForLLT(Ty);
2131 if (NumMemOps && Op.allowOverlap() && NewTySize < Size &&
2133 VT, DstAS, Op.isFixedDstAlign() ? Op.getDstAlign() : Align(1),
2135 Fast)
2136 TySize = Size;
2137 else {
2138 Ty = NewTy;
2139 TySize = NewTySize;
2140 }
2141 }
2142
2143 if (++NumMemOps > Limit)
2144 return false;
2145
2146 MemOps.push_back(Ty);
2147 Size -= TySize;
2148 }
2149
2150 return true;
2151}
2152
2154 const MachineRegisterInfo &MRI, unsigned MaxLen,
2155 Register &Dst, Register &Src,
2156 uint64_t &KnownLen, Align &Alignment,
2157 bool &DstAlignCanChange,
2158 std::vector<LLT> &MemOps) {
2159 const unsigned Opc = MI.getOpcode();
2160 assert((Opc == TargetOpcode::G_MEMCPY ||
2161 Opc == TargetOpcode::G_MEMCPY_INLINE ||
2162 Opc == TargetOpcode::G_MEMMOVE || Opc == TargetOpcode::G_MEMSET) &&
2163 "Expected memcpy like instruction");
2164
2165 auto MMOIt = MI.memoperands_begin();
2166 const MachineMemOperand *MemOp = *MMOIt;
2167
2168 Align DstAlign = MemOp->getBaseAlign();
2169 Align SrcAlign;
2170 Alignment = DstAlign;
2171 Register Len;
2172 std::tie(Dst, Src, Len) = MI.getFirst3Regs();
2173
2174 if (Opc != TargetOpcode::G_MEMSET) {
2175 assert(MMOIt != MI.memoperands_end() && "Expected a second MMO on MI");
2176 MemOp = *(++MMOIt);
2177 SrcAlign = MemOp->getBaseAlign();
2178 Alignment = std::min(DstAlign, SrcAlign);
2179 }
2180
2181 // See if this is a constant length copy.
2182 auto LenVRegAndVal = getIConstantVRegValWithLookThrough(Len, MRI);
2183 if (!LenVRegAndVal) {
2184 // FIXME: support dynamically sized G_MEMCPY_INLINE
2185 assert(Opc != TargetOpcode::G_MEMCPY_INLINE &&
2186 "inline memcpy with dynamic size is not yet supported");
2187 return false;
2188 }
2189
2190 KnownLen = LenVRegAndVal->Value.getZExtValue();
2191 DstAlignCanChange = false;
2192
2193 if (KnownLen == 0)
2194 return true;
2195
2196 if (Opc != TargetOpcode::G_MEMCPY_INLINE && MaxLen && KnownLen > MaxLen)
2197 return false;
2198
2199 bool IsVolatile = MemOp->isVolatile();
2200 const MachineFunction &MF = *MI.getParent()->getParent();
2201 const auto &TLI = *MF.getSubtarget().getTargetLowering();
2202 // On Darwin, -Os means optimize for size without hurting performance, so
2203 // only really optimize for size when -Oz (MinSize) is used.
2204 bool OptSize = MF.getTarget().getTargetTriple().isOSDarwin()
2205 ? MF.getFunction().hasMinSize()
2206 : MF.getFunction().hasOptSize();
2207
2208 const MachineFrameInfo &MFI = MF.getFrameInfo();
2209 MachineInstr *FIDef = getOpcodeDef(TargetOpcode::G_FRAME_INDEX, Dst, MRI);
2210 if (FIDef && !MFI.isFixedObjectIndex(FIDef->getOperand(1).getIndex()))
2211 DstAlignCanChange = true;
2212
2213 const auto &DstMMO = **MI.memoperands_begin();
2214 MachinePointerInfo DstPtrInfo = DstMMO.getPointerInfo();
2215
2216 switch (Opc) {
2217 case TargetOpcode::G_MEMCPY_INLINE:
2218 case TargetOpcode::G_MEMCPY: {
2219 const auto &SrcMMO = **std::next(MI.memoperands_begin());
2220 MachinePointerInfo SrcPtrInfo = SrcMMO.getPointerInfo();
2221 uint64_t Limit = Opc == TargetOpcode::G_MEMCPY_INLINE
2222 ? std::numeric_limits<uint64_t>::max()
2223 : TLI.getMaxStoresPerMemcpy(OptSize);
2225 MemOps, Limit,
2226 MemOp::Copy(KnownLen, DstAlignCanChange, std::min(DstAlign, SrcAlign),
2227 SrcAlign, IsVolatile),
2228 DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
2229 MF.getFunction().getAttributes(), TLI);
2230 }
2231 case TargetOpcode::G_MEMMOVE: {
2232 const auto &SrcMMO = **std::next(MI.memoperands_begin());
2233 MachinePointerInfo SrcPtrInfo = SrcMMO.getPointerInfo();
2234 unsigned Limit = TLI.getMaxStoresPerMemmove(OptSize);
2235 // FIXME: SelectionDAG always passes false for 'AllowOverlap', apparently
2236 // due to a bug in it's findOptimalMemOpLowering implementation. For now do
2237 // the same thing here.
2239 MemOps, Limit,
2240 MemOp::Copy(KnownLen, DstAlignCanChange, std::min(DstAlign, SrcAlign),
2241 SrcAlign, /*IsVolatile=*/true),
2242 DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
2243 MF.getFunction().getAttributes(), TLI);
2244 }
2245 case TargetOpcode::G_MEMSET: {
2246 unsigned Limit = TLI.getMaxStoresPerMemset(OptSize);
2247 auto ValVRegAndVal = getIConstantVRegValWithLookThrough(Src, MRI);
2248 bool IsZeroVal = ValVRegAndVal && ValVRegAndVal->Value == 0;
2250 MemOps, Limit,
2251 MemOp::Set(KnownLen, DstAlignCanChange, DstAlign,
2252 /*IsZeroMemset=*/IsZeroVal,
2253 /*IsVolatile=*/IsVolatile),
2254 DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes(), TLI);
2255 }
2256 default:
2257 llvm_unreachable("Unexpected memcpy-family opcode");
2258 }
2259}
MachineInstrBuilder MachineInstrBuilder & DefMI
unsigned RegSize
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
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 bool findGISelOptimalMemOpLowering(std::vector< LLT > &MemOps, unsigned Limit, const MemOp &Op, unsigned DstAS, unsigned SrcAS, const AttributeList &FuncAttributes, const TargetLowering &TLI)
Definition Utils.cpp:2087
static void reportGISelDiagnostic(DiagnosticSeverity Severity, MachineFunction &MF, MachineOptimizationRemarkEmitter &MORE, MachineOptimizationRemarkMissed &R)
Definition Utils.cpp:237
static bool shiftAmountKnownInRange(Register ShiftAmount, const MachineRegisterInfo &MRI)
Shifts return poison if shiftwidth is larger than the bitwidth.
Definition Utils.cpp:1766
static bool isBuildVectorOp(unsigned Opcode)
Definition Utils.cpp:1317
static bool isConstantScalar(const MachineInstr &MI, const MachineRegisterInfo &MRI, bool AllowFP=true, bool AllowOpaqueConstants=true)
Definition Utils.cpp:1473
static GBuildVector * getBuildVectorLikeDef(Register Reg, const MachineRegisterInfo &MRI)
Definition Utils.cpp:801
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
MachineInstr unsigned OpIdx
uint64_t IntrinsicInst * II
#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 rmNearestTiesToEven
Definition APFloat.h:344
static const fltSemantics & IEEEhalf()
Definition APFloat.h:294
opStatus divide(const APFloat &RHS, roundingMode RM)
Definition APFloat.h:1267
void copySign(const APFloat &RHS)
Definition APFloat.h:1361
LLVM_ABI opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition APFloat.cpp:5912
opStatus subtract(const APFloat &RHS, roundingMode RM)
Definition APFloat.h:1249
opStatus add(const APFloat &RHS, roundingMode RM)
Definition APFloat.h:1240
opStatus convertFromAPInt(const APInt &Input, bool IsSigned, roundingMode RM)
Definition APFloat.h:1406
opStatus multiply(const APFloat &RHS, roundingMode RM)
Definition APFloat.h:1258
APInt bitcastToAPInt() const
Definition APFloat.h:1430
opStatus mod(const APFloat &RHS)
Definition APFloat.h:1285
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition APInt.cpp:1599
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:235
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1055
LLVM_ABI APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
Definition APInt.cpp:1076
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
Definition APInt.cpp:968
LLVM_ABI APInt urem(const APInt &RHS) const
Unsigned remainder operation.
Definition APInt.cpp:1692
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1511
LLVM_ABI APInt sdiv(const APInt &RHS) const
Signed division function for APInt.
Definition APInt.cpp:1670
LLVM_ABI APInt sextOrTrunc(unsigned width) const
Sign extend or truncate to width.
Definition APInt.cpp:1084
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:555
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition APInt.h:834
LLVM_ABI APInt srem(const APInt &RHS) const
Function for signed remainder operation.
Definition APInt.cpp:1771
LLVM_ABI APInt sext(unsigned width) const
Sign extend to a new width.
Definition APInt.cpp:1028
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:201
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:240
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition APInt.h:858
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:43
A debug info location.
Definition DebugLoc.h:124
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:309
static constexpr ElementCount get(ScalarTy MinVal, bool Scalable)
Definition TypeSize.h:315
bool hasOptSize() const
Optimize this function for size (-Os) or minimum size (-Oz).
Definition Function.h:714
bool hasMinSize() const
Optimize this function for minimum size (-Oz).
Definition Function.h:711
AttributeList getAttributes() const
Return the attribute list for this Function.
Definition Function.h:354
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:2052
GFConstant(ArrayRef< APFloat > Values)
Definition Utils.h:704
LLVM_ABI APFloat getScalarValue() const
Returns the value, if this constant is a scalar.
Definition Utils.cpp:2045
LLVM_ABI APInt getScalarValue() const
Returns the value, if this constant is a scalar.
Definition Utils.cpp:2005
static LLVM_ABI std::optional< GIConstant > getConstant(Register Const, const MachineRegisterInfo &MRI)
Definition Utils.cpp:2012
GIConstant(ArrayRef< APInt > Values)
Definition Utils.h:663
Abstract class that contains various methods for clients to notify about changes.
KnownBits getKnownBits(Register R)
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:350
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:68
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,...
LLVM_ABI MachineInstr * getVRegDef(Register Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
bool use_nodbg_empty(Register RegNo) const
use_nodbg_empty - Return true if there are no non-Debug instructions using the specified register.
const RegClassOrRegBank & getRegClassOrRegBank(Register Reg) const
Return the register bank or register class of Reg.
def_iterator def_begin(Register RegNo) const
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
LLT getType(Register Reg) const
Get the low-level type of Reg or LLT{} if Reg is not a generic (target independent) virtual register.
LLVM_ABI void setType(Register VReg, LLT Ty)
Set the low-level type of VReg to Ty.
LLVM_ABI Register createGenericVirtualRegister(LLT Ty, StringRef Name="")
Create and return a new generic virtual register with low-level type Ty.
LLVM_ABI Register getLiveInVirtReg(MCRegister PReg) const
getLiveInVirtReg - If PReg is a live-in physical register, return the corresponding live-in virtual r...
const TargetRegisterClass * getRegClassOrNull(Register Reg) const
Return the register class of Reg, or null if Reg has not been assigned a register class yet.
static def_iterator def_end()
iterator_range< use_iterator > use_operands(Register Reg) const
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
Represents a value which can be a Register or a constant.
Definition Utils.h:408
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.
virtual bool allowsMisalignedMemoryAccesses(EVT, unsigned AddrSpace=0, Align Alignment=Align(1), MachineMemOperand::Flags Flags=MachineMemOperand::MONone, unsigned *=nullptr) const
Determine if the target supports unaligned memory accesses.
virtual LLT getOptimalMemOpLLT(const MemOp &Op, const AttributeList &) const
LLT returning variant.
BooleanContent getBooleanContents(bool isVec, bool isFloat) const
For targets without i1 registers, this gives the nature of the high-bits of boolean values held in ty...
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:645
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
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:200
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
constexpr LeafTy multiplyCoefficientBy(ScalarTy RHS) const
Definition TypeSize.h:256
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:165
#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:2277
const APInt & smax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be signed.
Definition APInt.h:2282
const APInt & umin(const APInt &A, const APInt &B)
Determine the smaller of two APInts considered to be unsigned.
Definition APInt.h:2287
const APInt & umax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be unsigned.
Definition APInt.h:2292
@ Fast
Attempts to make calls as fast as possible (e.g.
Definition CallingConv.h:41
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
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:861
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:315
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:996
@ Offset
Definition DWP.cpp:558
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:1447
LLVM_ABI Type * getTypeForLLT(LLT Ty, LLVMContext &C)
Get the type back from LLT.
Definition Utils.cpp:1987
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:1738
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:60
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:656
LLVM_ABI const ConstantFP * getConstantFPVRegVal(Register VReg, const MachineRegisterInfo &MRI)
Definition Utils.cpp:464
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:297
LLVM_ABI std::optional< APFloat > ConstantFoldIntToFloat(unsigned Opcode, LLT DstTy, Register Src, const MachineRegisterInfo &MRI)
Definition Utils.cpp:935
LLVM_ABI std::optional< APInt > getIConstantSplatVal(const Register Reg, const MachineRegisterInfo &MRI)
Definition Utils.cpp:1407
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:1572
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:744
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:1690
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:159
bool isPreISelGenericOpcode(unsigned Opcode)
Check whether the given Opcode is a generic opcode that is not supposed to appear after ISel.
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:894
LLVM_ABI std::optional< RegOrConstant > getVectorSplat(const MachineInstr &MI, const MachineRegisterInfo &MRI)
Definition Utils.cpp:1460
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:1740
GISelWorkList< 4 > SmallInstListTy
Definition Utils.h:583
LLVM_ABI std::optional< APInt > isConstantOrConstantSplatVector(MachineInstr &MI, const MachineRegisterInfo &MRI)
Determines if MI defines a constant integer or a splat vector of constant integers.
Definition Utils.cpp:1530
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:1554
LLVM_ABI MachineInstr * getDefIgnoringCopies(Register Reg, const MachineRegisterInfo &MRI)
Find the def instruction for Reg, folding away any trivial copies.
Definition Utils.cpp:497
LLVM_ABI bool matchUnaryPredicate(const MachineRegisterInfo &MRI, Register Reg, std::function< 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:1587
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:255
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:1619
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:1154
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:317
LLVM_ABI std::optional< APInt > ConstantFoldBinOp(unsigned Opcode, const Register Op1, const Register Op2, const MachineRegisterInfo &MRI)
Definition Utils.cpp:675
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:1745
LLVM_ABI const APInt & getIConstantFromReg(Register VReg, const MachineRegisterInfo &MRI)
VReg is defined by a G_CONSTANT, return the corresponding value.
Definition Utils.cpp:308
LLVM_READONLY APFloat maxnum(const APFloat &A, const APFloat &B)
Implements IEEE-754 2008 maxNum semantics.
Definition APFloat.h:1695
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:1510
constexpr unsigned MaxAnalysisRecursionDepth
auto reverse(ContainerTy &&C)
Definition STLExtras.h:407
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:203
LLVM_READONLY APFloat minimumnum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2019 minimumNumber semantics.
Definition APFloat.h:1726
LLVM_ABI void saveUsesAndErase(MachineInstr &MI, MachineRegisterInfo &MRI, LostDebugLocObserver *LocObserver, SmallInstListTy &DeadInstChain)
Definition Utils.cpp:1656
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:261
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:144
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:442
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:1453
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:822
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:1440
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:911
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:511
LLVM_ABI void getSelectionDAGFallbackAnalysisUsage(AnalysisUsage &AU)
Modify analysis usage so it preserves passes required for the SelectionDAG fallback.
Definition Utils.cpp:1150
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:2153
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:1221
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:1676
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:282
@ Mul
Product of integers.
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:450
LLVM_ABI bool isConstFalseVal(const TargetLowering &TLI, int64_t Val, bool IsVector, bool IsFP)
Definition Utils.cpp:1632
LLVM_ABI std::optional< APFloat > isConstantOrConstantSplatVectorFP(MachineInstr &MI, const MachineRegisterInfo &MRI)
Determines if MI defines a float constant integer or a splat vector of float constant integers.
Definition Utils.cpp:1543
constexpr unsigned BitWidth
LLVM_ABI APFloat getAPFloatFromSize(double Val, unsigned Size)
Returns an APFloat from Val converted to the appropriate size.
Definition Utils.cpp:662
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:1366
LLVM_ABI void eraseInstr(MachineInstr &MI, MachineRegisterInfo &MRI, LostDebugLocObserver *LocObserver=nullptr)
Definition Utils.cpp:1685
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:50
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:1644
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:436
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:1771
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:1709
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:472
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1946
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition Alignment.h:201
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:948
LLVM_ABI void eraseInstrs(ArrayRef< MachineInstr * > DeadInstrs, MachineRegisterInfo &MRI, LostDebugLocObserver *LocObserver=nullptr)
Definition Utils.cpp:1670
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 bool isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL, bool OrZero=false, AssumptionCache *AC=nullptr, const Instruction *CxtI=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 Register getSrcRegIgnoringCopies(Register Reg, const MachineRegisterInfo &MRI)
Find the source register for Reg, folding away any trivial copies.
Definition Utils.cpp:504
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:1242
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:1713
LLVM_READONLY APFloat maximumnum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2019 maximumNumber semantics.
Definition APFloat.h:1753
LLVM_ABI std::optional< int64_t > getIConstantSplatSExtVal(const Register Reg, const MachineRegisterInfo &MRI)
Definition Utils.cpp:1425
LLVM_ABI bool isAssertMI(const MachineInstr &MI)
Returns true if the instruction MI is one of the assert instructions.
Definition Utils.cpp:1994
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:614
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:224
LLVM_ABI Align inferAlignFromPtrInfo(MachineFunction &MF, const MachinePointerInfo &MPO)
Definition Utils.cpp:844
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:246
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:242
unsigned countMaxPopulation() const
Returns the maximum number of bits that could be one.
Definition KnownBits.h:303
unsigned countMinPopulation() const
Returns the number of bits known to be one.
Definition KnownBits.h:300
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)
Simple struct used to hold a constant integer value and a virtual register.
Definition Utils.h:189