#include "llvm/CodeGen/GlobalISel/InlineAsmLowering.h"
#include "llvm/CodeGen/GlobalISel/MachineIRBuilder.h"
#include "llvm/CodeGen/MachineOperand.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/TargetLowering.h"
#include "llvm/IR/Module.h"
#define DEBUG_TYPE "inline-asm-lowering"
using namespace llvm;
void InlineAsmLowering::anchor() {}
namespace {
class GISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
public:
SmallVector<Register, 1> Regs;
explicit GISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &Info)
: TargetLowering::AsmOperandInfo(Info) {}
};
using GISelAsmOperandInfoVector = SmallVector<GISelAsmOperandInfo, 16>;
class ExtraFlags {
unsigned Flags = 0;
public:
explicit ExtraFlags(const CallBase &CB) {
const InlineAsm *IA = cast<InlineAsm>(CB.getCalledOperand());
if (IA->hasSideEffects())
Flags |= InlineAsm::Extra_HasSideEffects;
if (IA->isAlignStack())
Flags |= InlineAsm::Extra_IsAlignStack;
if (CB.isConvergent())
Flags |= InlineAsm::Extra_IsConvergent;
Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
}
void update(const TargetLowering::AsmOperandInfo &OpInfo) {
if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
OpInfo.ConstraintType == TargetLowering::C_Other) {
if (OpInfo.Type == InlineAsm::isInput)
Flags |= InlineAsm::Extra_MayLoad;
else if (OpInfo.Type == InlineAsm::isOutput)
Flags |= InlineAsm::Extra_MayStore;
else if (OpInfo.Type == InlineAsm::isClobber)
Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
}
}
unsigned get() const { return Flags; }
};
}
static void getRegistersForValue(MachineFunction &MF,
MachineIRBuilder &MIRBuilder,
GISelAsmOperandInfo &OpInfo,
GISelAsmOperandInfo &RefOpInfo) {
const TargetLowering &TLI = *MF.getSubtarget().getTargetLowering();
const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
if (OpInfo.ConstraintType == TargetLowering::C_Memory)
return;
Register AssignedReg;
const TargetRegisterClass *RC;
std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
&TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
if (!RC)
return;
if (OpInfo.isMatchingInputConstraint())
return;
unsigned NumRegs = 1;
if (OpInfo.ConstraintVT != MVT::Other)
NumRegs =
TLI.getNumRegisters(MF.getFunction().getContext(), OpInfo.ConstraintVT);
TargetRegisterClass::iterator I = RC->begin();
MachineRegisterInfo &RegInfo = MF.getRegInfo();
if (AssignedReg) {
for (; *I != AssignedReg; ++I)
assert(I != RC->end() && "AssignedReg should be a member of provided RC");
}
for (; NumRegs; --NumRegs, ++I) {
assert(I != RC->end() && "Ran out of registers to allocate!");
Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
OpInfo.Regs.push_back(R);
}
}
static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
switch (CT) {
case TargetLowering::C_Immediate:
case TargetLowering::C_Other:
case TargetLowering::C_Unknown:
return 0;
case TargetLowering::C_Register:
return 1;
case TargetLowering::C_RegisterClass:
return 2;
case TargetLowering::C_Memory:
case TargetLowering::C_Address:
return 3;
}
llvm_unreachable("Invalid constraint type");
}
static void chooseConstraint(TargetLowering::AsmOperandInfo &OpInfo,
const TargetLowering *TLI) {
assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options");
unsigned BestIdx = 0;
TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown;
int BestGenerality = -1;
for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) {
TargetLowering::ConstraintType CType =
TLI->getConstraintType(OpInfo.Codes[i]);
if (OpInfo.isIndirect && !(CType == TargetLowering::C_Memory ||
CType == TargetLowering::C_Register ||
CType == TargetLowering::C_RegisterClass))
continue;
if (CType == TargetLowering::C_Other ||
CType == TargetLowering::C_Immediate) {
assert(OpInfo.Codes[i].size() == 1 &&
"Unhandled multi-letter 'other' constraint");
}
if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput())
continue;
int Generality = getConstraintGenerality(CType);
if (Generality > BestGenerality) {
BestType = CType;
BestIdx = i;
BestGenerality = Generality;
}
}
OpInfo.ConstraintCode = OpInfo.Codes[BestIdx];
OpInfo.ConstraintType = BestType;
}
static void computeConstraintToUse(const TargetLowering *TLI,
TargetLowering::AsmOperandInfo &OpInfo) {
assert(!OpInfo.Codes.empty() && "Must have at least one constraint");
if (OpInfo.Codes.size() == 1) {
OpInfo.ConstraintCode = OpInfo.Codes[0];
OpInfo.ConstraintType = TLI->getConstraintType(OpInfo.ConstraintCode);
} else {
chooseConstraint(OpInfo, TLI);
}
if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) {
Value *Val = OpInfo.CallOperandVal;
if (isa<BasicBlock>(Val) || isa<ConstantInt>(Val) || isa<Function>(Val))
return;
if (const char *Repl = TLI->LowerXConstraint(OpInfo.ConstraintVT)) {
OpInfo.ConstraintCode = Repl;
OpInfo.ConstraintType = TLI->getConstraintType(OpInfo.ConstraintCode);
}
}
}
static unsigned getNumOpRegs(const MachineInstr &I, unsigned OpIdx) {
unsigned Flag = I.getOperand(OpIdx).getImm();
return InlineAsm::getNumOperandRegisters(Flag);
}
static bool buildAnyextOrCopy(Register Dst, Register Src,
MachineIRBuilder &MIRBuilder) {
const TargetRegisterInfo *TRI =
MIRBuilder.getMF().getSubtarget().getRegisterInfo();
MachineRegisterInfo *MRI = MIRBuilder.getMRI();
auto SrcTy = MRI->getType(Src);
if (!SrcTy.isValid()) {
LLVM_DEBUG(dbgs() << "Source type for copy is not valid\n");
return false;
}
unsigned SrcSize = TRI->getRegSizeInBits(Src, *MRI);
unsigned DstSize = TRI->getRegSizeInBits(Dst, *MRI);
if (DstSize < SrcSize) {
LLVM_DEBUG(dbgs() << "Input can't fit in destination reg class\n");
return false;
}
if (DstSize > SrcSize) {
if (!SrcTy.isScalar()) {
LLVM_DEBUG(dbgs() << "Can't extend non-scalar input to size of"
"destination register class\n");
return false;
}
Src = MIRBuilder.buildAnyExt(LLT::scalar(DstSize), Src).getReg(0);
}
MIRBuilder.buildCopy(Dst, Src);
return true;
}
bool InlineAsmLowering::lowerInlineAsm(
MachineIRBuilder &MIRBuilder, const CallBase &Call,
std::function<ArrayRef<Register>(const Value &Val)> GetOrCreateVRegs)
const {
const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
GISelAsmOperandInfoVector ConstraintOperands;
MachineFunction &MF = MIRBuilder.getMF();
const Function &F = MF.getFunction();
const DataLayout &DL = F.getParent()->getDataLayout();
const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
MachineRegisterInfo *MRI = MIRBuilder.getMRI();
TargetLowering::AsmOperandInfoVector TargetConstraints =
TLI->ParseConstraints(DL, TRI, Call);
ExtraFlags ExtraInfo(Call);
unsigned ArgNo = 0; unsigned ResNo = 0; for (auto &T : TargetConstraints) {
ConstraintOperands.push_back(GISelAsmOperandInfo(T));
GISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
if (OpInfo.hasArg()) {
OpInfo.CallOperandVal = const_cast<Value *>(Call.getArgOperand(ArgNo));
if (isa<BasicBlock>(OpInfo.CallOperandVal)) {
LLVM_DEBUG(dbgs() << "Basic block input operands not supported yet\n");
return false;
}
Type *OpTy = OpInfo.CallOperandVal->getType();
if (OpInfo.isIndirect) {
OpTy = Call.getParamElementType(ArgNo);
assert(OpTy && "Indirect operand must have elementtype attribute");
}
if (!OpTy->isSingleValueType()) {
LLVM_DEBUG(
dbgs() << "Aggregate input operands are not supported yet\n");
return false;
}
OpInfo.ConstraintVT =
TLI->getAsmOperandValueType(DL, OpTy, true).getSimpleVT();
++ArgNo;
} else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
if (StructType *STy = dyn_cast<StructType>(Call.getType())) {
OpInfo.ConstraintVT =
TLI->getSimpleValueType(DL, STy->getElementType(ResNo));
} else {
assert(ResNo == 0 && "Asm only has one result!");
OpInfo.ConstraintVT =
TLI->getAsmOperandValueType(DL, Call.getType()).getSimpleVT();
}
++ResNo;
} else {
assert(OpInfo.Type != InlineAsm::isLabel &&
"GlobalISel currently doesn't support callbr");
OpInfo.ConstraintVT = MVT::Other;
}
if (OpInfo.ConstraintVT == MVT::i64x8)
return false;
computeConstraintToUse(TLI, OpInfo);
ExtraInfo.update(OpInfo);
}
auto Inst = MIRBuilder.buildInstrNoInsert(TargetOpcode::INLINEASM)
.addExternalSymbol(IA->getAsmString().c_str())
.addImm(ExtraInfo.get());
unsigned StartIdx = Inst->getNumOperands();
GISelAsmOperandInfoVector OutputOperands;
for (auto &OpInfo : ConstraintOperands) {
GISelAsmOperandInfo &RefOpInfo =
OpInfo.isMatchingInputConstraint()
? ConstraintOperands[OpInfo.getMatchedOperand()]
: OpInfo;
getRegistersForValue(MF, MIRBuilder, OpInfo, RefOpInfo);
switch (OpInfo.Type) {
case InlineAsm::isOutput:
if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
unsigned ConstraintID =
TLI->getInlineAsmMemConstraint(OpInfo.ConstraintCode);
assert(ConstraintID != InlineAsm::Constraint_Unknown &&
"Failed to convert memory constraint code to constraint id.");
unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
Inst.addImm(OpFlags);
ArrayRef<Register> SourceRegs =
GetOrCreateVRegs(*OpInfo.CallOperandVal);
assert(
SourceRegs.size() == 1 &&
"Expected the memory output to fit into a single virtual register");
Inst.addReg(SourceRegs[0]);
} else {
assert(OpInfo.ConstraintType == TargetLowering::C_Register ||
OpInfo.ConstraintType == TargetLowering::C_RegisterClass);
if (OpInfo.Regs.empty()) {
LLVM_DEBUG(dbgs()
<< "Couldn't allocate output register for constraint\n");
return false;
}
unsigned Flag = InlineAsm::getFlagWord(
OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
: InlineAsm::Kind_RegDef,
OpInfo.Regs.size());
if (OpInfo.Regs.front().isVirtual()) {
const TargetRegisterClass *RC = MRI->getRegClass(OpInfo.Regs.front());
Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
}
Inst.addImm(Flag);
for (Register Reg : OpInfo.Regs) {
Inst.addReg(Reg,
RegState::Define | getImplRegState(Reg.isPhysical()) |
(OpInfo.isEarlyClobber ? RegState::EarlyClobber : 0));
}
OutputOperands.push_back(OpInfo);
}
break;
case InlineAsm::isInput:
case InlineAsm::isLabel: {
if (OpInfo.isMatchingInputConstraint()) {
unsigned DefIdx = OpInfo.getMatchedOperand();
unsigned InstFlagIdx = StartIdx;
for (unsigned i = 0; i < DefIdx; ++i)
InstFlagIdx += getNumOpRegs(*Inst, InstFlagIdx) + 1;
assert(getNumOpRegs(*Inst, InstFlagIdx) == 1 && "Wrong flag");
unsigned MatchedOperandFlag = Inst->getOperand(InstFlagIdx).getImm();
if (InlineAsm::isMemKind(MatchedOperandFlag)) {
LLVM_DEBUG(dbgs() << "Matching input constraint to mem operand not "
"supported. This should be target specific.\n");
return false;
}
if (!InlineAsm::isRegDefKind(MatchedOperandFlag) &&
!InlineAsm::isRegDefEarlyClobberKind(MatchedOperandFlag)) {
LLVM_DEBUG(dbgs() << "Unknown matching constraint\n");
return false;
}
unsigned DefRegIdx = InstFlagIdx + 1;
Register Def = Inst->getOperand(DefRegIdx).getReg();
ArrayRef<Register> SrcRegs = GetOrCreateVRegs(*OpInfo.CallOperandVal);
assert(SrcRegs.size() == 1 && "Single register is expected here");
Register In = SrcRegs[0];
if (Def.isVirtual()) {
In = MRI->createVirtualRegister(MRI->getRegClass(Def));
if (!buildAnyextOrCopy(In, SrcRegs[0], MIRBuilder))
return false;
}
unsigned UseFlag = InlineAsm::getFlagWord(InlineAsm::Kind_RegUse, 1);
unsigned Flag = InlineAsm::getFlagWordForMatchingOp(UseFlag, DefIdx);
Inst.addImm(Flag);
Inst.addReg(In);
Inst->tieOperands(DefRegIdx, Inst->getNumOperands() - 1);
break;
}
if (OpInfo.ConstraintType == TargetLowering::C_Other &&
OpInfo.isIndirect) {
LLVM_DEBUG(dbgs() << "Indirect input operands with unknown constraint "
"not supported yet\n");
return false;
}
if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
OpInfo.ConstraintType == TargetLowering::C_Other) {
std::vector<MachineOperand> Ops;
if (!lowerAsmOperandForConstraint(OpInfo.CallOperandVal,
OpInfo.ConstraintCode, Ops,
MIRBuilder)) {
LLVM_DEBUG(dbgs() << "Don't support constraint: "
<< OpInfo.ConstraintCode << " yet\n");
return false;
}
assert(Ops.size() > 0 &&
"Expected constraint to be lowered to at least one operand");
unsigned OpFlags =
InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
Inst.addImm(OpFlags);
Inst.add(Ops);
break;
}
if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
if (!OpInfo.isIndirect) {
LLVM_DEBUG(dbgs()
<< "Cannot indirectify memory input operands yet\n");
return false;
}
assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
unsigned ConstraintID =
TLI->getInlineAsmMemConstraint(OpInfo.ConstraintCode);
unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
Inst.addImm(OpFlags);
ArrayRef<Register> SourceRegs =
GetOrCreateVRegs(*OpInfo.CallOperandVal);
assert(
SourceRegs.size() == 1 &&
"Expected the memory input to fit into a single virtual register");
Inst.addReg(SourceRegs[0]);
break;
}
assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
OpInfo.ConstraintType == TargetLowering::C_Register) &&
"Unknown constraint type!");
if (OpInfo.isIndirect) {
LLVM_DEBUG(dbgs() << "Can't handle indirect register inputs yet "
"for constraint '"
<< OpInfo.ConstraintCode << "'\n");
return false;
}
if (OpInfo.Regs.empty()) {
LLVM_DEBUG(
dbgs()
<< "Couldn't allocate input register for register constraint\n");
return false;
}
unsigned NumRegs = OpInfo.Regs.size();
ArrayRef<Register> SourceRegs = GetOrCreateVRegs(*OpInfo.CallOperandVal);
assert(NumRegs == SourceRegs.size() &&
"Expected the number of input registers to match the number of "
"source registers");
if (NumRegs > 1) {
LLVM_DEBUG(dbgs() << "Input operands with multiple input registers are "
"not supported yet\n");
return false;
}
unsigned Flag = InlineAsm::getFlagWord(InlineAsm::Kind_RegUse, NumRegs);
if (OpInfo.Regs.front().isVirtual()) {
const TargetRegisterClass *RC = MRI->getRegClass(OpInfo.Regs.front());
Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
}
Inst.addImm(Flag);
if (!buildAnyextOrCopy(OpInfo.Regs[0], SourceRegs[0], MIRBuilder))
return false;
Inst.addReg(OpInfo.Regs[0]);
break;
}
case InlineAsm::isClobber: {
unsigned NumRegs = OpInfo.Regs.size();
if (NumRegs > 0) {
unsigned Flag =
InlineAsm::getFlagWord(InlineAsm::Kind_Clobber, NumRegs);
Inst.addImm(Flag);
for (Register Reg : OpInfo.Regs) {
Inst.addReg(Reg, RegState::Define | RegState::EarlyClobber |
getImplRegState(Reg.isPhysical()));
}
}
break;
}
}
}
if (const MDNode *SrcLoc = Call.getMetadata("srcloc"))
Inst.addMetadata(SrcLoc);
MIRBuilder.insertInstr(Inst);
ArrayRef<Register> ResRegs = GetOrCreateVRegs(Call);
if (ResRegs.size() != OutputOperands.size()) {
LLVM_DEBUG(dbgs() << "Expected the number of output registers to match the "
"number of destination registers\n");
return false;
}
for (unsigned int i = 0, e = ResRegs.size(); i < e; i++) {
GISelAsmOperandInfo &OpInfo = OutputOperands[i];
if (OpInfo.Regs.empty())
continue;
switch (OpInfo.ConstraintType) {
case TargetLowering::C_Register:
case TargetLowering::C_RegisterClass: {
if (OpInfo.Regs.size() > 1) {
LLVM_DEBUG(dbgs() << "Output operands with multiple defining "
"registers are not supported yet\n");
return false;
}
Register SrcReg = OpInfo.Regs[0];
unsigned SrcSize = TRI->getRegSizeInBits(SrcReg, *MRI);
LLT ResTy = MRI->getType(ResRegs[i]);
if (ResTy.isScalar() && ResTy.getSizeInBits() < SrcSize) {
Register Tmp1Reg =
MRI->createGenericVirtualRegister(LLT::scalar(SrcSize));
MIRBuilder.buildCopy(Tmp1Reg, SrcReg);
MIRBuilder.buildTrunc(ResRegs[i], Tmp1Reg);
} else if (ResTy.getSizeInBits() == SrcSize) {
MIRBuilder.buildCopy(ResRegs[i], SrcReg);
} else {
LLVM_DEBUG(dbgs() << "Unhandled output operand with "
"mismatched register size\n");
return false;
}
break;
}
case TargetLowering::C_Immediate:
case TargetLowering::C_Other:
LLVM_DEBUG(
dbgs() << "Cannot lower target specific output constraints yet\n");
return false;
case TargetLowering::C_Memory:
break; case TargetLowering::C_Address:
break; case TargetLowering::C_Unknown:
LLVM_DEBUG(dbgs() << "Unexpected unknown constraint\n");
return false;
}
}
return true;
}
bool InlineAsmLowering::lowerAsmOperandForConstraint(
Value *Val, StringRef Constraint, std::vector<MachineOperand> &Ops,
MachineIRBuilder &MIRBuilder) const {
if (Constraint.size() > 1)
return false;
char ConstraintLetter = Constraint[0];
switch (ConstraintLetter) {
default:
return false;
case 'i': case 'n': if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
assert(CI->getBitWidth() <= 64 &&
"expected immediate to fit into 64-bits");
bool IsBool = CI->getBitWidth() == 1;
int64_t ExtVal = IsBool ? CI->getZExtValue() : CI->getSExtValue();
Ops.push_back(MachineOperand::CreateImm(ExtVal));
return true;
}
return false;
}
}