LLVM 24.0.0git
Utils.cpp
Go to the documentation of this file.
1//===- llvm/CodeGen/GlobalISel/Utils.cpp -------------------------*- C++ -*-==//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8/// \file This file implements the utility functions used by the GlobalISel
9/// pipeline.
10//===----------------------------------------------------------------------===//
11
13#include "llvm/ADT/APFloat.h"
14#include "llvm/ADT/APInt.h"
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.getConstrainedRegClassForReg(Reg, 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
662std::optional<APInt> llvm::ConstantFoldBinOp(unsigned Opcode,
663 const Register Op1,
664 const Register Op2,
665 const MachineRegisterInfo &MRI) {
666 auto MaybeOp2Cst = getAnyConstantVRegValWithLookThrough(Op2, MRI, false);
667 if (!MaybeOp2Cst)
668 return std::nullopt;
669
670 auto MaybeOp1Cst = getAnyConstantVRegValWithLookThrough(Op1, MRI, false);
671 if (!MaybeOp1Cst)
672 return std::nullopt;
673
674 const APInt &C1 = MaybeOp1Cst->Value;
675 const APInt &C2 = MaybeOp2Cst->Value;
676 switch (Opcode) {
677 default:
678 break;
679 case TargetOpcode::G_ADD:
680 return C1 + C2;
681 case TargetOpcode::G_PTR_ADD:
682 // Types can be of different width here.
683 // Result needs to be the same width as C1, so trunc or sext C2.
684 return C1 + C2.sextOrTrunc(C1.getBitWidth());
685 case TargetOpcode::G_AND:
686 return C1 & C2;
687 case TargetOpcode::G_ASHR:
688 return C1.ashr(C2);
689 case TargetOpcode::G_LSHR:
690 return C1.lshr(C2);
691 case TargetOpcode::G_MUL:
692 return C1 * C2;
693 case TargetOpcode::G_OR:
694 return C1 | C2;
695 case TargetOpcode::G_SHL:
696 return C1 << C2;
697 case TargetOpcode::G_SUB:
698 return C1 - C2;
699 case TargetOpcode::G_XOR:
700 return C1 ^ C2;
701 case TargetOpcode::G_UDIV:
702 if (!C2.getBoolValue())
703 break;
704 return C1.udiv(C2);
705 case TargetOpcode::G_SDIV:
706 if (!C2.getBoolValue())
707 break;
708 return C1.sdiv(C2);
709 case TargetOpcode::G_UREM:
710 if (!C2.getBoolValue())
711 break;
712 return C1.urem(C2);
713 case TargetOpcode::G_SREM:
714 if (!C2.getBoolValue())
715 break;
716 return C1.srem(C2);
717 case TargetOpcode::G_SMIN:
718 return APIntOps::smin(C1, C2);
719 case TargetOpcode::G_SMAX:
720 return APIntOps::smax(C1, C2);
721 case TargetOpcode::G_UMIN:
722 return APIntOps::umin(C1, C2);
723 case TargetOpcode::G_UMAX:
724 return APIntOps::umax(C1, C2);
725 }
726
727 return std::nullopt;
728}
729
730std::optional<APFloat>
731llvm::ConstantFoldFPBinOp(unsigned Opcode, const Register Op1,
732 const Register Op2, const MachineRegisterInfo &MRI) {
733 const ConstantFP *Op2Cst = getConstantFPVRegVal(Op2, MRI);
734 if (!Op2Cst)
735 return std::nullopt;
736
737 const ConstantFP *Op1Cst = getConstantFPVRegVal(Op1, MRI);
738 if (!Op1Cst)
739 return std::nullopt;
740
741 APFloat C1 = Op1Cst->getValueAPF();
742 const APFloat &C2 = Op2Cst->getValueAPF();
743 switch (Opcode) {
744 case TargetOpcode::G_FADD:
746 return C1;
747 case TargetOpcode::G_FSUB:
749 return C1;
750 case TargetOpcode::G_FMUL:
752 return C1;
753 case TargetOpcode::G_FDIV:
755 return C1;
756 case TargetOpcode::G_FREM:
757 C1.mod(C2);
758 return C1;
759 case TargetOpcode::G_FCOPYSIGN:
760 C1.copySign(C2);
761 return C1;
762 case TargetOpcode::G_FMINNUM:
763 return minnum(C1, C2);
764 case TargetOpcode::G_FMAXNUM:
765 return maxnum(C1, C2);
766 case TargetOpcode::G_FMINIMUM:
767 return minimum(C1, C2);
768 case TargetOpcode::G_FMAXIMUM:
769 return maximum(C1, C2);
770 case TargetOpcode::G_FMINIMUMNUM:
771 return minimumnum(C1, C2);
772 case TargetOpcode::G_FMAXIMUMNUM:
773 return maximumnum(C1, C2);
774 case TargetOpcode::G_FMINNUM_IEEE:
775 case TargetOpcode::G_FMAXNUM_IEEE:
776 // FIXME: These operations were unfortunately named. fminnum/fmaxnum do not
777 // follow the IEEE behavior for signaling nans and follow libm's fmin/fmax,
778 // and currently there isn't a nice wrapper in APFloat for the version with
779 // correct snan handling.
780 break;
781 default:
782 break;
783 }
784
785 return std::nullopt;
786}
787
789 const MachineRegisterInfo &MRI) {
790 if (auto *BV = getOpcodeDef<GBuildVector>(Reg, MRI))
791 return BV;
792
793 auto *Bitcast = getOpcodeDef(TargetOpcode::G_BITCAST, Reg, MRI);
794 if (!Bitcast)
795 return nullptr;
796
797 auto [Dst, DstTy, Src, SrcTy] = Bitcast->getFirst2RegLLTs();
798 if (!SrcTy.isVector() || !DstTy.isVector())
799 return nullptr;
800 if (SrcTy.getElementCount() != DstTy.getElementCount())
801 return nullptr;
802 if (SrcTy.getScalarSizeInBits() != DstTy.getScalarSizeInBits())
803 return nullptr;
804
805 return getOpcodeDef<GBuildVector>(Src, MRI);
806}
807
809llvm::ConstantFoldVectorBinop(unsigned Opcode, const Register Op1,
810 const Register Op2,
811 const MachineRegisterInfo &MRI) {
812 auto *SrcVec2 = getBuildVectorLikeDef(Op2, MRI);
813 if (!SrcVec2)
814 return SmallVector<APInt>();
815
816 auto *SrcVec1 = getBuildVectorLikeDef(Op1, MRI);
817 if (!SrcVec1)
818 return SmallVector<APInt>();
819
820 SmallVector<APInt> FoldedElements;
821 for (unsigned Idx = 0, E = SrcVec1->getNumSources(); Idx < E; ++Idx) {
822 auto MaybeCst = ConstantFoldBinOp(Opcode, SrcVec1->getSourceReg(Idx),
823 SrcVec2->getSourceReg(Idx), MRI);
824 if (!MaybeCst)
825 return SmallVector<APInt>();
826 FoldedElements.push_back(*MaybeCst);
827 }
828 return FoldedElements;
829}
830
832 const MachinePointerInfo &MPO) {
835 MachineFrameInfo &MFI = MF.getFrameInfo();
836 return commonAlignment(MFI.getObjectAlign(FSPV->getFrameIndex()),
837 MPO.Offset);
838 }
839
840 if (const Value *V = dyn_cast_if_present<const Value *>(MPO.V)) {
841 const Module *M = MF.getFunction().getParent();
842 return V->getPointerAlignment(M->getDataLayout());
843 }
844
845 return Align(1);
846}
847
849 const TargetInstrInfo &TII,
850 MCRegister PhysReg,
851 const TargetRegisterClass &RC,
852 const DebugLoc &DL, LLT RegTy) {
853 MachineBasicBlock &EntryMBB = MF.front();
855 Register LiveIn = MRI.getLiveInVirtReg(PhysReg);
856 if (LiveIn) {
857 MachineInstr *Def = MRI.getVRegDef(LiveIn);
858 if (Def) {
859 // FIXME: Should the verifier check this is in the entry block?
860 assert(Def->getParent() == &EntryMBB && "live-in copy not in entry block");
861 return LiveIn;
862 }
863
864 // It's possible the incoming argument register and copy was added during
865 // lowering, but later deleted due to being/becoming dead. If this happens,
866 // re-insert the copy.
867 } else {
868 // The live in register was not present, so add it.
869 LiveIn = MF.addLiveIn(PhysReg, &RC);
870 if (RegTy.isValid())
871 MRI.setType(LiveIn, RegTy);
872 }
873
874 BuildMI(EntryMBB, EntryMBB.begin(), DL, TII.get(TargetOpcode::COPY), LiveIn)
875 .addReg(PhysReg);
876 if (!EntryMBB.isLiveIn(PhysReg))
877 EntryMBB.addLiveIn(PhysReg);
878 return LiveIn;
879}
880
881std::optional<APInt> llvm::ConstantFoldExtOp(unsigned Opcode,
882 const Register Op1, uint64_t Imm,
883 const MachineRegisterInfo &MRI) {
884 auto MaybeOp1Cst = getIConstantVRegVal(Op1, MRI);
885 if (MaybeOp1Cst) {
886 switch (Opcode) {
887 default:
888 break;
889 case TargetOpcode::G_SEXT_INREG: {
890 LLT Ty = MRI.getType(Op1);
891 return MaybeOp1Cst->trunc(Imm).sext(Ty.getScalarSizeInBits());
892 }
893 }
894 }
895 return std::nullopt;
896}
897
898std::optional<APInt> llvm::ConstantFoldCastOp(unsigned Opcode, LLT DstTy,
899 const Register Op0,
900 const MachineRegisterInfo &MRI) {
901 std::optional<APInt> Val = getIConstantVRegVal(Op0, MRI);
902 if (!Val)
903 return Val;
904
905 const unsigned DstSize = DstTy.getScalarSizeInBits();
906
907 switch (Opcode) {
908 case TargetOpcode::G_SEXT:
909 return Val->sext(DstSize);
910 case TargetOpcode::G_ZEXT:
911 case TargetOpcode::G_ANYEXT:
912 // TODO: DAG considers target preference when constant folding any_extend.
913 return Val->zext(DstSize);
914 default:
915 break;
916 }
917
918 llvm_unreachable("unexpected cast opcode to constant fold");
919}
920
921std::optional<APFloat>
922llvm::ConstantFoldIntToFloat(unsigned Opcode, LLT DstTy, Register Src,
923 const MachineRegisterInfo &MRI) {
924 assert(Opcode == TargetOpcode::G_SITOFP || Opcode == TargetOpcode::G_UITOFP);
925 if (auto MaybeSrcVal = getIConstantVRegVal(Src, MRI)) {
926 APFloat DstVal(getFltSemanticForLLT(DstTy));
927 DstVal.convertFromAPInt(*MaybeSrcVal, Opcode == TargetOpcode::G_SITOFP,
929 return DstVal;
930 }
931 return std::nullopt;
932}
933
935llvm::ConstantFoldUnaryIntOp(unsigned Opcode, LLT DstTy, Register Src,
936 const MachineRegisterInfo &MRI) {
937 unsigned EltBits = DstTy.getScalarSizeInBits();
938 auto Fold = [Opcode, EltBits](const APInt &V) -> APInt {
939 switch (Opcode) {
940 case TargetOpcode::G_CTLZ:
941 case TargetOpcode::G_CTLZ_ZERO_POISON:
942 return APInt(EltBits, V.countl_zero());
943 case TargetOpcode::G_CTTZ:
944 case TargetOpcode::G_CTTZ_ZERO_POISON:
945 return APInt(EltBits, V.countr_zero());
946 case TargetOpcode::G_CTPOP:
947 return APInt(EltBits, V.popcount());
948 case TargetOpcode::G_ABS:
949 return V.abs();
950 case TargetOpcode::G_BSWAP:
951 return V.byteSwap();
952 case TargetOpcode::G_BITREVERSE:
953 return V.reverseBits();
954 }
955 llvm_unreachable("unexpected opcode in ConstantFoldUnaryIntOp");
956 };
957
958 auto tryFoldScalar = [&](Register R) -> std::optional<APInt> {
959 if (auto MaybeCst = getIConstantVRegVal(R, MRI))
960 return Fold(*MaybeCst);
961 return std::nullopt;
962 };
963 if (MRI.getType(Src).isVector()) {
964 auto *BV = getOpcodeDef<GBuildVector>(Src, MRI);
965 if (!BV)
966 return {};
967 SmallVector<APInt> Folded;
968 for (unsigned SrcIdx = 0; SrcIdx < BV->getNumSources(); ++SrcIdx) {
969 if (auto MaybeFold = tryFoldScalar(BV->getSourceReg(SrcIdx))) {
970 Folded.emplace_back(std::move(*MaybeFold));
971 continue;
972 }
973 return {};
974 }
975 return Folded;
976 }
977 if (auto MaybeCst = tryFoldScalar(Src))
978 return {std::move(*MaybeCst)};
979 return {};
980}
981
982std::optional<SmallVector<APInt>>
983llvm::ConstantFoldICmp(unsigned Pred, const Register Op1, const Register Op2,
984 unsigned DstScalarSizeInBits, unsigned ExtOp,
985 const MachineRegisterInfo &MRI) {
986 assert(ExtOp == TargetOpcode::G_SEXT || ExtOp == TargetOpcode::G_ZEXT ||
987 ExtOp == TargetOpcode::G_ANYEXT);
988
989 const LLT Ty = MRI.getType(Op1);
990
991 auto GetICmpResultCst = [&](bool IsTrue) {
992 if (IsTrue)
993 return ExtOp == TargetOpcode::G_SEXT
994 ? APInt::getAllOnes(DstScalarSizeInBits)
995 : APInt::getOneBitSet(DstScalarSizeInBits, 0);
996 return APInt::getZero(DstScalarSizeInBits);
997 };
998
999 auto TryFoldScalar = [&](Register LHS, Register RHS) -> std::optional<APInt> {
1000 auto RHSCst = getIConstantVRegVal(RHS, MRI);
1001 if (!RHSCst)
1002 return std::nullopt;
1003 auto LHSCst = getIConstantVRegVal(LHS, MRI);
1004 if (!LHSCst)
1005 return std::nullopt;
1006
1007 switch (Pred) {
1009 return GetICmpResultCst(LHSCst->eq(*RHSCst));
1011 return GetICmpResultCst(LHSCst->ne(*RHSCst));
1013 return GetICmpResultCst(LHSCst->ugt(*RHSCst));
1015 return GetICmpResultCst(LHSCst->uge(*RHSCst));
1017 return GetICmpResultCst(LHSCst->ult(*RHSCst));
1019 return GetICmpResultCst(LHSCst->ule(*RHSCst));
1021 return GetICmpResultCst(LHSCst->sgt(*RHSCst));
1023 return GetICmpResultCst(LHSCst->sge(*RHSCst));
1025 return GetICmpResultCst(LHSCst->slt(*RHSCst));
1027 return GetICmpResultCst(LHSCst->sle(*RHSCst));
1028 default:
1029 return std::nullopt;
1030 }
1031 };
1032
1033 SmallVector<APInt> FoldedICmps;
1034
1035 if (Ty.isVector()) {
1036 // Try to constant fold each element.
1037 auto *BV1 = getOpcodeDef<GBuildVector>(Op1, MRI);
1038 auto *BV2 = getOpcodeDef<GBuildVector>(Op2, MRI);
1039 if (!BV1 || !BV2)
1040 return std::nullopt;
1041 assert(BV1->getNumSources() == BV2->getNumSources() && "Invalid vectors");
1042 for (unsigned I = 0; I < BV1->getNumSources(); ++I) {
1043 if (auto MaybeFold =
1044 TryFoldScalar(BV1->getSourceReg(I), BV2->getSourceReg(I))) {
1045 FoldedICmps.emplace_back(*MaybeFold);
1046 continue;
1047 }
1048 return std::nullopt;
1049 }
1050 return FoldedICmps;
1051 }
1052
1053 if (auto MaybeCst = TryFoldScalar(Op1, Op2)) {
1054 FoldedICmps.emplace_back(*MaybeCst);
1055 return FoldedICmps;
1056 }
1057
1058 return std::nullopt;
1059}
1060
1062 GISelValueTracking *VT, bool OrNegative) {
1063 std::optional<DefinitionAndSourceRegister> DefSrcReg =
1065 if (!DefSrcReg)
1066 return false;
1067
1068 const MachineInstr &MI = *DefSrcReg->MI;
1069 const LLT Ty = MRI.getType(Reg);
1070
1071 auto IsPow2 = [OrNegative](const APInt &V) {
1072 return V.isPowerOf2() || (OrNegative && V.isNegatedPowerOf2());
1073 };
1074
1075 switch (MI.getOpcode()) {
1076 case TargetOpcode::G_CONSTANT: {
1077 unsigned BitWidth = Ty.getScalarSizeInBits();
1078 const ConstantInt *CI = MI.getOperand(1).getCImm();
1079 return IsPow2(CI->getValue().zextOrTrunc(BitWidth));
1080 }
1081 case TargetOpcode::G_SHL: {
1082 // A left-shift of a constant one will have exactly one bit set because
1083 // shifting the bit off the end is undefined.
1084
1085 // TODO: Constant splat
1086 if (auto ConstLHS = getIConstantVRegVal(MI.getOperand(1).getReg(), MRI)) {
1087 if (*ConstLHS == 1)
1088 return true;
1089 }
1090
1091 break;
1092 }
1093 case TargetOpcode::G_LSHR: {
1094 if (auto ConstLHS = getIConstantVRegVal(MI.getOperand(1).getReg(), MRI)) {
1095 if (ConstLHS->isSignMask())
1096 return true;
1097 }
1098
1099 break;
1100 }
1101 case TargetOpcode::G_BUILD_VECTOR: {
1102 // TODO: Probably should have a recursion depth guard since you could have
1103 // bitcasted vector elements.
1104 for (const MachineOperand &MO : llvm::drop_begin(MI.operands()))
1105 if (!isKnownToBeAPowerOfTwo(MO.getReg(), MRI, VT, OrNegative))
1106 return false;
1107
1108 return true;
1109 }
1110 case TargetOpcode::G_BUILD_VECTOR_TRUNC: {
1111 // Only handle constants since we would need to know if number of leading
1112 // zeros is greater than the truncation amount.
1113 const unsigned BitWidth = Ty.getScalarSizeInBits();
1114 for (const MachineOperand &MO : llvm::drop_begin(MI.operands())) {
1115 auto Const = getIConstantVRegVal(MO.getReg(), MRI);
1116 if (!Const || !IsPow2(Const->zextOrTrunc(BitWidth)))
1117 return false;
1118 }
1119
1120 return true;
1121 }
1122 default:
1123 break;
1124 }
1125
1126 if (!VT)
1127 return false;
1128
1129 // More could be done here, though the above checks are enough
1130 // to handle some common cases.
1131
1132 // Fall back to computeKnownBits to catch other known cases.
1133 KnownBits Known = VT->getKnownBits(Reg);
1134 return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
1135}
1136
1140
1141LLT llvm::getLCMType(LLT OrigTy, LLT TargetTy) {
1142 if (OrigTy.getSizeInBits() == TargetTy.getSizeInBits())
1143 return OrigTy;
1144
1145 if (OrigTy.isVector() && TargetTy.isVector()) {
1146 LLT OrigElt = OrigTy.getElementType();
1147 LLT TargetElt = TargetTy.getElementType();
1148
1149 // TODO: The docstring for this function says the intention is to use this
1150 // function to build MERGE/UNMERGE instructions. It won't be the case that
1151 // we generate a MERGE/UNMERGE between fixed and scalable vector types. We
1152 // could implement getLCMType between the two in the future if there was a
1153 // need, but it is not worth it now as this function should not be used in
1154 // that way.
1155 assert(((OrigTy.isScalableVector() && !TargetTy.isFixedVector()) ||
1156 (OrigTy.isFixedVector() && !TargetTy.isScalableVector())) &&
1157 "getLCMType not implemented between fixed and scalable vectors.");
1158
1159 if (OrigElt.getSizeInBits() == TargetElt.getSizeInBits()) {
1160 int GCDMinElts = std::gcd(OrigTy.getElementCount().getKnownMinValue(),
1161 TargetTy.getElementCount().getKnownMinValue());
1162 // Prefer the original element type.
1163 ElementCount Mul = OrigTy.getElementCount() *
1164 TargetTy.getElementCount().getKnownMinValue();
1165 return LLT::vector(Mul.divideCoefficientBy(GCDMinElts),
1166 OrigTy.getElementType());
1167 }
1168 unsigned LCM = std::lcm(OrigTy.getSizeInBits().getKnownMinValue(),
1169 TargetTy.getSizeInBits().getKnownMinValue());
1170 return LLT::vector(
1171 ElementCount::get(LCM / OrigElt.getSizeInBits(), OrigTy.isScalable()),
1172 OrigElt);
1173 }
1174
1175 // One type is scalar, one type is vector
1176 if (OrigTy.isVector() || TargetTy.isVector()) {
1177 LLT VecTy = OrigTy.isVector() ? OrigTy : TargetTy;
1178 LLT ScalarTy = OrigTy.isVector() ? TargetTy : OrigTy;
1179 LLT EltTy = VecTy.getElementType();
1180 LLT OrigEltTy = OrigTy.isVector() ? OrigTy.getElementType() : OrigTy;
1181
1182 // Prefer scalar type from OrigTy.
1183 if (EltTy.getSizeInBits() == ScalarTy.getSizeInBits())
1184 return LLT::vector(VecTy.getElementCount(), OrigEltTy);
1185
1186 // Different size scalars. Create vector with the same total size.
1187 // LCM will take fixed/scalable from VecTy.
1188 unsigned LCM = std::lcm(EltTy.getSizeInBits().getFixedValue() *
1190 ScalarTy.getSizeInBits().getFixedValue());
1191 // Prefer type from OrigTy
1192 return LLT::vector(ElementCount::get(LCM / OrigEltTy.getSizeInBits(),
1193 VecTy.getElementCount().isScalable()),
1194 OrigEltTy);
1195 }
1196
1197 // At this point, both types are scalars of different size
1198 unsigned LCM = std::lcm(OrigTy.getSizeInBits().getFixedValue(),
1199 TargetTy.getSizeInBits().getFixedValue());
1200 // Preserve pointer types.
1201 if (LCM == OrigTy.getSizeInBits())
1202 return OrigTy;
1203 if (LCM == TargetTy.getSizeInBits())
1204 return TargetTy;
1205 return LLT::scalar(LCM);
1206}
1207
1208LLT llvm::getCoverTy(LLT OrigTy, LLT TargetTy) {
1209
1210 if ((OrigTy.isScalableVector() && TargetTy.isFixedVector()) ||
1211 (OrigTy.isFixedVector() && TargetTy.isScalableVector()))
1213 "getCoverTy not implemented between fixed and scalable vectors.");
1214
1215 if (!OrigTy.isVector() || !TargetTy.isVector() || OrigTy == TargetTy ||
1216 (OrigTy.getScalarSizeInBits() != TargetTy.getScalarSizeInBits()))
1217 return getLCMType(OrigTy, TargetTy);
1218
1219 unsigned OrigTyNumElts = OrigTy.getElementCount().getKnownMinValue();
1220 unsigned TargetTyNumElts = TargetTy.getElementCount().getKnownMinValue();
1221 if (OrigTyNumElts % TargetTyNumElts == 0)
1222 return OrigTy;
1223
1224 unsigned NumElts = alignTo(OrigTyNumElts, TargetTyNumElts);
1226 OrigTy.getElementType());
1227}
1228
1229LLT llvm::getGCDType(LLT OrigTy, LLT TargetTy) {
1230 if (OrigTy.getSizeInBits() == TargetTy.getSizeInBits())
1231 return OrigTy;
1232
1233 if (OrigTy.isVector() && TargetTy.isVector()) {
1234 LLT OrigElt = OrigTy.getElementType();
1235
1236 // TODO: The docstring for this function says the intention is to use this
1237 // function to build MERGE/UNMERGE instructions. It won't be the case that
1238 // we generate a MERGE/UNMERGE between fixed and scalable vector types. We
1239 // could implement getGCDType between the two in the future if there was a
1240 // need, but it is not worth it now as this function should not be used in
1241 // that way.
1242 assert(((OrigTy.isScalableVector() && !TargetTy.isFixedVector()) ||
1243 (OrigTy.isFixedVector() && !TargetTy.isScalableVector())) &&
1244 "getGCDType not implemented between fixed and scalable vectors.");
1245
1246 unsigned GCD = std::gcd(OrigTy.getSizeInBits().getKnownMinValue(),
1247 TargetTy.getSizeInBits().getKnownMinValue());
1248 if (GCD == OrigElt.getSizeInBits())
1250 OrigElt);
1251
1252 // Cannot produce original element type, but both have vscale in common.
1253 if (GCD < OrigElt.getSizeInBits())
1255 GCD);
1256
1257 return LLT::vector(
1259 OrigTy.isScalable()),
1260 OrigElt);
1261 }
1262
1263 // If one type is vector and the element size matches the scalar size, then
1264 // the gcd is the scalar type.
1265 if (OrigTy.isVector() &&
1266 OrigTy.getElementType().getSizeInBits() == TargetTy.getSizeInBits())
1267 return OrigTy.getElementType();
1268 if (TargetTy.isVector() &&
1269 TargetTy.getElementType().getSizeInBits() == OrigTy.getSizeInBits())
1270 return OrigTy;
1271
1272 // At this point, both types are either scalars of different type or one is a
1273 // vector and one is a scalar. If both types are scalars, the GCD type is the
1274 // GCD between the two scalar sizes. If one is vector and one is scalar, then
1275 // the GCD type is the GCD between the scalar and the vector element size.
1276 LLT OrigScalar = OrigTy.getScalarType();
1277 LLT TargetScalar = TargetTy.getScalarType();
1278 unsigned GCD = std::gcd(OrigScalar.getSizeInBits().getFixedValue(),
1279 TargetScalar.getSizeInBits().getFixedValue());
1280 return LLT::integer(GCD);
1281}
1282
1284 assert(MI.getOpcode() == TargetOpcode::G_SHUFFLE_VECTOR &&
1285 "Only G_SHUFFLE_VECTOR can have a splat index!");
1286 ArrayRef<int> Mask = MI.getOperand(3).getShuffleMask();
1287 auto FirstDefinedIdx = find_if(Mask, [](int Elt) { return Elt >= 0; });
1288
1289 // If all elements are undefined, this shuffle can be considered a splat.
1290 // Return 0 for better potential for callers to simplify.
1291 if (FirstDefinedIdx == Mask.end())
1292 return 0;
1293
1294 // Make sure all remaining elements are either undef or the same
1295 // as the first non-undef value.
1296 int SplatValue = *FirstDefinedIdx;
1297 if (any_of(make_range(std::next(FirstDefinedIdx), Mask.end()),
1298 [&SplatValue](int Elt) { return Elt >= 0 && Elt != SplatValue; }))
1299 return std::nullopt;
1300
1301 return SplatValue;
1302}
1303
1304static bool isBuildVectorOp(unsigned Opcode) {
1305 return Opcode == TargetOpcode::G_BUILD_VECTOR ||
1306 Opcode == TargetOpcode::G_BUILD_VECTOR_TRUNC;
1307}
1308
1309namespace {
1310
1311std::optional<ValueAndVReg> getAnyConstantSplat(Register VReg,
1312 const MachineRegisterInfo &MRI,
1313 bool AllowUndef) {
1314 MachineInstr *MI = getDefIgnoringCopies(VReg, MRI);
1315 if (!MI)
1316 return std::nullopt;
1317
1318 bool isConcatVectorsOp = MI->getOpcode() == TargetOpcode::G_CONCAT_VECTORS;
1319 if (!isBuildVectorOp(MI->getOpcode()) && !isConcatVectorsOp)
1320 return std::nullopt;
1321
1322 std::optional<ValueAndVReg> SplatValAndReg;
1323 for (MachineOperand &Op : MI->uses()) {
1324 Register Element = Op.getReg();
1325 // If we have a G_CONCAT_VECTOR, we recursively look into the
1326 // vectors that we're concatenating to see if they're splats.
1327 auto ElementValAndReg =
1328 isConcatVectorsOp
1329 ? getAnyConstantSplat(Element, MRI, AllowUndef)
1331
1332 // If AllowUndef, treat undef as value that will result in a constant splat.
1333 if (!ElementValAndReg) {
1334 if (AllowUndef && mi_match(Element, MRI, m_GImplicitDef()))
1335 continue;
1336 return std::nullopt;
1337 }
1338
1339 // Record splat value
1340 if (!SplatValAndReg)
1341 SplatValAndReg = ElementValAndReg;
1342
1343 // Different constant than the one already recorded, not a constant splat.
1344 if (SplatValAndReg->Value != ElementValAndReg->Value)
1345 return std::nullopt;
1346 }
1347
1348 return SplatValAndReg;
1349}
1350
1351} // end anonymous namespace
1352
1354 const MachineRegisterInfo &MRI,
1355 int64_t SplatValue, bool AllowUndef) {
1356 if (auto SplatValAndReg = getAnyConstantSplat(Reg, MRI, AllowUndef))
1357 return SplatValAndReg->Value.getSExtValue() == SplatValue;
1358
1359 return false;
1360}
1361
1363 const MachineRegisterInfo &MRI,
1364 const APInt &SplatValue,
1365 bool AllowUndef) {
1366 if (auto SplatValAndReg = getAnyConstantSplat(Reg, MRI, AllowUndef)) {
1367 if (SplatValAndReg->Value.getBitWidth() < SplatValue.getBitWidth())
1368 return APInt::isSameValue(
1369 SplatValAndReg->Value.sext(SplatValue.getBitWidth()), SplatValue);
1370 return APInt::isSameValue(
1371 SplatValAndReg->Value,
1372 SplatValue.sext(SplatValAndReg->Value.getBitWidth()));
1373 }
1374
1375 return false;
1376}
1377
1379 const MachineRegisterInfo &MRI,
1380 int64_t SplatValue, bool AllowUndef) {
1381 return isBuildVectorConstantSplat(MI.getOperand(0).getReg(), MRI, SplatValue,
1382 AllowUndef);
1383}
1384
1386 const MachineRegisterInfo &MRI,
1387 const APInt &SplatValue,
1388 bool AllowUndef) {
1389 return isBuildVectorConstantSplat(MI.getOperand(0).getReg(), MRI, SplatValue,
1390 AllowUndef);
1391}
1392
1393std::optional<APInt>
1395 if (auto SplatValAndReg =
1396 getAnyConstantSplat(Reg, MRI, /* AllowUndef */ false)) {
1397 if (std::optional<ValueAndVReg> ValAndVReg =
1398 getIConstantVRegValWithLookThrough(SplatValAndReg->VReg, MRI))
1399 return ValAndVReg->Value;
1400 }
1401
1402 return std::nullopt;
1403}
1404
1405std::optional<APInt>
1407 const MachineRegisterInfo &MRI) {
1408 return getIConstantSplatVal(MI.getOperand(0).getReg(), MRI);
1409}
1410
1411std::optional<int64_t>
1413 const MachineRegisterInfo &MRI) {
1414 if (auto SplatValAndReg =
1415 getAnyConstantSplat(Reg, MRI, /* AllowUndef */ false))
1416 return getIConstantVRegSExtVal(SplatValAndReg->VReg, MRI);
1417 return std::nullopt;
1418}
1419
1420std::optional<int64_t>
1422 const MachineRegisterInfo &MRI) {
1423 return getIConstantSplatSExtVal(MI.getOperand(0).getReg(), MRI);
1424}
1425
1426std::optional<FPValueAndVReg>
1428 bool AllowUndef) {
1429 if (auto SplatValAndReg = getAnyConstantSplat(VReg, MRI, AllowUndef))
1430 return getFConstantVRegValWithLookThrough(SplatValAndReg->VReg, MRI);
1431 return std::nullopt;
1432}
1433
1435 const MachineRegisterInfo &MRI,
1436 bool AllowUndef) {
1437 return isBuildVectorConstantSplat(MI, MRI, 0, AllowUndef);
1438}
1439
1441 const MachineRegisterInfo &MRI,
1442 bool AllowUndef) {
1443 return isBuildVectorConstantSplat(MI, MRI, -1, AllowUndef);
1444}
1445
1446std::optional<Register> llvm::getVectorSplat(const MachineInstr &MI,
1447 const MachineRegisterInfo &MRI) {
1448 unsigned Opc = MI.getOpcode();
1449 if (Opc == TargetOpcode::G_SPLAT_VECTOR)
1450 return MI.getOperand(1).getReg();
1451
1452 if (!isBuildVectorOp(Opc))
1453 return std::nullopt;
1454 auto Reg = MI.getOperand(1).getReg();
1455 if (any_of(drop_begin(MI.operands(), 2),
1456 [&Reg](const MachineOperand &Op) { return Op.getReg() != Reg; }))
1457 return std::nullopt;
1458 return Reg;
1459}
1460
1462 const MachineRegisterInfo &MRI,
1463 bool AllowFP = true,
1464 bool AllowOpaqueConstants = true) {
1465 switch (MI.getOpcode()) {
1466 case TargetOpcode::G_CONSTANT:
1467 case TargetOpcode::G_IMPLICIT_DEF:
1468 return true;
1469 case TargetOpcode::G_FCONSTANT:
1470 return AllowFP;
1471 case TargetOpcode::G_GLOBAL_VALUE:
1472 case TargetOpcode::G_FRAME_INDEX:
1473 case TargetOpcode::G_BLOCK_ADDR:
1474 case TargetOpcode::G_JUMP_TABLE:
1475 return AllowOpaqueConstants;
1476 default:
1477 return false;
1478 }
1479}
1480
1482 const MachineRegisterInfo &MRI) {
1483 Register Def = MI.getOperand(0).getReg();
1484 if (auto C = getIConstantVRegValWithLookThrough(Def, MRI))
1485 return true;
1487 if (!BV)
1488 return false;
1489 for (unsigned SrcIdx = 0; SrcIdx < BV->getNumSources(); ++SrcIdx) {
1490 if (getIConstantVRegValWithLookThrough(BV->getSourceReg(SrcIdx), MRI) ||
1491 getOpcodeDef<GImplicitDef>(BV->getSourceReg(SrcIdx), MRI))
1492 continue;
1493 return false;
1494 }
1495 return true;
1496}
1497
1499 const MachineRegisterInfo &MRI,
1500 bool AllowFP, bool AllowOpaqueConstants) {
1501 if (isConstantScalar(MI, MRI, AllowFP, AllowOpaqueConstants))
1502 return true;
1503
1504 if (!isBuildVectorOp(MI.getOpcode()))
1505 return false;
1506
1507 const unsigned NumOps = MI.getNumOperands();
1508 for (unsigned I = 1; I != NumOps; ++I) {
1509 const MachineInstr *ElementDef = MRI.getVRegDef(MI.getOperand(I).getReg());
1510 if (!isConstantScalar(*ElementDef, MRI, AllowFP, AllowOpaqueConstants))
1511 return false;
1512 }
1513
1514 return true;
1515}
1516
1517std::optional<APInt>
1519 const MachineRegisterInfo &MRI) {
1520 if (auto C = getIConstantVRegValWithLookThrough(Def, MRI))
1521 return C->Value;
1522 auto MaybeCst = getIConstantSplatSExtVal(Def, MRI);
1523 if (!MaybeCst)
1524 return std::nullopt;
1525 const unsigned ScalarSize = MRI.getType(Def).getScalarSizeInBits();
1526 return APInt(ScalarSize, *MaybeCst, true);
1527}
1528
1529std::optional<APFloat>
1531 const MachineRegisterInfo &MRI) {
1532 if (auto FpConst = getFConstantVRegValWithLookThrough(Def, MRI))
1533 return FpConst->Value;
1534 auto MaybeCstFP = getFConstantSplat(Def, MRI, /*allowUndef=*/false);
1535 if (!MaybeCstFP)
1536 return std::nullopt;
1537 return MaybeCstFP->Value;
1538}
1539
1541 const MachineRegisterInfo &MRI, bool AllowUndefs) {
1542 switch (MI.getOpcode()) {
1543 case TargetOpcode::G_IMPLICIT_DEF:
1544 return AllowUndefs;
1545 case TargetOpcode::G_CONSTANT:
1546 return MI.getOperand(1).getCImm()->isNullValue();
1547 case TargetOpcode::G_FCONSTANT: {
1548 const ConstantFP *FPImm = MI.getOperand(1).getFPImm();
1549 return FPImm->isZero() && !FPImm->isNegative();
1550 }
1551 default:
1552 if (!AllowUndefs) // TODO: isBuildVectorAllZeros assumes undef is OK already
1553 return false;
1554 return isBuildVectorAllZeros(MI, MRI);
1555 }
1556}
1557
1559 const MachineRegisterInfo &MRI,
1560 bool AllowUndefs) {
1561 switch (MI.getOpcode()) {
1562 case TargetOpcode::G_IMPLICIT_DEF:
1563 return AllowUndefs;
1564 case TargetOpcode::G_CONSTANT:
1565 return MI.getOperand(1).getCImm()->isAllOnesValue();
1566 default:
1567 if (!AllowUndefs) // TODO: isBuildVectorAllOnes assumes undef is OK already
1568 return false;
1569 return isBuildVectorAllOnes(MI, MRI);
1570 }
1571}
1572
1574 const MachineRegisterInfo &MRI, Register Reg,
1575 llvm::function_ref<bool(const Constant *ConstVal)> Match,
1576 bool AllowUndefs) {
1577
1578 const MachineInstr *Def = getDefIgnoringCopies(Reg, MRI);
1579 if (AllowUndefs && Def->getOpcode() == TargetOpcode::G_IMPLICIT_DEF)
1580 return Match(nullptr);
1581
1582 // TODO: Also handle fconstant
1583 if (Def->getOpcode() == TargetOpcode::G_CONSTANT)
1584 return Match(Def->getOperand(1).getCImm());
1585
1586 if (Def->getOpcode() != TargetOpcode::G_BUILD_VECTOR)
1587 return false;
1588
1589 for (unsigned I = 1, E = Def->getNumOperands(); I != E; ++I) {
1590 Register SrcElt = Def->getOperand(I).getReg();
1591 const MachineInstr *SrcDef = getDefIgnoringCopies(SrcElt, MRI);
1592 if (AllowUndefs && SrcDef->getOpcode() == TargetOpcode::G_IMPLICIT_DEF) {
1593 if (!Match(nullptr))
1594 return false;
1595 continue;
1596 }
1597
1598 if (SrcDef->getOpcode() != TargetOpcode::G_CONSTANT ||
1599 !Match(SrcDef->getOperand(1).getCImm()))
1600 return false;
1601 }
1602
1603 return true;
1604}
1605
1606bool llvm::isConstTrueVal(const TargetLowering &TLI, int64_t Val, bool IsVector,
1607 bool IsFP) {
1608 switch (TLI.getBooleanContents(IsVector, IsFP)) {
1610 return Val & 0x1;
1612 return Val == 1;
1614 return Val == -1;
1615 }
1616 llvm_unreachable("Invalid boolean contents");
1617}
1618
1619bool llvm::isConstFalseVal(const TargetLowering &TLI, int64_t Val,
1620 bool IsVector, bool IsFP) {
1621 switch (TLI.getBooleanContents(IsVector, IsFP)) {
1623 return ~Val & 0x1;
1626 return Val == 0;
1627 }
1628 llvm_unreachable("Invalid boolean contents");
1629}
1630
1631int64_t llvm::getICmpTrueVal(const TargetLowering &TLI, bool IsVector,
1632 bool IsFP) {
1633 switch (TLI.getBooleanContents(IsVector, IsFP)) {
1636 return 1;
1638 return -1;
1639 }
1640 llvm_unreachable("Invalid boolean contents");
1641}
1642
1644 LostDebugLocObserver *LocObserver,
1645 SmallInstListTy &DeadInstChain) {
1646 for (MachineOperand &Op : MI.uses()) {
1647 if (Op.isReg() && Op.getReg().isVirtual())
1648 DeadInstChain.insert(MRI.getVRegDef(Op.getReg()));
1649 }
1650 LLVM_DEBUG(dbgs() << MI << "Is dead; erasing.\n");
1651 DeadInstChain.remove(&MI);
1652 MI.eraseFromParent();
1653 if (LocObserver)
1654 LocObserver->checkpoint(false);
1655}
1656
1659 LostDebugLocObserver *LocObserver) {
1660 SmallInstListTy DeadInstChain;
1661 for (MachineInstr *MI : DeadInstrs)
1662 saveUsesAndErase(*MI, MRI, LocObserver, DeadInstChain);
1663
1664 while (!DeadInstChain.empty()) {
1665 MachineInstr *Inst = DeadInstChain.pop_back_val();
1666 if (!isTriviallyDead(*Inst, MRI))
1667 continue;
1668 saveUsesAndErase(*Inst, MRI, LocObserver, DeadInstChain);
1669 }
1670}
1671
1673 LostDebugLocObserver *LocObserver) {
1674 return eraseInstrs({&MI}, MRI, LocObserver);
1675}
1676
1678 for (auto &Def : MI.defs()) {
1679 assert(Def.isReg() && "Must be a reg");
1680
1682 for (auto &MOUse : MRI.use_operands(Def.getReg())) {
1683 MachineInstr *DbgValue = MOUse.getParent();
1684 // Ignore partially formed DBG_VALUEs.
1685 if (DbgValue->isNonListDebugValue() && DbgValue->getNumOperands() == 4) {
1686 DbgUsers.push_back(&MOUse);
1687 }
1688 }
1689
1690 if (!DbgUsers.empty()) {
1691 salvageDebugInfoForDbgValue(MRI, MI, DbgUsers);
1692 }
1693 }
1694}
1695
1697 switch (Opc) {
1698 case TargetOpcode::G_FABS:
1699 case TargetOpcode::G_FADD:
1700 case TargetOpcode::G_FCANONICALIZE:
1701 case TargetOpcode::G_FCEIL:
1702 case TargetOpcode::G_FCONSTANT:
1703 case TargetOpcode::G_FCOPYSIGN:
1704 case TargetOpcode::G_FCOS:
1705 case TargetOpcode::G_FDIV:
1706 case TargetOpcode::G_FEXP2:
1707 case TargetOpcode::G_FEXP:
1708 case TargetOpcode::G_FFLOOR:
1709 case TargetOpcode::G_FLOG10:
1710 case TargetOpcode::G_FLOG2:
1711 case TargetOpcode::G_FLOG:
1712 case TargetOpcode::G_FMA:
1713 case TargetOpcode::G_FMAD:
1714 case TargetOpcode::G_FMAXIMUM:
1715 case TargetOpcode::G_FMAXIMUMNUM:
1716 case TargetOpcode::G_FMAXNUM:
1717 case TargetOpcode::G_FMAXNUM_IEEE:
1718 case TargetOpcode::G_FMINIMUM:
1719 case TargetOpcode::G_FMINIMUMNUM:
1720 case TargetOpcode::G_FMINNUM:
1721 case TargetOpcode::G_FMINNUM_IEEE:
1722 case TargetOpcode::G_FMUL:
1723 case TargetOpcode::G_FNEARBYINT:
1724 case TargetOpcode::G_FNEG:
1725 case TargetOpcode::G_FPEXT:
1726 case TargetOpcode::G_FPEXTLOAD:
1727 case TargetOpcode::G_FPOW:
1728 case TargetOpcode::G_FPTRUNC:
1729 case TargetOpcode::G_FPTRUNCSTORE:
1730 case TargetOpcode::G_FREM:
1731 case TargetOpcode::G_FRINT:
1732 case TargetOpcode::G_FSIN:
1733 case TargetOpcode::G_FTAN:
1734 case TargetOpcode::G_FACOS:
1735 case TargetOpcode::G_FASIN:
1736 case TargetOpcode::G_FATAN:
1737 case TargetOpcode::G_FATAN2:
1738 case TargetOpcode::G_FCOSH:
1739 case TargetOpcode::G_FSINH:
1740 case TargetOpcode::G_FTANH:
1741 case TargetOpcode::G_FSQRT:
1742 case TargetOpcode::G_FSUB:
1743 case TargetOpcode::G_INTRINSIC_ROUND:
1744 case TargetOpcode::G_INTRINSIC_ROUNDEVEN:
1745 case TargetOpcode::G_INTRINSIC_TRUNC:
1746 return true;
1747 default:
1748 return false;
1749 }
1750}
1751
1752/// Shifts return poison if shiftwidth is larger than the bitwidth.
1753static bool shiftAmountKnownInRange(Register ShiftAmount,
1754 const MachineRegisterInfo &MRI) {
1755 LLT Ty = MRI.getType(ShiftAmount);
1756
1757 if (Ty.isScalableVector())
1758 return false; // Can't tell, just return false to be safe
1759
1760 if (Ty.isScalar()) {
1761 std::optional<ValueAndVReg> Val =
1762 getIConstantVRegValWithLookThrough(ShiftAmount, MRI);
1763 if (!Val)
1764 return false;
1765 return Val->Value.ult(Ty.getScalarSizeInBits());
1766 }
1767
1768 GBuildVector *BV = getOpcodeDef<GBuildVector>(ShiftAmount, MRI);
1769 if (!BV)
1770 return false;
1771
1772 unsigned Sources = BV->getNumSources();
1773 for (unsigned I = 0; I < Sources; ++I) {
1774 std::optional<ValueAndVReg> Val =
1776 if (!Val)
1777 return false;
1778 if (!Val->Value.ult(Ty.getScalarSizeInBits()))
1779 return false;
1780 }
1781
1782 return true;
1783}
1784
1786 bool ConsiderFlagsAndMetadata,
1787 UndefPoisonKind Kind) {
1788 MachineInstr *RegDef = MRI.getVRegDef(Reg);
1789
1790 if (ConsiderFlagsAndMetadata && includesPoison(Kind))
1791 if (auto *GMI = dyn_cast<GenericMachineInstr>(RegDef))
1792 if (GMI->hasPoisonGeneratingFlags())
1793 return true;
1794
1795 // Check whether opcode is a poison/undef-generating operation.
1796 switch (RegDef->getOpcode()) {
1797 case TargetOpcode::G_BUILD_VECTOR:
1798 case TargetOpcode::G_CONSTANT_FOLD_BARRIER:
1799 return false;
1800 case TargetOpcode::G_SHL:
1801 case TargetOpcode::G_ASHR:
1802 case TargetOpcode::G_LSHR:
1803 return includesPoison(Kind) &&
1804 !shiftAmountKnownInRange(RegDef->getOperand(2).getReg(), MRI);
1805 case TargetOpcode::G_FPTOSI:
1806 case TargetOpcode::G_FPTOUI:
1807 // fptosi/ui yields poison if the resulting value does not fit in the
1808 // destination type.
1809 return true;
1810 case TargetOpcode::G_CTLZ:
1811 case TargetOpcode::G_CTTZ:
1812 case TargetOpcode::G_CTLS:
1813 case TargetOpcode::G_ABS:
1814 case TargetOpcode::G_CTPOP:
1815 case TargetOpcode::G_BSWAP:
1816 case TargetOpcode::G_BITREVERSE:
1817 case TargetOpcode::G_FSHL:
1818 case TargetOpcode::G_FSHR:
1819 case TargetOpcode::G_SMAX:
1820 case TargetOpcode::G_SMIN:
1821 case TargetOpcode::G_SCMP:
1822 case TargetOpcode::G_UMAX:
1823 case TargetOpcode::G_UMIN:
1824 case TargetOpcode::G_UCMP:
1825 case TargetOpcode::G_PTRMASK:
1826 case TargetOpcode::G_SADDO:
1827 case TargetOpcode::G_SSUBO:
1828 case TargetOpcode::G_UADDO:
1829 case TargetOpcode::G_USUBO:
1830 case TargetOpcode::G_SMULO:
1831 case TargetOpcode::G_UMULO:
1832 case TargetOpcode::G_SADDSAT:
1833 case TargetOpcode::G_UADDSAT:
1834 case TargetOpcode::G_SSUBSAT:
1835 case TargetOpcode::G_USUBSAT:
1836 case TargetOpcode::G_SBFX:
1837 case TargetOpcode::G_UBFX:
1838 return false;
1839 case TargetOpcode::G_SSHLSAT:
1840 case TargetOpcode::G_USHLSAT:
1841 return includesPoison(Kind) &&
1842 !shiftAmountKnownInRange(RegDef->getOperand(2).getReg(), MRI);
1843 case TargetOpcode::G_INSERT_VECTOR_ELT: {
1845 if (includesPoison(Kind)) {
1846 std::optional<ValueAndVReg> Index =
1847 getIConstantVRegValWithLookThrough(Insert->getIndexReg(), MRI);
1848 if (!Index)
1849 return true;
1850 LLT VecTy = MRI.getType(Insert->getVectorReg());
1851 return Index->Value.uge(VecTy.getElementCount().getKnownMinValue());
1852 }
1853 return false;
1854 }
1855 case TargetOpcode::G_EXTRACT_VECTOR_ELT: {
1857 if (includesPoison(Kind)) {
1858 std::optional<ValueAndVReg> Index =
1860 if (!Index)
1861 return true;
1862 LLT VecTy = MRI.getType(Extract->getVectorReg());
1863 return Index->Value.uge(VecTy.getElementCount().getKnownMinValue());
1864 }
1865 return false;
1866 }
1867 case TargetOpcode::G_SHUFFLE_VECTOR: {
1868 GShuffleVector *Shuffle = cast<GShuffleVector>(RegDef);
1869 ArrayRef<int> Mask = Shuffle->getMask();
1870 return includesPoison(Kind) && is_contained(Mask, -1);
1871 }
1872 case TargetOpcode::G_FNEG:
1873 case TargetOpcode::G_PHI:
1874 case TargetOpcode::G_SELECT:
1875 case TargetOpcode::G_UREM:
1876 case TargetOpcode::G_SREM:
1877 case TargetOpcode::G_FREEZE:
1878 case TargetOpcode::G_ICMP:
1879 case TargetOpcode::G_FCMP:
1880 case TargetOpcode::G_FADD:
1881 case TargetOpcode::G_FSUB:
1882 case TargetOpcode::G_FMUL:
1883 case TargetOpcode::G_FDIV:
1884 case TargetOpcode::G_FREM:
1885 case TargetOpcode::G_PTR_ADD:
1886 return false;
1887 default:
1888 return !isa<GCastOp>(RegDef) && !isa<GBinOp>(RegDef);
1889 }
1890}
1891
1893 const MachineRegisterInfo &MRI,
1894 unsigned Depth,
1895 UndefPoisonKind Kind) {
1897 return false;
1898
1899 MachineInstr *RegDef = MRI.getVRegDef(Reg);
1900
1901 switch (RegDef->getOpcode()) {
1902 case TargetOpcode::G_FREEZE:
1903 return true;
1904 case TargetOpcode::G_IMPLICIT_DEF:
1905 return !includesUndef(Kind);
1906 case TargetOpcode::G_CONSTANT:
1907 case TargetOpcode::G_FCONSTANT:
1908 return true;
1909 case TargetOpcode::G_BUILD_VECTOR: {
1910 GBuildVector *BV = cast<GBuildVector>(RegDef);
1911 unsigned NumSources = BV->getNumSources();
1912 for (unsigned I = 0; I < NumSources; ++I)
1914 Depth + 1, Kind))
1915 return false;
1916 return true;
1917 }
1918 case TargetOpcode::G_PHI: {
1919 GPhi *Phi = cast<GPhi>(RegDef);
1920 unsigned NumIncoming = Phi->getNumIncomingValues();
1921 for (unsigned I = 0; I < NumIncoming; ++I)
1922 if (!::isGuaranteedNotToBeUndefOrPoison(Phi->getIncomingValue(I), MRI,
1923 Depth + 1, Kind))
1924 return false;
1925 return true;
1926 }
1927 default: {
1928 auto MOCheck = [&](const MachineOperand &MO) {
1929 if (!MO.isReg())
1930 return true;
1931 return ::isGuaranteedNotToBeUndefOrPoison(MO.getReg(), MRI, Depth + 1,
1932 Kind);
1933 };
1934 return !::canCreateUndefOrPoison(Reg, MRI,
1935 /*ConsiderFlagsAndMetadata=*/true, Kind) &&
1936 all_of(RegDef->uses(), MOCheck);
1937 }
1938 }
1939}
1940
1942 bool ConsiderFlagsAndMetadata) {
1943 return ::canCreateUndefOrPoison(Reg, MRI, ConsiderFlagsAndMetadata,
1945}
1946
1948 bool ConsiderFlagsAndMetadata = true) {
1949 return ::canCreateUndefOrPoison(Reg, MRI, ConsiderFlagsAndMetadata,
1951}
1952
1954 const MachineRegisterInfo &MRI,
1955 unsigned Depth) {
1956 return ::isGuaranteedNotToBeUndefOrPoison(Reg, MRI, Depth,
1958}
1959
1961 const MachineRegisterInfo &MRI,
1962 unsigned Depth) {
1963 return ::isGuaranteedNotToBeUndefOrPoison(Reg, MRI, Depth,
1965}
1966
1968 const MachineRegisterInfo &MRI,
1969 unsigned Depth) {
1970 return ::isGuaranteedNotToBeUndefOrPoison(Reg, MRI, Depth,
1972}
1973
1975 if (Ty.isVector())
1976 return VectorType::get(IntegerType::get(C, Ty.getScalarSizeInBits()),
1977 Ty.getElementCount());
1978 return IntegerType::get(C, Ty.getSizeInBits());
1979}
1980
1982 switch (MI.getOpcode()) {
1983 default:
1984 return false;
1985 case TargetOpcode::G_ASSERT_ALIGN:
1986 case TargetOpcode::G_ASSERT_SEXT:
1987 case TargetOpcode::G_ASSERT_ZEXT:
1988 return true;
1989 }
1990}
1991
1993 assert(Kind == GIConstantKind::Scalar && "Expected scalar constant");
1994
1995 return Value;
1996}
1997
1998std::optional<GIConstant>
2001
2003 std::optional<ValueAndVReg> MayBeConstant =
2004 getIConstantVRegValWithLookThrough(Splat->getScalarReg(), MRI);
2005 if (!MayBeConstant)
2006 return std::nullopt;
2007 return GIConstant(MayBeConstant->Value, GIConstantKind::ScalableVector);
2008 }
2009
2011 SmallVector<APInt> Values;
2012 unsigned NumSources = Build->getNumSources();
2013 for (unsigned I = 0; I < NumSources; ++I) {
2014 Register SrcReg = Build->getSourceReg(I);
2015 std::optional<ValueAndVReg> MayBeConstant =
2017 if (!MayBeConstant)
2018 return std::nullopt;
2019 Values.push_back(MayBeConstant->Value);
2020 }
2021 return GIConstant(Values);
2022 }
2023
2024 std::optional<ValueAndVReg> MayBeConstant =
2026 if (!MayBeConstant)
2027 return std::nullopt;
2028
2029 return GIConstant(MayBeConstant->Value, GIConstantKind::Scalar);
2030}
2031
2033 assert(Kind == GFConstantKind::Scalar && "Expected scalar constant");
2034
2035 return Values[0];
2036}
2037
2038std::optional<GFConstant>
2041
2043 std::optional<FPValueAndVReg> MayBeConstant =
2044 getFConstantVRegValWithLookThrough(Splat->getScalarReg(), MRI);
2045 if (!MayBeConstant)
2046 return std::nullopt;
2047 return GFConstant(MayBeConstant->Value, GFConstantKind::ScalableVector);
2048 }
2049
2051 SmallVector<APFloat> Values;
2052 unsigned NumSources = Build->getNumSources();
2053 for (unsigned I = 0; I < NumSources; ++I) {
2054 Register SrcReg = Build->getSourceReg(I);
2055 std::optional<FPValueAndVReg> MayBeConstant =
2057 if (!MayBeConstant)
2058 return std::nullopt;
2059 Values.push_back(MayBeConstant->Value);
2060 }
2061 return GFConstant(Values);
2062 }
2063
2064 std::optional<FPValueAndVReg> MayBeConstant =
2066 if (!MayBeConstant)
2067 return std::nullopt;
2068
2069 return GFConstant(MayBeConstant->Value, GFConstantKind::Scalar);
2070}
2071
2072// Returns a list of types to use for memory op lowering in MemOps. A partial
2073// port of findOptimalMemOpLowering in TargetLowering.
2074static bool findGISelOptimalMemOpLowering(std::vector<LLT> &MemOps,
2075 unsigned Limit, const MemOp &Op,
2076 unsigned DstAS, unsigned SrcAS,
2077 const AttributeList &FuncAttributes,
2078 const TargetLowering &TLI) {
2079 if (Op.isMemcpyOrMemmoveWithFixedDstAlign() &&
2080 Op.getSrcAlign() < Op.getDstAlign())
2081 return false;
2082
2083 LLT Ty = TLI.getOptimalMemOpLLT(Op, FuncAttributes);
2084
2085 if (Ty == LLT()) {
2086 // Use the largest scalar type whose alignment constraints are satisfied.
2087 // We only need to check DstAlign here as SrcAlign is always greater or
2088 // equal to DstAlign (or zero).
2089 Ty = LLT::integer(64);
2090 if (Op.isFixedDstAlign())
2091 while (Op.getDstAlign() < Ty.getSizeInBytes() &&
2092 !TLI.allowsMisalignedMemoryAccesses(Ty, DstAS, Op.getDstAlign()))
2093 Ty = LLT::integer(Ty.getSizeInBytes());
2094 assert(Ty.getSizeInBits() > 0 && "Could not find valid type");
2095 // FIXME: check for the largest legal type we can load/store to.
2096 }
2097
2098 unsigned NumMemOps = 0;
2099 uint64_t Size = Op.size();
2100 while (Size) {
2101 unsigned TySize = Ty.getSizeInBytes();
2102 while (TySize > Size) {
2103 // For now, only use non-vector load / store's for the left-over pieces.
2104 LLT NewTy = Ty;
2105 // FIXME: check for mem op safety and legality of the types. Not all of
2106 // SDAGisms map cleanly to GISel concepts.
2107 if (NewTy.isVector())
2108 NewTy =
2109 NewTy.getSizeInBits() > 64 ? LLT::integer(64) : LLT::integer(32);
2110 NewTy = LLT::integer(llvm::bit_floor(NewTy.getSizeInBits() - 1));
2111 unsigned NewTySize = NewTy.getSizeInBytes();
2112 assert(NewTySize > 0 && "Could not find appropriate type");
2113
2114 // If the new LLT cannot cover all of the remaining bits, then consider
2115 // issuing a (or a pair of) unaligned and overlapping load / store.
2116 unsigned Fast;
2117 // Need to get a VT equivalent for allowMisalignedMemoryAccesses().
2118 MVT VT = getMVTForLLT(Ty);
2119 if (NumMemOps && !Op.isVolatile() && NewTySize < Size &&
2121 VT, DstAS, Op.isFixedDstAlign() ? Op.getDstAlign() : Align(1),
2123 Fast)
2124 TySize = Size;
2125 else {
2126 Ty = NewTy;
2127 TySize = NewTySize;
2128 }
2129 }
2130
2131 if (++NumMemOps > Limit)
2132 return false;
2133
2134 MemOps.push_back(Ty);
2135 Size -= TySize;
2136 }
2137
2138 return true;
2139}
2140
2142 const MachineRegisterInfo &MRI, unsigned MaxLen,
2143 Register &Dst, Register &Src,
2144 uint64_t &KnownLen, Align &Alignment,
2145 bool &DstAlignCanChange,
2146 std::vector<LLT> &MemOps) {
2147 const unsigned Opc = MI.getOpcode();
2148 assert((Opc == TargetOpcode::G_MEMCPY ||
2149 Opc == TargetOpcode::G_MEMCPY_INLINE ||
2150 Opc == TargetOpcode::G_MEMMOVE || Opc == TargetOpcode::G_MEMSET ||
2151 Opc == TargetOpcode::G_MEMSET_INLINE) &&
2152 "Expected memcpy like instruction");
2153
2154 auto MMOIt = MI.memoperands_begin();
2155 const MachineMemOperand *MemOp = *MMOIt;
2156
2157 Align DstAlign = MemOp->getBaseAlign();
2158 Align SrcAlign;
2159 Alignment = DstAlign;
2160 Register Len;
2161 std::tie(Dst, Src, Len) = MI.getFirst3Regs();
2162
2163 if (Opc != TargetOpcode::G_MEMSET && Opc != TargetOpcode::G_MEMSET_INLINE) {
2164 assert(MMOIt != MI.memoperands_end() && "Expected a second MMO on MI");
2165 MemOp = *(++MMOIt);
2166 SrcAlign = MemOp->getBaseAlign();
2167 Alignment = std::min(DstAlign, SrcAlign);
2168 }
2169
2170 // See if this is a constant length copy.
2171 auto LenVRegAndVal = getIConstantVRegValWithLookThrough(Len, MRI);
2172 if (!LenVRegAndVal) {
2173 // FIXME: support dynamically sized G_MEMCPY_INLINE and G_MEMSET_INLINE
2174 assert(Opc != TargetOpcode::G_MEMCPY_INLINE &&
2175 Opc != TargetOpcode::G_MEMSET_INLINE &&
2176 "inline memcpy and memset with dynamic size are not yet supported");
2177 return false;
2178 }
2179
2180 KnownLen = LenVRegAndVal->Value.getZExtValue();
2181 DstAlignCanChange = false;
2182
2183 if (KnownLen == 0)
2184 return true;
2185
2186 if (Opc != TargetOpcode::G_MEMCPY_INLINE &&
2187 Opc != TargetOpcode::G_MEMSET_INLINE && MaxLen && KnownLen > MaxLen)
2188 return false;
2189
2190 bool IsVolatile = MemOp->isVolatile();
2191 const MachineFunction &MF = *MI.getParent()->getParent();
2192 const auto &TLI = *MF.getSubtarget().getTargetLowering();
2193 // On Darwin, -Os means optimize for size without hurting performance, so
2194 // only really optimize for size when -Oz (MinSize) is used.
2195 bool OptSize = MF.getTarget().getTargetTriple().isOSDarwin()
2196 ? MF.getFunction().hasMinSize()
2197 : MF.getFunction().hasOptSize();
2198
2199 const MachineFrameInfo &MFI = MF.getFrameInfo();
2200 MachineInstr *FIDef = getOpcodeDef(TargetOpcode::G_FRAME_INDEX, Dst, MRI);
2201 if (FIDef && !MFI.isFixedObjectIndex(FIDef->getOperand(1).getIndex()))
2202 DstAlignCanChange = true;
2203
2204 const auto &DstMMO = **MI.memoperands_begin();
2205 MachinePointerInfo DstPtrInfo = DstMMO.getPointerInfo();
2206
2207 switch (Opc) {
2208 case TargetOpcode::G_MEMCPY_INLINE:
2209 case TargetOpcode::G_MEMCPY: {
2210 const auto &SrcMMO = **std::next(MI.memoperands_begin());
2211 MachinePointerInfo SrcPtrInfo = SrcMMO.getPointerInfo();
2212 uint64_t Limit = Opc == TargetOpcode::G_MEMCPY_INLINE
2213 ? std::numeric_limits<uint64_t>::max()
2214 : TLI.getMaxStoresPerMemcpy(OptSize);
2216 MemOps, Limit,
2217 MemOp::Copy(KnownLen, DstAlignCanChange, std::min(DstAlign, SrcAlign),
2218 SrcAlign, IsVolatile),
2219 DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
2220 MF.getFunction().getAttributes(), TLI);
2221 }
2222 case TargetOpcode::G_MEMMOVE: {
2223 const auto &SrcMMO = **std::next(MI.memoperands_begin());
2224 MachinePointerInfo SrcPtrInfo = SrcMMO.getPointerInfo();
2225 unsigned Limit = TLI.getMaxStoresPerMemmove(OptSize);
2227 MemOps, Limit,
2228 MemOp::Move(KnownLen, DstAlignCanChange, std::min(DstAlign, SrcAlign),
2229 SrcAlign, IsVolatile),
2230 DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
2231 MF.getFunction().getAttributes(), TLI);
2232 }
2233 case TargetOpcode::G_MEMSET:
2234 case TargetOpcode::G_MEMSET_INLINE: {
2235 unsigned Limit = Opc == TargetOpcode::G_MEMSET_INLINE
2236 ? std::numeric_limits<unsigned>::max()
2237 : TLI.getMaxStoresPerMemset(OptSize);
2238 auto ValVRegAndVal = getIConstantVRegValWithLookThrough(Src, MRI);
2239 bool IsZeroVal = ValVRegAndVal && ValVRegAndVal->Value == 0;
2241 MemOps, Limit,
2242 MemOp::Set(KnownLen, DstAlignCanChange, DstAlign,
2243 /*IsZeroMemset=*/IsZeroVal,
2244 /*IsVolatile=*/IsVolatile),
2245 DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes(), TLI);
2246 }
2247 default:
2248 llvm_unreachable("Unexpected memcpy-family opcode");
2249 }
2250}
MachineInstrBuilder MachineInstrBuilder & DefMI
unsigned RegSize
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned Imm
unsigned uint64_t
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static bool findGISelOptimalMemOpLowering(std::vector< LLT > &MemOps, unsigned Limit, const MemOp &Op, unsigned DstAS, unsigned SrcAS, const AttributeList &FuncAttributes, const TargetLowering &TLI)
Definition Utils.cpp:2074
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:1753
static bool isBuildVectorOp(unsigned Opcode)
Definition Utils.cpp:1304
static bool isConstantScalar(const MachineInstr &MI, const MachineRegisterInfo &MRI, bool AllowFP=true, bool AllowOpaqueConstants=true)
Definition Utils.cpp:1461
static GBuildVector * getBuildVectorLikeDef(Register Reg, const MachineRegisterInfo &MRI)
Definition Utils.cpp:788
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This contains common code to allow clients to notify changes to machine instr.
Provides analysis for querying information about KnownBits during GISel passes.
Declares convenience wrapper classes for interpreting MachineInstr instances as specific generic oper...
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
Tracks DebugLocs between checkpoints and verifies that they are transferred.
Implement a low-level type suitable for MachineInstr level instruction selection.
#define I(x, y, z)
Definition MD5.cpp:57
Contains matchers for matching SSA Machine Instructions.
This file declares the MachineIRBuilder class.
===- MachineOptimizationRemarkEmitter.h - Opt Diagnostics -*- C++ -*-—===//
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
uint64_t IntrinsicInst * II
const char * Msg
#define LLVM_DEBUG(...)
Definition Debug.h:119
This file describes how to lower LLVM code to machine code.
Target-Independent Code Generator Pass Configuration Options pass.
This file contains the UndefPoisonKind enum and helper functions.
static const char PassName[]
Class recording the (high level) value of a variable.
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:361
opStatus divide(const APFloat &RHS, roundingMode RM)
Definition APFloat.h:1312
void copySign(const APFloat &RHS)
Definition APFloat.h:1406
opStatus subtract(const APFloat &RHS, roundingMode RM)
Definition APFloat.h:1294
opStatus add(const APFloat &RHS, roundingMode RM)
Definition APFloat.h:1285
opStatus convertFromAPInt(const APInt &Input, bool IsSigned, roundingMode RM)
Definition APFloat.h:1451
opStatus multiply(const APFloat &RHS, roundingMode RM)
Definition APFloat.h:1303
APInt bitcastToAPInt() const
Definition APFloat.h:1475
opStatus mod(const APFloat &RHS)
Definition APFloat.h:1330
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition APInt.cpp:1602
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:230
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1057
LLVM_ABI APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
Definition APInt.cpp:1078
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
Definition APInt.cpp:970
LLVM_ABI APInt urem(const APInt &RHS) const
Unsigned remainder operation.
Definition APInt.cpp:1695
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
LLVM_ABI APInt sdiv(const APInt &RHS) const
Signed division function for APInt.
Definition APInt.cpp:1673
LLVM_ABI APInt sextOrTrunc(unsigned width) const
Sign extend or truncate to width.
Definition APInt.cpp:1086
static bool isSameValue(const APInt &I1, const APInt &I2, bool SignedCompare=false)
Determine if two APInts have the same value, after zero-extending or sign-extending (if SignedCompare...
Definition APInt.h:550
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition APInt.h:829
LLVM_ABI APInt srem(const APInt &RHS) const
Function for signed remainder operation.
Definition APInt.cpp:1774
LLVM_ABI APInt sext(unsigned width) const
Sign extend to a new width.
Definition APInt.cpp:1030
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:235
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition APInt.h:853
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:126
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:305
static constexpr ElementCount get(ScalarTy MinVal, bool Scalable)
Definition TypeSize.h:311
bool hasOptSize() const
Optimize this function for size (-Os) or minimum size (-Oz).
Definition Function.h:699
bool hasMinSize() const
Optimize this function for minimum size (-Oz).
Definition Function.h:696
AttributeList getAttributes() const
Return the attribute list for this Function.
Definition Function.h:329
Represents a G_BUILD_VECTOR.
Represents an extract vector element.
static LLVM_ABI std::optional< GFConstant > getConstant(Register Const, const MachineRegisterInfo &MRI)
Definition Utils.cpp:2039
GFConstant(ArrayRef< APFloat > Values)
Definition Utils.h:661
LLVM_ABI APFloat getScalarValue() const
Returns the value, if this constant is a scalar.
Definition Utils.cpp:2032
LLVM_ABI APInt getScalarValue() const
Returns the value, if this constant is a scalar.
Definition Utils.cpp:1992
static LLVM_ABI std::optional< GIConstant > getConstant(Register Const, const MachineRegisterInfo &MRI)
Definition Utils.cpp:1999
GIConstant(ArrayRef< APInt > Values)
Definition Utils.h:620
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:338
constexpr bool isScalableVector() const
Returns true if the LLT is a scalable vector.
constexpr unsigned getScalarSizeInBits() const
static constexpr LLT vector(ElementCount EC, unsigned ScalarSizeInBits)
Get a low-level vector of some number of elements and element width.
LLT getScalarType() const
static constexpr LLT scalar(unsigned SizeInBits)
Get a low-level scalar or aggregate "bag of bits".
constexpr bool isValid() const
constexpr uint16_t getNumElements() const
Returns the number of elements in a vector LLT.
constexpr bool isVector() const
constexpr bool isScalable() const
Returns true if the LLT is a scalable vector.
constexpr TypeSize getSizeInBits() const
Returns the total size of the type. Must only be called on sized types.
constexpr ElementCount getElementCount() const
static constexpr LLT fixed_vector(unsigned NumElements, unsigned ScalarSizeInBits)
Get a low-level fixed-width vector of some number of elements and element width.
constexpr bool isFixedVector() const
Returns true if the LLT is a fixed vector.
static LLT integer(unsigned SizeInBits)
constexpr TypeSize getSizeInBytes() const
Returns the total size of the type in bytes, i.e.
LLT getElementType() const
Returns the vector's element type. Only valid for vector types.
static constexpr LLT scalarOrVector(ElementCount EC, LLT ScalarTy)
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:71
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 LLVM_READONLY 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:68
Holds all the information related to register banks.
static const TargetRegisterClass * constrainGenericRegister(Register Reg, const TargetRegisterClass &RC, MachineRegisterInfo &MRI)
Constrain the (possibly generic) virtual register Reg to RC.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition Register.h:83
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
TargetInstrInfo - Interface to description of machine instruction set.
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:724
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
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 ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:165
An efficient, type-erasing, non-owning reference to a callable.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
const APInt & smin(const APInt &A, const APInt &B)
Determine the smaller of two APInts considered to be signed.
Definition APInt.h:2274
const APInt & smax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be signed.
Definition APInt.h:2279
const APInt & umin(const APInt &A, const APInt &B)
Determine the smaller of two APInts considered to be unsigned.
Definition APInt.h:2284
const APInt & umax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be unsigned.
Definition APInt.h:2289
ImplicitDefMatch m_GImplicitDef()
bool mi_match(Reg R, const MachineRegisterInfo &MRI, Pattern &&P)
DiagnosticInfoMIROptimization::MachineArgument MNV
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI Register getFunctionLiveInPhysReg(MachineFunction &MF, const TargetInstrInfo &TII, MCRegister PhysReg, const TargetRegisterClass &RC, const DebugLoc &DL, LLT RegTy=LLT())
Return a virtual register corresponding to the incoming argument register PhysReg.
Definition Utils.cpp:848
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
LLVM_ABI std::optional< SmallVector< APInt > > ConstantFoldICmp(unsigned Pred, const Register Op1, const Register Op2, unsigned DstScalarSizeInBits, unsigned ExtOp, const MachineRegisterInfo &MRI)
Definition Utils.cpp:983
LLVM_ABI std::optional< APInt > isConstantOrConstantSplatVector(Register Def, const MachineRegisterInfo &MRI)
Determines if Def defines a constant integer or a splat vector of constant integers.
Definition Utils.cpp:1518
@ Offset
Definition DWP.cpp:577
LLVM_ABI bool isBuildVectorAllZeros(const MachineInstr &MI, const MachineRegisterInfo &MRI, bool AllowUndef=false)
Return true if the specified instruction is a G_BUILD_VECTOR or G_BUILD_VECTOR_TRUNC where all of the...
Definition Utils.cpp:1434
LLVM_ABI Type * getTypeForLLT(LLT Ty, LLVMContext &C)
Get the type back from LLT.
Definition Utils.cpp:1974
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
LLVM_ABI Register constrainOperandRegClass(const MachineFunction &MF, const TargetRegisterInfo &TRI, MachineRegisterInfo &MRI, const TargetInstrInfo &TII, const RegisterBankInfo &RBI, MachineInstr &InsertPt, const TargetRegisterClass &RegClass, MachineOperand &RegMO)
Constrain the Register operand OpIdx, so that it is now constrained to the TargetRegisterClass passed...
Definition Utils.cpp: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 std::optional< APFloat > isConstantOrConstantSplatVectorFP(Register Def, const MachineRegisterInfo &MRI)
Determines if Def defines a float constant integer or a splat vector of float constant integers.
Definition Utils.cpp:1530
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:922
LLVM_ABI std::optional< APInt > getIConstantSplatVal(const Register Reg, const MachineRegisterInfo &MRI)
Definition Utils.cpp:1394
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:1558
@ Known
Known to have no common set bits.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI const llvm::fltSemantics & getFltSemanticForLLT(LLT Ty)
Get the appropriate floating point arithmetic semantic based on the bit size of the given scalar LLT.
LLVM_ABI std::optional< APFloat > ConstantFoldFPBinOp(unsigned Opcode, const Register Op1, const Register Op2, const MachineRegisterInfo &MRI)
Definition Utils.cpp:731
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:1677
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.
LLVM_ABI bool matchUnaryPredicate(const MachineRegisterInfo &MRI, Register Reg, llvm::function_ref< bool(const Constant *ConstVal)> Match, bool AllowUndefs=false)
Attempt to match a unary predicate against a scalar/splat constant or every element of a constant G_B...
Definition Utils.cpp:1573
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:881
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:1801
GISelWorkList< 4 > SmallInstListTy
Definition Utils.h:540
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:1540
LLVM_ABI MachineInstr * getDefIgnoringCopies(Register Reg, const MachineRegisterInfo &MRI)
Find the def instruction for Reg, folding away any trivial copies.
Definition Utils.cpp:497
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:1606
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:1141
LLVM_ABI bool isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL, bool OrZero=false, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Return true if the given value is known to have exactly one bit set when defined.
LLVM_ABI std::optional< int64_t > getIConstantVRegSExtVal(Register VReg, const MachineRegisterInfo &MRI)
If VReg is defined by a G_CONSTANT fits in int64_t returns it.
Definition Utils.cpp:317
LLVM_ABI std::optional< APInt > ConstantFoldBinOp(unsigned Opcode, const Register Op1, const Register Op2, const MachineRegisterInfo &MRI)
Definition Utils.cpp:662
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
LLVM_ABI const APInt & getIConstantFromReg(Register VReg, const MachineRegisterInfo &MRI)
VReg is defined by a G_CONSTANT, return the corresponding value.
Definition Utils.cpp:308
LLVM_READONLY APFloat maxnum(const APFloat &A, const APFloat &B)
Implements IEEE-754 2008 maxNum semantics.
Definition APFloat.h:1756
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:1498
constexpr unsigned MaxAnalysisRecursionDepth
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
LLVM_ABI bool canReplaceReg(Register DstReg, Register SrcReg, MachineRegisterInfo &MRI)
Check if DstReg can be replaced with SrcReg depending on the register constraints.
Definition Utils.cpp:203
LLVM_READONLY APFloat minimumnum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2019 minimumNumber semantics.
Definition APFloat.h:1787
LLVM_ABI void saveUsesAndErase(MachineInstr &MI, MachineRegisterInfo &MRI, LostDebugLocObserver *LocObserver, SmallInstListTy &DeadInstChain)
Definition Utils.cpp:1643
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:149
LLVM_ABI std::optional< ValueAndVReg > getAnyConstantVRegValWithLookThrough(Register VReg, const MachineRegisterInfo &MRI, bool LookThroughInstrs=true, bool LookThroughAnyExt=false)
If VReg is defined by a statically evaluable chain of instructions rooted on a G_CONSTANT or G_FCONST...
Definition Utils.cpp: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:1440
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:809
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:1427
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:898
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:1137
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:2141
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:1208
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:1737
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.
@ Fast
Assign the register banks as fast as possible (default).
bool isTargetSpecificOpcode(unsigned Opcode)
Check whether the given Opcode is a target-specific opcode.
DWARFExpression::Operation Op
LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Return true if this function can prove that V does not have undef bits and is never poison.
LLVM_ABI std::optional< FPValueAndVReg > getFConstantVRegValWithLookThrough(Register VReg, const MachineRegisterInfo &MRI, bool LookThroughInstrs=true)
If VReg is defined by a statically evaluable chain of instructions rooted on a G_FCONSTANT returns it...
Definition Utils.cpp:450
LLVM_ABI bool isConstFalseVal(const TargetLowering &TLI, int64_t Val, bool IsVector, bool IsFP)
Definition Utils.cpp:1619
constexpr unsigned BitWidth
LLVM_ABI bool isBuildVectorConstantSplat(const Register Reg, const MachineRegisterInfo &MRI, int64_t SplatValue, bool AllowUndef)
Return true if the specified register is defined by G_BUILD_VECTOR or G_BUILD_VECTOR_TRUNC where all ...
Definition Utils.cpp:1353
LLVM_ABI void eraseInstr(MachineInstr &MI, MachineRegisterInfo &MRI, LostDebugLocObserver *LocObserver=nullptr)
Definition Utils.cpp:1672
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:1631
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:1788
UndefPoisonKind
Enumeration to track whether we are interested in Undef, Poison, or both.
Definition UndefPoison.h:20
LLVM_ABI bool isPreISelGenericFloatingPointOpcode(unsigned Opc)
Returns whether opcode Opc is a pre-isel generic floating-point opcode, having only floating-point op...
Definition Utils.cpp:1696
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:1963
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition Alignment.h:206
LLVM_ABI SmallVector< APInt > ConstantFoldUnaryIntOp(unsigned Opcode, LLT DstTy, Register Src, const MachineRegisterInfo &MRI)
Tries to constant fold a unary integer operation (G_CTLZ, G_CTTZ, G_CTPOP and their _ZERO_POISON vari...
Definition Utils.cpp:935
LLVM_ABI std::optional< Register > getVectorSplat(const MachineInstr &MI, const MachineRegisterInfo &MRI)
Definition Utils.cpp:1446
LLVM_ABI void eraseInstrs(ArrayRef< MachineInstr * > DeadInstrs, MachineRegisterInfo &MRI, LostDebugLocObserver *LocObserver=nullptr)
Definition Utils.cpp:1657
LLVM_ABI void salvageDebugInfoForDbgValue(const MachineRegisterInfo &MRI, MachineInstr &MI, ArrayRef< MachineOperand * > DbgUsers)
Assuming the instruction MI is going to be deleted, attempt to salvage debug users of MI by writing t...
LLVM_ABI Register getSrcRegIgnoringCopies(Register Reg, const MachineRegisterInfo &MRI)
Find the source register for Reg, folding away any trivial copies.
Definition Utils.cpp: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:1229
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:1774
LLVM_READONLY APFloat maximumnum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2019 maximumNumber semantics.
Definition APFloat.h:1814
LLVM_ABI std::optional< int64_t > getIConstantSplatSExtVal(const Register Reg, const MachineRegisterInfo &MRI)
Definition Utils.cpp:1412
LLVM_ABI bool isAssertMI(const MachineInstr &MI)
Returns true if the instruction MI is one of the assert instructions.
Definition Utils.cpp:1981
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
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
LLVM_ABI Align inferAlignFromPtrInfo(MachineFunction &MF, const MachinePointerInfo &MPO)
Definition Utils.cpp:831
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
#define MORE()
Definition regcomp.c:247
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
Simple struct used to hold a Register value and the instruction which defines it.
Definition Utils.h:247
This class contains a discriminated union of information about pointers in memory operands,...
LLVM_ABI unsigned getAddrSpace() const
Return the LLVM IR address space number that this pointer points into.
int64_t Offset
Offset - This is an offset from the base Value*.
PointerUnion< const Value *, const PseudoSourceValue * > V
This is the IR pointer value for the access, or it is null if unknown.
static MemOp Set(uint64_t Size, bool DstAlignCanChange, Align DstAlign, bool IsZeroMemset, bool IsVolatile)
static MemOp Copy(uint64_t Size, bool DstAlignCanChange, Align DstAlign, Align SrcAlign, bool IsVolatile, bool MemcpyStrSrc=false)
static MemOp Move(uint64_t Size, bool DstAlignCanChange, Align DstAlign, Align SrcAlign, bool IsVolatile)
bool isVolatile() const
Simple struct used to hold a constant integer value and a virtual register.
Definition Utils.h:194