23#include "llvm/IR/IntrinsicsSPIRV.h"
26#define DEBUG_TYPE "spirv-prelegalizer"
51 cast<Constant>(cast<ConstantAsMetadata>(
52 MI.getOperand(3).getMetadata()->getOperand(0))
54 if (
auto *GV = dyn_cast<GlobalValue>(Const)) {
57 GR->
add(GV, &MF,
MI.getOperand(2).getReg());
59 RegsAlreadyAddedToDT[&
MI] = Reg;
63 if (
auto *ConstVec = dyn_cast<ConstantDataVector>(Const)) {
64 auto *BuildVec =
MRI.getVRegDef(
MI.getOperand(2).getReg());
66 BuildVec->getOpcode() == TargetOpcode::G_BUILD_VECTOR);
67 for (
unsigned i = 0; i < ConstVec->getNumElements(); ++i) {
70 Constant *ElemConst = ConstVec->getElementAsConstant(i);
73 GR->
add(ElemConst, &MF, BuildVec->getOperand(1 + i).getReg());
75 BuildVec->getOperand(1 + i).setReg(ElemReg);
78 GR->
add(Const, &MF,
MI.getOperand(2).getReg());
80 RegsAlreadyAddedToDT[&
MI] = Reg;
83 assert(
MI.getOperand(2).isReg() &&
"Reg operand is expected");
85 if (SrcMI &&
isSpvIntrinsic(*SrcMI, Intrinsic::spv_const_composite))
94 Reg = RegsAlreadyAddedToDT[
MI];
95 auto *RC =
MRI.getRegClassOrNull(
MI->getOperand(0).getReg());
96 if (!
MRI.getRegClassOrNull(Reg) && RC)
97 MRI.setRegClass(Reg, RC);
98 MRI.replaceRegWith(
MI->getOperand(0).getReg(), Reg);
99 MI->eraseFromParent();
102 MI->eraseFromParent();
108 const unsigned AssignNameOperandShift = 2;
113 unsigned NumOp =
MI.getNumExplicitDefs() + AssignNameOperandShift;
114 while (
MI.getOperand(NumOp).isReg()) {
118 MI.removeOperand(NumOp);
127 MI->eraseFromParent();
167 MI->eraseFromParent();
188 assert(
MI &&
"Machine instr is expected");
189 if (
MI->getOperand(0).isReg()) {
193 switch (
MI->getOpcode()) {
194 case TargetOpcode::G_CONSTANT: {
196 Type *Ty =
MI->getOperand(1).getCImm()->getType();
200 case TargetOpcode::G_GLOBAL_VALUE: {
205 Global->getType()->getAddressSpace());
209 case TargetOpcode::G_ZEXT: {
210 if (
MI->getOperand(1).isReg()) {
212 MRI.getVRegDef(
MI->getOperand(1).getReg())) {
215 unsigned ExpectedBW =
216 std::max(
MRI.getType(Reg).getScalarSizeInBits(), CurrentBW);
227 case TargetOpcode::G_TRUNC:
228 case TargetOpcode::G_ADDRSPACE_CAST:
229 case TargetOpcode::G_PTR_ADD:
230 case TargetOpcode::COPY: {
242 if (!
MRI.getRegClassOrNull(Reg))
243 MRI.setRegClass(Reg, &SPIRV::IDRegClass);
249static std::pair<Register, unsigned>
254 assert(SpvType &&
"VReg is expected to have SPIRV type");
256 bool IsFloat = SpvType->
getOpcode() == SPIRV::OpTypeFloat;
258 SpvType->
getOpcode() == SPIRV::OpTypeVector &&
261 IsFloat |= IsVectorFloat;
262 auto GetIdOp = IsFloat ? SPIRV::GET_fID : SPIRV::GET_ID;
263 auto DstClass = IsFloat ? &SPIRV::fIDRegClass : &SPIRV::IDRegClass;
264 if (
MRI.getType(SrcReg).isPointer()) {
267 bool IsVec =
MRI.getType(SrcReg).isVector();
272 GetIdOp = SPIRV::GET_vpID64;
273 DstClass = &SPIRV::vpID64RegClass;
275 GetIdOp = SPIRV::GET_pID64;
276 DstClass = &SPIRV::pID64RegClass;
280 GetIdOp = SPIRV::GET_vpID32;
281 DstClass = &SPIRV::vpID32RegClass;
283 GetIdOp = SPIRV::GET_pID32;
284 DstClass = &SPIRV::pID32RegClass;
287 }
else if (
MRI.getType(SrcReg).isVector()) {
290 GetIdOp = SPIRV::GET_vfID;
291 DstClass = &SPIRV::vfIDRegClass;
293 GetIdOp = SPIRV::GET_vID;
294 DstClass = &SPIRV::vIDRegClass;
297 Register IdReg =
MRI.createGenericVirtualRegister(NewT);
298 MRI.setRegClass(IdReg, DstClass);
299 return {IdReg, GetIdOp};
312 assert((Ty || SpirvTy) &&
"Either LLVM or SPIRV type is expected.");
314 (Def->getNextNode() ? Def->getNextNode()->getIterator()
315 : Def->getParent()->end()));
317 Register NewReg =
MRI.createGenericVirtualRegister(
MRI.getType(Reg));
318 if (
auto *RC =
MRI.getRegClassOrNull(Reg)) {
319 MRI.setRegClass(NewReg, RC);
321 MRI.setRegClass(NewReg, &SPIRV::IDRegClass);
322 MRI.setRegClass(Reg, &SPIRV::IDRegClass);
330 const uint32_t Flags = Def->getFlags();
336 Def->getOperand(0).setReg(NewReg);
342 assert(
MI.getNumDefs() > 0 &&
MRI.hasOneUse(
MI.getOperand(0).getReg()));
344 *(
MRI.use_instr_begin(
MI.getOperand(0).getReg()));
348 MI.getOperand(0).setReg(NewReg);
350 (
MI.getNextNode() ?
MI.getNextNode()->getIterator()
351 :
MI.getParent()->end()));
352 for (
auto &
Op :
MI.operands()) {
353 if (!
Op.isReg() ||
Op.isDef())
357 Op.setReg(IdOpInfo.first);
375 bool ReachedBegin =
false;
389 assert(Def &&
"Expecting an instruction that defines the register");
391 if (Def->getOpcode() != TargetOpcode::G_GLOBAL_VALUE)
399 assert(Def &&
"Expecting an instruction that defines the register");
401 if (Def->getOpcode() != TargetOpcode::G_GLOBAL_VALUE)
404 }
else if (
MI.getOpcode() == TargetOpcode::G_CONSTANT ||
405 MI.getOpcode() == TargetOpcode::G_FCONSTANT ||
406 MI.getOpcode() == TargetOpcode::G_BUILD_VECTOR) {
413 if (
MRI.hasOneUse(Reg)) {
420 if (
MI.getOpcode() == TargetOpcode::G_CONSTANT)
421 Ty =
MI.getOperand(1).getCImm()->getType();
422 else if (
MI.getOpcode() == TargetOpcode::G_FCONSTANT)
423 Ty =
MI.getOperand(1).getFPImm()->getType();
425 assert(
MI.getOpcode() == TargetOpcode::G_BUILD_VECTOR);
426 Type *ElemTy =
nullptr;
430 if (ElemMI->
getOpcode() == TargetOpcode::G_CONSTANT)
432 else if (ElemMI->
getOpcode() == TargetOpcode::G_FCONSTANT)
437 MI.getNumExplicitOperands() -
MI.getNumExplicitDefs();
438 Ty = VectorType::get(ElemTy, NumElts,
false);
441 }
else if (
MI.getOpcode() == TargetOpcode::G_TRUNC ||
442 MI.getOpcode() == TargetOpcode::G_ZEXT ||
443 MI.getOpcode() == TargetOpcode::G_GLOBAL_VALUE ||
444 MI.getOpcode() == TargetOpcode::COPY ||
445 MI.getOpcode() == TargetOpcode::G_ADDRSPACE_CAST) {
456 MI->eraseFromParent();
478 if (
MI.getOpcode() != SPIRV::ASSIGN_TYPE)
481 unsigned Opcode =
MRI.getVRegDef(SrcReg)->getOpcode();
485 bool IsDstPtr =
MRI.getType(DstReg).isPointer();
486 if (IsDstPtr ||
MRI.getType(DstReg).isVector())
487 MRI.setRegClass(DstReg, &SPIRV::IDRegClass);
490 if (Opcode == TargetOpcode::G_CONSTANT &&
MRI.hasOneUse(DstReg)) {
492 if (
UseMI.getOpcode() == TargetOpcode::G_ADDRSPACE_CAST)
516 for (
unsigned i = 2; i <
MI.getNumOperands(); ++i) {
524 BuildMBB->
getOpcode() == TargetOpcode::G_BLOCK_ADDR &&
535 for (
auto &SwIt : Switches) {
539 for (
unsigned i = 0; i < Ins.size(); ++i) {
540 if (Ins[i]->
getOpcode() == TargetOpcode::G_BLOCK_ADDR) {
542 Ins[i]->getOperand(1).getBlockAddress()->getBasicBlock();
543 auto It = BB2MBB.
find(CaseBB);
544 if (It == BB2MBB.
end())
546 "block in a switch statement");
548 MI.getParent()->addSuccessor(It->second);
555 for (
unsigned i =
MI.getNumOperands() - 1; i > 1; --i)
557 for (
auto &MO : NewOps)
562 Next =
MI.getNextNode();
564 if (Next && Next->getOpcode() == TargetOpcode::G_BRINDIRECT)
569 BlockAddrI->eraseFromParent();
610 GR->setCurrentFunc(MF);
626char SPIRVPreLegalizer::
ID = 0;
629 return new SPIRVPreLegalizer();
unsigned const MachineRegisterInfo * MRI
MachineInstrBuilder & UseMI
This file contains the simple types necessary to represent the attributes associated with functions a...
This file contains the declarations for the subclasses of Constant, which represent the different fla...
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static void removeImplicitFallthroughs(MachineFunction &MF, MachineIRBuilder MIB)
static bool isImplicitFallthrough(MachineBasicBlock &MBB)
bool isTypeFoldingSupported(unsigned Opcode)
static void insertBitcasts(MachineFunction &MF, SPIRVGlobalRegistry *GR, MachineIRBuilder MIB)
static void processInstrsWithTypeFolding(MachineFunction &MF, SPIRVGlobalRegistry *GR, MachineIRBuilder MIB)
static SPIRVType * propagateSPIRVType(MachineInstr *MI, SPIRVGlobalRegistry *GR, MachineRegisterInfo &MRI, MachineIRBuilder &MIB)
static void processSwitches(MachineFunction &MF, SPIRVGlobalRegistry *GR, MachineIRBuilder MIB)
static void generateAssignInstrs(MachineFunction &MF, SPIRVGlobalRegistry *GR, MachineIRBuilder MIB)
static void addConstantsToTrack(MachineFunction &MF, SPIRVGlobalRegistry *GR)
static std::pair< Register, unsigned > createNewIdReg(SPIRVType *SpvType, Register SrcReg, MachineRegisterInfo &MRI, const SPIRVGlobalRegistry &GR)
static void foldConstantsIntoIntrinsics(MachineFunction &MF)
static std::optional< unsigned > getOpcode(ArrayRef< VPValue * > Values)
Returns the opcode of Values or ~0 if they do not all agree.
LLVM Basic Block Representation.
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
This is an important base class in LLVM.
This class represents an Operation in the Expression.
iterator find(const_arg_type_t< KeyT > Val)
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
FunctionPass class - This class is used to implement most global optimizations.
static constexpr LLT scalar(unsigned SizeInBits)
Get a low-level scalar or aggregate "bag of bits".
static constexpr LLT pointer(unsigned AddressSpace, unsigned SizeInBits)
Get a low-level pointer in the given address space.
static constexpr LLT fixed_vector(unsigned NumElements, unsigned ScalarSizeInBits)
Get a low-level fixed-width vector of some number of elements and element width.
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
bool canFallThrough()
Return true if the block can implicitly transfer control to the block after it by falling off the end...
iterator_range< succ_iterator > successors()
reverse_iterator rbegin()
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
virtual bool runOnMachineFunction(MachineFunction &MF)=0
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Helper class to build MachineInstr.
MachineInstrBuilder buildBr(MachineBasicBlock &Dest)
Build and insert G_BR Dest.
void setInsertPt(MachineBasicBlock &MBB, MachineBasicBlock::iterator II)
Set the insertion point before the specified position.
MachineInstrBuilder buildInstr(unsigned Opcode)
Build and insert <empty> = Opcode <empty>.
MachineFunction & getMF()
Getter for the function we currently build.
MachineInstrBuilder buildBitcast(const DstOp &Dst, const SrcOp &Src)
Build and insert Dst = G_BITCAST Src.
MachineRegisterInfo * getMRI()
Getter for MRI.
const MachineInstrBuilder & addUse(Register RegNo, unsigned Flags=0, unsigned SubReg=0) const
Add a virtual register use operand.
const MachineInstrBuilder & setMIFlags(unsigned Flags) const
const MachineInstrBuilder & addDef(Register RegNo, unsigned Flags=0, unsigned SubReg=0) const
Add a virtual register definition operand.
MachineBasicBlock iterator that automatically skips over MIs that are inside bundles (i....
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
const MachineOperand & getOperand(unsigned i) const
MachineOperand class - Representation of each machine instruction operand.
const ConstantInt * getCImm() const
static MachineOperand CreateCImm(const ConstantInt *CI)
void setReg(Register Reg)
Change the register this operand corresponds to.
const BlockAddress * getBlockAddress() const
static MachineOperand CreateImm(int64_t Val)
bool isBlockAddress() const
isBlockAddress - Tests if this is a MO_BlockAddress operand.
Register getReg() const
getReg - Returns the register number.
const ConstantFP * getFPImm() const
static MachineOperand CreateMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0)
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
void replaceRegWith(Register FromReg, Register ToReg)
replaceRegWith - Replace all instances of FromReg with ToReg in the machine function.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
Wrapper class representing virtual and physical registers.
constexpr bool isValid() const
SPIRVType * getSPIRVTypeForVReg(Register VReg, const MachineFunction *MF=nullptr) const
void add(const Constant *C, MachineFunction *MF, Register R)
unsigned getScalarOrVectorComponentCount(Register VReg) const
unsigned getPointerSize() const
Register getSPIRVTypeID(const SPIRVType *SpirvType) const
SPIRVType * getOrCreateSPIRVType(const Type *Type, MachineIRBuilder &MIRBuilder, SPIRV::AccessQualifier::AccessQualifier AQ=SPIRV::AccessQualifier::ReadWrite, bool EmitIR=true)
void assignSPIRVTypeToVReg(SPIRVType *Type, Register VReg, MachineFunction &MF)
Register find(const MachineInstr *MI, MachineFunction *MF)
SPIRVType * getOrCreateSPIRVPointerType(SPIRVType *BaseType, MachineIRBuilder &MIRBuilder, SPIRV::StorageClass::StorageClass SClass=SPIRV::StorageClass::Function)
SPIRVType * getOrCreateSPIRVVectorType(SPIRVType *BaseType, unsigned NumElements, MachineIRBuilder &MIRBuilder)
SPIRVType * getOrCreateSPIRVIntegerType(unsigned BitWidth, MachineIRBuilder &MIRBuilder)
Type * getDeducedGlobalValueType(const GlobalValue *Global)
unsigned getScalarOrVectorBitWidth(const SPIRVType *Type) const
const SPIRVInstrInfo * getInstrInfo() const override
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
The instances of the Type class are immutable: once they are created, they are never changed.
static TypedPointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
Type * getType() const
All values are typed, get the type of this value.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
This is an optimization pass for GlobalISel generic memory operations.
FunctionPass * createSPIRVPreLegalizerPass()
Register insertAssignInstr(Register Reg, Type *Ty, SPIRVType *SpirvTy, SPIRVGlobalRegistry *GR, MachineIRBuilder &MIB, MachineRegisterInfo &MRI)
Helper external function for inserting ASSIGN_TYPE instuction between Reg and its definition,...
iterator_range< po_iterator< T > > post_order(const T &G)
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
@ Global
Append to llvm.global_dtors.
SPIRV::StorageClass::StorageClass addressSpaceToStorageClass(unsigned AddrSpace, const SPIRVSubtarget &STI)
void processInstr(MachineInstr &MI, MachineIRBuilder &MIB, MachineRegisterInfo &MRI, SPIRVGlobalRegistry *GR)
MachineInstr * getDefInstrMaybeConstant(Register &ConstReg, const MachineRegisterInfo *MRI)
Type * getMDOperandAsType(const MDNode *N, unsigned I)
void initializeSPIRVPreLegalizerPass(PassRegistry &)
bool isSpvIntrinsic(const MachineInstr &MI, Intrinsic::ID IntrinsicID)