Path: blob/main/contrib/llvm-project/llvm/lib/Target/Sparc/AsmParser/SparcAsmParser.cpp
35294 views
//===-- SparcAsmParser.cpp - Parse Sparc assembly to MCInst instructions --===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include "MCTargetDesc/SparcMCExpr.h"9#include "MCTargetDesc/SparcMCTargetDesc.h"10#include "TargetInfo/SparcTargetInfo.h"11#include "llvm/ADT/STLExtras.h"12#include "llvm/ADT/SmallVector.h"13#include "llvm/ADT/StringRef.h"14#include "llvm/MC/MCAsmMacro.h"15#include "llvm/MC/MCContext.h"16#include "llvm/MC/MCExpr.h"17#include "llvm/MC/MCInst.h"18#include "llvm/MC/MCInstBuilder.h"19#include "llvm/MC/MCInstrInfo.h"20#include "llvm/MC/MCObjectFileInfo.h"21#include "llvm/MC/MCParser/MCAsmLexer.h"22#include "llvm/MC/MCParser/MCAsmParser.h"23#include "llvm/MC/MCParser/MCParsedAsmOperand.h"24#include "llvm/MC/MCParser/MCTargetAsmParser.h"25#include "llvm/MC/MCRegisterInfo.h"26#include "llvm/MC/MCStreamer.h"27#include "llvm/MC/MCSubtargetInfo.h"28#include "llvm/MC/MCSymbol.h"29#include "llvm/MC/TargetRegistry.h"30#include "llvm/Support/Casting.h"31#include "llvm/Support/ErrorHandling.h"32#include "llvm/Support/MathExtras.h"33#include "llvm/Support/SMLoc.h"34#include "llvm/Support/raw_ostream.h"35#include "llvm/TargetParser/Triple.h"36#include <algorithm>37#include <cassert>38#include <cstdint>39#include <memory>4041using namespace llvm;4243// The generated AsmMatcher SparcGenAsmMatcher uses "Sparc" as the target44// namespace. But SPARC backend uses "SP" as its namespace.45namespace llvm {46namespace Sparc {4748using namespace SP;4950} // end namespace Sparc51} // end namespace llvm5253namespace {5455class SparcOperand;5657class SparcAsmParser : public MCTargetAsmParser {58MCAsmParser &Parser;59const MCRegisterInfo &MRI;6061enum class TailRelocKind { Load_GOT, Add_TLS, Load_TLS, Call_TLS };6263/// @name Auto-generated Match Functions64/// {6566#define GET_ASSEMBLER_HEADER67#include "SparcGenAsmMatcher.inc"6869/// }7071// public interface of the MCTargetAsmParser.72bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,73OperandVector &Operands, MCStreamer &Out,74uint64_t &ErrorInfo,75bool MatchingInlineAsm) override;76bool parseRegister(MCRegister &Reg, SMLoc &StartLoc, SMLoc &EndLoc) override;77ParseStatus tryParseRegister(MCRegister &Reg, SMLoc &StartLoc,78SMLoc &EndLoc) override;79bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,80SMLoc NameLoc, OperandVector &Operands) override;81ParseStatus parseDirective(AsmToken DirectiveID) override;8283unsigned validateTargetOperandClass(MCParsedAsmOperand &Op,84unsigned Kind) override;8586// Custom parse functions for Sparc specific operands.87ParseStatus parseMEMOperand(OperandVector &Operands);8889ParseStatus parseMembarTag(OperandVector &Operands);9091ParseStatus parseASITag(OperandVector &Operands);9293ParseStatus parsePrefetchTag(OperandVector &Operands);9495template <TailRelocKind Kind>96ParseStatus parseTailRelocSym(OperandVector &Operands);9798template <unsigned N> ParseStatus parseShiftAmtImm(OperandVector &Operands);99100ParseStatus parseCallTarget(OperandVector &Operands);101102ParseStatus parseOperand(OperandVector &Operands, StringRef Name);103104ParseStatus parseSparcAsmOperand(std::unique_ptr<SparcOperand> &Operand,105bool isCall = false);106107ParseStatus parseBranchModifiers(OperandVector &Operands);108109ParseStatus parseExpression(int64_t &Val);110111// Helper function for dealing with %lo / %hi in PIC mode.112const SparcMCExpr *adjustPICRelocation(SparcMCExpr::VariantKind VK,113const MCExpr *subExpr);114115// Helper function to see if current token can start an expression.116bool isPossibleExpression(const AsmToken &Token);117118// Check if mnemonic is valid.119MatchResultTy mnemonicIsValid(StringRef Mnemonic, unsigned VariantID);120121// returns true if Tok is matched to a register and returns register in RegNo.122MCRegister matchRegisterName(const AsmToken &Tok, unsigned &RegKind);123124bool matchSparcAsmModifiers(const MCExpr *&EVal, SMLoc &EndLoc);125126bool is64Bit() const {127return getSTI().getTargetTriple().getArch() == Triple::sparcv9;128}129130bool expandSET(MCInst &Inst, SMLoc IDLoc,131SmallVectorImpl<MCInst> &Instructions);132133bool expandSETX(MCInst &Inst, SMLoc IDLoc,134SmallVectorImpl<MCInst> &Instructions);135136SMLoc getLoc() const { return getParser().getTok().getLoc(); }137138public:139SparcAsmParser(const MCSubtargetInfo &sti, MCAsmParser &parser,140const MCInstrInfo &MII, const MCTargetOptions &Options)141: MCTargetAsmParser(Options, sti, MII), Parser(parser),142MRI(*Parser.getContext().getRegisterInfo()) {143Parser.addAliasForDirective(".half", ".2byte");144Parser.addAliasForDirective(".uahalf", ".2byte");145Parser.addAliasForDirective(".word", ".4byte");146Parser.addAliasForDirective(".uaword", ".4byte");147Parser.addAliasForDirective(".nword", is64Bit() ? ".8byte" : ".4byte");148if (is64Bit())149Parser.addAliasForDirective(".xword", ".8byte");150151// Initialize the set of available features.152setAvailableFeatures(ComputeAvailableFeatures(getSTI().getFeatureBits()));153}154};155156} // end anonymous namespace157158static const MCPhysReg IntRegs[32] = {159Sparc::G0, Sparc::G1, Sparc::G2, Sparc::G3,160Sparc::G4, Sparc::G5, Sparc::G6, Sparc::G7,161Sparc::O0, Sparc::O1, Sparc::O2, Sparc::O3,162Sparc::O4, Sparc::O5, Sparc::O6, Sparc::O7,163Sparc::L0, Sparc::L1, Sparc::L2, Sparc::L3,164Sparc::L4, Sparc::L5, Sparc::L6, Sparc::L7,165Sparc::I0, Sparc::I1, Sparc::I2, Sparc::I3,166Sparc::I4, Sparc::I5, Sparc::I6, Sparc::I7 };167168static const MCPhysReg DoubleRegs[32] = {169Sparc::D0, Sparc::D1, Sparc::D2, Sparc::D3,170Sparc::D4, Sparc::D5, Sparc::D6, Sparc::D7,171Sparc::D8, Sparc::D9, Sparc::D10, Sparc::D11,172Sparc::D12, Sparc::D13, Sparc::D14, Sparc::D15,173Sparc::D16, Sparc::D17, Sparc::D18, Sparc::D19,174Sparc::D20, Sparc::D21, Sparc::D22, Sparc::D23,175Sparc::D24, Sparc::D25, Sparc::D26, Sparc::D27,176Sparc::D28, Sparc::D29, Sparc::D30, Sparc::D31 };177178static const MCPhysReg QuadFPRegs[32] = {179Sparc::Q0, Sparc::Q1, Sparc::Q2, Sparc::Q3,180Sparc::Q4, Sparc::Q5, Sparc::Q6, Sparc::Q7,181Sparc::Q8, Sparc::Q9, Sparc::Q10, Sparc::Q11,182Sparc::Q12, Sparc::Q13, Sparc::Q14, Sparc::Q15 };183184static const MCPhysReg IntPairRegs[] = {185Sparc::G0_G1, Sparc::G2_G3, Sparc::G4_G5, Sparc::G6_G7,186Sparc::O0_O1, Sparc::O2_O3, Sparc::O4_O5, Sparc::O6_O7,187Sparc::L0_L1, Sparc::L2_L3, Sparc::L4_L5, Sparc::L6_L7,188Sparc::I0_I1, Sparc::I2_I3, Sparc::I4_I5, Sparc::I6_I7};189190static const MCPhysReg CoprocPairRegs[] = {191Sparc::C0_C1, Sparc::C2_C3, Sparc::C4_C5, Sparc::C6_C7,192Sparc::C8_C9, Sparc::C10_C11, Sparc::C12_C13, Sparc::C14_C15,193Sparc::C16_C17, Sparc::C18_C19, Sparc::C20_C21, Sparc::C22_C23,194Sparc::C24_C25, Sparc::C26_C27, Sparc::C28_C29, Sparc::C30_C31};195196namespace {197198/// SparcOperand - Instances of this class represent a parsed Sparc machine199/// instruction.200class SparcOperand : public MCParsedAsmOperand {201public:202enum RegisterKind {203rk_None,204rk_IntReg,205rk_IntPairReg,206rk_FloatReg,207rk_DoubleReg,208rk_QuadReg,209rk_CoprocReg,210rk_CoprocPairReg,211rk_Special,212};213214private:215enum KindTy {216k_Token,217k_Register,218k_Immediate,219k_MemoryReg,220k_MemoryImm,221k_ASITag,222k_PrefetchTag,223} Kind;224225SMLoc StartLoc, EndLoc;226227struct Token {228const char *Data;229unsigned Length;230};231232struct RegOp {233unsigned RegNum;234RegisterKind Kind;235};236237struct ImmOp {238const MCExpr *Val;239};240241struct MemOp {242unsigned Base;243unsigned OffsetReg;244const MCExpr *Off;245};246247union {248struct Token Tok;249struct RegOp Reg;250struct ImmOp Imm;251struct MemOp Mem;252unsigned ASI;253unsigned Prefetch;254};255256public:257SparcOperand(KindTy K) : Kind(K) {}258259bool isToken() const override { return Kind == k_Token; }260bool isReg() const override { return Kind == k_Register; }261bool isImm() const override { return Kind == k_Immediate; }262bool isMem() const override { return isMEMrr() || isMEMri(); }263bool isMEMrr() const { return Kind == k_MemoryReg; }264bool isMEMri() const { return Kind == k_MemoryImm; }265bool isMembarTag() const { return Kind == k_Immediate; }266bool isASITag() const { return Kind == k_ASITag; }267bool isPrefetchTag() const { return Kind == k_PrefetchTag; }268bool isTailRelocSym() const { return Kind == k_Immediate; }269270bool isCallTarget() const {271if (!isImm())272return false;273274if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val))275return CE->getValue() % 4 == 0;276277return true;278}279280bool isShiftAmtImm5() const {281if (!isImm())282return false;283284if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val))285return isUInt<5>(CE->getValue());286287return false;288}289290bool isShiftAmtImm6() const {291if (!isImm())292return false;293294if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val))295return isUInt<6>(CE->getValue());296297return false;298}299300bool isIntReg() const {301return (Kind == k_Register && Reg.Kind == rk_IntReg);302}303304bool isFloatReg() const {305return (Kind == k_Register && Reg.Kind == rk_FloatReg);306}307308bool isFloatOrDoubleReg() const {309return (Kind == k_Register && (Reg.Kind == rk_FloatReg310|| Reg.Kind == rk_DoubleReg));311}312313bool isCoprocReg() const {314return (Kind == k_Register && Reg.Kind == rk_CoprocReg);315}316317StringRef getToken() const {318assert(Kind == k_Token && "Invalid access!");319return StringRef(Tok.Data, Tok.Length);320}321322MCRegister getReg() const override {323assert((Kind == k_Register) && "Invalid access!");324return Reg.RegNum;325}326327const MCExpr *getImm() const {328assert((Kind == k_Immediate) && "Invalid access!");329return Imm.Val;330}331332unsigned getMemBase() const {333assert((Kind == k_MemoryReg || Kind == k_MemoryImm) && "Invalid access!");334return Mem.Base;335}336337unsigned getMemOffsetReg() const {338assert((Kind == k_MemoryReg) && "Invalid access!");339return Mem.OffsetReg;340}341342const MCExpr *getMemOff() const {343assert((Kind == k_MemoryImm) && "Invalid access!");344return Mem.Off;345}346347unsigned getASITag() const {348assert((Kind == k_ASITag) && "Invalid access!");349return ASI;350}351352unsigned getPrefetchTag() const {353assert((Kind == k_PrefetchTag) && "Invalid access!");354return Prefetch;355}356357/// getStartLoc - Get the location of the first token of this operand.358SMLoc getStartLoc() const override {359return StartLoc;360}361/// getEndLoc - Get the location of the last token of this operand.362SMLoc getEndLoc() const override {363return EndLoc;364}365366void print(raw_ostream &OS) const override {367switch (Kind) {368case k_Token: OS << "Token: " << getToken() << "\n"; break;369case k_Register: OS << "Reg: #" << getReg() << "\n"; break;370case k_Immediate: OS << "Imm: " << getImm() << "\n"; break;371case k_MemoryReg: OS << "Mem: " << getMemBase() << "+"372<< getMemOffsetReg() << "\n"; break;373case k_MemoryImm: assert(getMemOff() != nullptr);374OS << "Mem: " << getMemBase()375<< "+" << *getMemOff()376<< "\n"; break;377case k_ASITag:378OS << "ASI tag: " << getASITag() << "\n";379break;380case k_PrefetchTag:381OS << "Prefetch tag: " << getPrefetchTag() << "\n";382break;383}384}385386void addRegOperands(MCInst &Inst, unsigned N) const {387assert(N == 1 && "Invalid number of operands!");388Inst.addOperand(MCOperand::createReg(getReg()));389}390391void addImmOperands(MCInst &Inst, unsigned N) const {392assert(N == 1 && "Invalid number of operands!");393const MCExpr *Expr = getImm();394addExpr(Inst, Expr);395}396397void addShiftAmtImm5Operands(MCInst &Inst, unsigned N) const {398assert(N == 1 && "Invalid number of operands!");399addExpr(Inst, getImm());400}401void addShiftAmtImm6Operands(MCInst &Inst, unsigned N) const {402assert(N == 1 && "Invalid number of operands!");403addExpr(Inst, getImm());404}405406void addExpr(MCInst &Inst, const MCExpr *Expr) const{407// Add as immediate when possible. Null MCExpr = 0.408if (!Expr)409Inst.addOperand(MCOperand::createImm(0));410else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))411Inst.addOperand(MCOperand::createImm(CE->getValue()));412else413Inst.addOperand(MCOperand::createExpr(Expr));414}415416void addMEMrrOperands(MCInst &Inst, unsigned N) const {417assert(N == 2 && "Invalid number of operands!");418419Inst.addOperand(MCOperand::createReg(getMemBase()));420421assert(getMemOffsetReg() != 0 && "Invalid offset");422Inst.addOperand(MCOperand::createReg(getMemOffsetReg()));423}424425void addMEMriOperands(MCInst &Inst, unsigned N) const {426assert(N == 2 && "Invalid number of operands!");427428Inst.addOperand(MCOperand::createReg(getMemBase()));429430const MCExpr *Expr = getMemOff();431addExpr(Inst, Expr);432}433434void addASITagOperands(MCInst &Inst, unsigned N) const {435assert(N == 1 && "Invalid number of operands!");436Inst.addOperand(MCOperand::createImm(getASITag()));437}438439void addPrefetchTagOperands(MCInst &Inst, unsigned N) const {440assert(N == 1 && "Invalid number of operands!");441Inst.addOperand(MCOperand::createImm(getPrefetchTag()));442}443444void addMembarTagOperands(MCInst &Inst, unsigned N) const {445assert(N == 1 && "Invalid number of operands!");446const MCExpr *Expr = getImm();447addExpr(Inst, Expr);448}449450void addCallTargetOperands(MCInst &Inst, unsigned N) const {451assert(N == 1 && "Invalid number of operands!");452addExpr(Inst, getImm());453}454455void addTailRelocSymOperands(MCInst &Inst, unsigned N) const {456assert(N == 1 && "Invalid number of operands!");457addExpr(Inst, getImm());458}459460static std::unique_ptr<SparcOperand> CreateToken(StringRef Str, SMLoc S) {461auto Op = std::make_unique<SparcOperand>(k_Token);462Op->Tok.Data = Str.data();463Op->Tok.Length = Str.size();464Op->StartLoc = S;465Op->EndLoc = S;466return Op;467}468469static std::unique_ptr<SparcOperand> CreateReg(unsigned RegNum, unsigned Kind,470SMLoc S, SMLoc E) {471auto Op = std::make_unique<SparcOperand>(k_Register);472Op->Reg.RegNum = RegNum;473Op->Reg.Kind = (SparcOperand::RegisterKind)Kind;474Op->StartLoc = S;475Op->EndLoc = E;476return Op;477}478479static std::unique_ptr<SparcOperand> CreateImm(const MCExpr *Val, SMLoc S,480SMLoc E) {481auto Op = std::make_unique<SparcOperand>(k_Immediate);482Op->Imm.Val = Val;483Op->StartLoc = S;484Op->EndLoc = E;485return Op;486}487488static std::unique_ptr<SparcOperand> CreateASITag(unsigned Val, SMLoc S,489SMLoc E) {490auto Op = std::make_unique<SparcOperand>(k_ASITag);491Op->ASI = Val;492Op->StartLoc = S;493Op->EndLoc = E;494return Op;495}496497static std::unique_ptr<SparcOperand> CreatePrefetchTag(unsigned Val, SMLoc S,498SMLoc E) {499auto Op = std::make_unique<SparcOperand>(k_PrefetchTag);500Op->Prefetch = Val;501Op->StartLoc = S;502Op->EndLoc = E;503return Op;504}505506static bool MorphToIntPairReg(SparcOperand &Op) {507unsigned Reg = Op.getReg();508assert(Op.Reg.Kind == rk_IntReg);509unsigned regIdx = 32;510if (Reg >= Sparc::G0 && Reg <= Sparc::G7)511regIdx = Reg - Sparc::G0;512else if (Reg >= Sparc::O0 && Reg <= Sparc::O7)513regIdx = Reg - Sparc::O0 + 8;514else if (Reg >= Sparc::L0 && Reg <= Sparc::L7)515regIdx = Reg - Sparc::L0 + 16;516else if (Reg >= Sparc::I0 && Reg <= Sparc::I7)517regIdx = Reg - Sparc::I0 + 24;518if (regIdx % 2 || regIdx > 31)519return false;520Op.Reg.RegNum = IntPairRegs[regIdx / 2];521Op.Reg.Kind = rk_IntPairReg;522return true;523}524525static bool MorphToDoubleReg(SparcOperand &Op) {526unsigned Reg = Op.getReg();527assert(Op.Reg.Kind == rk_FloatReg);528unsigned regIdx = Reg - Sparc::F0;529if (regIdx % 2 || regIdx > 31)530return false;531Op.Reg.RegNum = DoubleRegs[regIdx / 2];532Op.Reg.Kind = rk_DoubleReg;533return true;534}535536static bool MorphToQuadReg(SparcOperand &Op) {537unsigned Reg = Op.getReg();538unsigned regIdx = 0;539switch (Op.Reg.Kind) {540default: llvm_unreachable("Unexpected register kind!");541case rk_FloatReg:542regIdx = Reg - Sparc::F0;543if (regIdx % 4 || regIdx > 31)544return false;545Reg = QuadFPRegs[regIdx / 4];546break;547case rk_DoubleReg:548regIdx = Reg - Sparc::D0;549if (regIdx % 2 || regIdx > 31)550return false;551Reg = QuadFPRegs[regIdx / 2];552break;553}554Op.Reg.RegNum = Reg;555Op.Reg.Kind = rk_QuadReg;556return true;557}558559static bool MorphToCoprocPairReg(SparcOperand &Op) {560unsigned Reg = Op.getReg();561assert(Op.Reg.Kind == rk_CoprocReg);562unsigned regIdx = 32;563if (Reg >= Sparc::C0 && Reg <= Sparc::C31)564regIdx = Reg - Sparc::C0;565if (regIdx % 2 || regIdx > 31)566return false;567Op.Reg.RegNum = CoprocPairRegs[regIdx / 2];568Op.Reg.Kind = rk_CoprocPairReg;569return true;570}571572static std::unique_ptr<SparcOperand>573MorphToMEMrr(unsigned Base, std::unique_ptr<SparcOperand> Op) {574unsigned offsetReg = Op->getReg();575Op->Kind = k_MemoryReg;576Op->Mem.Base = Base;577Op->Mem.OffsetReg = offsetReg;578Op->Mem.Off = nullptr;579return Op;580}581582static std::unique_ptr<SparcOperand>583CreateMEMr(unsigned Base, SMLoc S, SMLoc E) {584auto Op = std::make_unique<SparcOperand>(k_MemoryReg);585Op->Mem.Base = Base;586Op->Mem.OffsetReg = Sparc::G0; // always 0587Op->Mem.Off = nullptr;588Op->StartLoc = S;589Op->EndLoc = E;590return Op;591}592593static std::unique_ptr<SparcOperand>594MorphToMEMri(unsigned Base, std::unique_ptr<SparcOperand> Op) {595const MCExpr *Imm = Op->getImm();596Op->Kind = k_MemoryImm;597Op->Mem.Base = Base;598Op->Mem.OffsetReg = 0;599Op->Mem.Off = Imm;600return Op;601}602};603604} // end anonymous namespace605606#define GET_MATCHER_IMPLEMENTATION607#define GET_REGISTER_MATCHER608#define GET_MNEMONIC_SPELL_CHECKER609#include "SparcGenAsmMatcher.inc"610611// Use a custom function instead of the one from SparcGenAsmMatcher612// so we can differentiate between unavailable and unknown instructions.613SparcAsmParser::MatchResultTy614SparcAsmParser::mnemonicIsValid(StringRef Mnemonic, unsigned VariantID) {615// Process all MnemonicAliases to remap the mnemonic.616applyMnemonicAliases(Mnemonic, getAvailableFeatures(), VariantID);617618// Find the appropriate table for this asm variant.619const MatchEntry *Start, *End;620switch (VariantID) {621default:622llvm_unreachable("invalid variant!");623case 0:624Start = std::begin(MatchTable0);625End = std::end(MatchTable0);626break;627}628629// Search the table.630auto MnemonicRange = std::equal_range(Start, End, Mnemonic, LessOpcode());631632if (MnemonicRange.first == MnemonicRange.second)633return Match_MnemonicFail;634635for (const MatchEntry *it = MnemonicRange.first, *ie = MnemonicRange.second;636it != ie; ++it) {637const FeatureBitset &RequiredFeatures =638FeatureBitsets[it->RequiredFeaturesIdx];639if ((getAvailableFeatures() & RequiredFeatures) == RequiredFeatures)640return Match_Success;641}642return Match_MissingFeature;643}644645bool SparcAsmParser::expandSET(MCInst &Inst, SMLoc IDLoc,646SmallVectorImpl<MCInst> &Instructions) {647MCOperand MCRegOp = Inst.getOperand(0);648MCOperand MCValOp = Inst.getOperand(1);649assert(MCRegOp.isReg());650assert(MCValOp.isImm() || MCValOp.isExpr());651652// the imm operand can be either an expression or an immediate.653bool IsImm = Inst.getOperand(1).isImm();654int64_t RawImmValue = IsImm ? MCValOp.getImm() : 0;655656// Allow either a signed or unsigned 32-bit immediate.657if (RawImmValue < -2147483648LL || RawImmValue > 4294967295LL) {658return Error(IDLoc,659"set: argument must be between -2147483648 and 4294967295");660}661662// If the value was expressed as a large unsigned number, that's ok.663// We want to see if it "looks like" a small signed number.664int32_t ImmValue = RawImmValue;665// For 'set' you can't use 'or' with a negative operand on V9 because666// that would splat the sign bit across the upper half of the destination667// register, whereas 'set' is defined to zero the high 32 bits.668bool IsEffectivelyImm13 =669IsImm && ((is64Bit() ? 0 : -4096) <= ImmValue && ImmValue < 4096);670const MCExpr *ValExpr;671if (IsImm)672ValExpr = MCConstantExpr::create(ImmValue, getContext());673else674ValExpr = MCValOp.getExpr();675676MCOperand PrevReg = MCOperand::createReg(Sparc::G0);677678// If not just a signed imm13 value, then either we use a 'sethi' with a679// following 'or', or a 'sethi' by itself if there are no more 1 bits.680// In either case, start with the 'sethi'.681if (!IsEffectivelyImm13) {682MCInst TmpInst;683const MCExpr *Expr = adjustPICRelocation(SparcMCExpr::VK_Sparc_HI, ValExpr);684TmpInst.setLoc(IDLoc);685TmpInst.setOpcode(SP::SETHIi);686TmpInst.addOperand(MCRegOp);687TmpInst.addOperand(MCOperand::createExpr(Expr));688Instructions.push_back(TmpInst);689PrevReg = MCRegOp;690}691692// The low bits require touching in 3 cases:693// * A non-immediate value will always require both instructions.694// * An effectively imm13 value needs only an 'or' instruction.695// * Otherwise, an immediate that is not effectively imm13 requires the696// 'or' only if bits remain after clearing the 22 bits that 'sethi' set.697// If the low bits are known zeros, there's nothing to do.698// In the second case, and only in that case, must we NOT clear699// bits of the immediate value via the %lo() assembler function.700// Note also, the 'or' instruction doesn't mind a large value in the case701// where the operand to 'set' was 0xFFFFFzzz - it does exactly what you mean.702if (!IsImm || IsEffectivelyImm13 || (ImmValue & 0x3ff)) {703MCInst TmpInst;704const MCExpr *Expr;705if (IsEffectivelyImm13)706Expr = ValExpr;707else708Expr = adjustPICRelocation(SparcMCExpr::VK_Sparc_LO, ValExpr);709TmpInst.setLoc(IDLoc);710TmpInst.setOpcode(SP::ORri);711TmpInst.addOperand(MCRegOp);712TmpInst.addOperand(PrevReg);713TmpInst.addOperand(MCOperand::createExpr(Expr));714Instructions.push_back(TmpInst);715}716return false;717}718719bool SparcAsmParser::expandSETX(MCInst &Inst, SMLoc IDLoc,720SmallVectorImpl<MCInst> &Instructions) {721MCOperand MCRegOp = Inst.getOperand(0);722MCOperand MCValOp = Inst.getOperand(1);723MCOperand MCTmpOp = Inst.getOperand(2);724assert(MCRegOp.isReg() && MCTmpOp.isReg());725assert(MCValOp.isImm() || MCValOp.isExpr());726727// the imm operand can be either an expression or an immediate.728bool IsImm = MCValOp.isImm();729int64_t ImmValue = IsImm ? MCValOp.getImm() : 0;730731const MCExpr *ValExpr = IsImm ? MCConstantExpr::create(ImmValue, getContext())732: MCValOp.getExpr();733734// Very small immediates can be expressed directly as a single `or`.735if (IsImm && isInt<13>(ImmValue)) {736// or rd, val, rd737Instructions.push_back(MCInstBuilder(SP::ORri)738.addReg(MCRegOp.getReg())739.addReg(Sparc::G0)740.addExpr(ValExpr));741return false;742}743744// Otherwise, first we set the lower half of the register.745746// sethi %hi(val), rd747Instructions.push_back(748MCInstBuilder(SP::SETHIi)749.addReg(MCRegOp.getReg())750.addExpr(adjustPICRelocation(SparcMCExpr::VK_Sparc_HI, ValExpr)));751// or rd, %lo(val), rd752Instructions.push_back(753MCInstBuilder(SP::ORri)754.addReg(MCRegOp.getReg())755.addReg(MCRegOp.getReg())756.addExpr(adjustPICRelocation(SparcMCExpr::VK_Sparc_LO, ValExpr)));757758// Small positive immediates can be expressed as a single `sethi`+`or`759// combination, so we can just return here.760if (IsImm && isUInt<32>(ImmValue))761return false;762763// For bigger immediates, we need to generate the upper half, then shift and764// merge it with the lower half that has just been generated above.765766// sethi %hh(val), tmp767Instructions.push_back(768MCInstBuilder(SP::SETHIi)769.addReg(MCTmpOp.getReg())770.addExpr(adjustPICRelocation(SparcMCExpr::VK_Sparc_HH, ValExpr)));771// or tmp, %hm(val), tmp772Instructions.push_back(773MCInstBuilder(SP::ORri)774.addReg(MCTmpOp.getReg())775.addReg(MCTmpOp.getReg())776.addExpr(adjustPICRelocation(SparcMCExpr::VK_Sparc_HM, ValExpr)));777// sllx tmp, 32, tmp778Instructions.push_back(MCInstBuilder(SP::SLLXri)779.addReg(MCTmpOp.getReg())780.addReg(MCTmpOp.getReg())781.addImm(32));782// or tmp, rd, rd783Instructions.push_back(MCInstBuilder(SP::ORrr)784.addReg(MCRegOp.getReg())785.addReg(MCTmpOp.getReg())786.addReg(MCRegOp.getReg()));787788return false;789}790791bool SparcAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,792OperandVector &Operands,793MCStreamer &Out,794uint64_t &ErrorInfo,795bool MatchingInlineAsm) {796MCInst Inst;797SmallVector<MCInst, 8> Instructions;798unsigned MatchResult = MatchInstructionImpl(Operands, Inst, ErrorInfo,799MatchingInlineAsm);800switch (MatchResult) {801case Match_Success: {802switch (Inst.getOpcode()) {803default:804Inst.setLoc(IDLoc);805Instructions.push_back(Inst);806break;807case SP::SET:808if (expandSET(Inst, IDLoc, Instructions))809return true;810break;811case SP::SETX:812if (expandSETX(Inst, IDLoc, Instructions))813return true;814break;815}816817for (const MCInst &I : Instructions) {818Out.emitInstruction(I, getSTI());819}820return false;821}822823case Match_MissingFeature:824return Error(IDLoc,825"instruction requires a CPU feature not currently enabled");826827case Match_InvalidOperand: {828SMLoc ErrorLoc = IDLoc;829if (ErrorInfo != ~0ULL) {830if (ErrorInfo >= Operands.size())831return Error(IDLoc, "too few operands for instruction");832833ErrorLoc = ((SparcOperand &)*Operands[ErrorInfo]).getStartLoc();834if (ErrorLoc == SMLoc())835ErrorLoc = IDLoc;836}837838return Error(ErrorLoc, "invalid operand for instruction");839}840case Match_MnemonicFail:841return Error(IDLoc, "invalid instruction mnemonic");842}843llvm_unreachable("Implement any new match types added!");844}845846bool SparcAsmParser::parseRegister(MCRegister &Reg, SMLoc &StartLoc,847SMLoc &EndLoc) {848if (!tryParseRegister(Reg, StartLoc, EndLoc).isSuccess())849return Error(StartLoc, "invalid register name");850return false;851}852853ParseStatus SparcAsmParser::tryParseRegister(MCRegister &Reg, SMLoc &StartLoc,854SMLoc &EndLoc) {855const AsmToken &Tok = Parser.getTok();856StartLoc = Tok.getLoc();857EndLoc = Tok.getEndLoc();858Reg = Sparc::NoRegister;859if (getLexer().getKind() != AsmToken::Percent)860return ParseStatus::NoMatch;861Parser.Lex();862unsigned RegKind = SparcOperand::rk_None;863Reg = matchRegisterName(Tok, RegKind);864if (Reg) {865Parser.Lex();866return ParseStatus::Success;867}868869getLexer().UnLex(Tok);870return ParseStatus::NoMatch;871}872873bool SparcAsmParser::ParseInstruction(ParseInstructionInfo &Info,874StringRef Name, SMLoc NameLoc,875OperandVector &Operands) {876// Validate and reject unavailable mnemonics early before877// running any operand parsing.878// This is needed because some operands (mainly memory ones)879// differ between V8 and V9 ISA and so any operand parsing errors880// will cause IAS to bail out before it reaches MatchAndEmitInstruction881// (where the instruction as a whole, including the mnemonic, is validated882// once again just before emission).883// As a nice side effect this also allows us to reject unknown884// instructions and suggest replacements.885MatchResultTy MS = mnemonicIsValid(Name, 0);886switch (MS) {887case Match_Success:888break;889case Match_MissingFeature:890return Error(NameLoc,891"instruction requires a CPU feature not currently enabled");892case Match_MnemonicFail:893return Error(NameLoc,894"invalid instruction mnemonic" +895SparcMnemonicSpellCheck(Name, getAvailableFeatures(), 0));896default:897llvm_unreachable("invalid return status!");898}899900// First operand in MCInst is instruction mnemonic.901Operands.push_back(SparcOperand::CreateToken(Name, NameLoc));902903// apply mnemonic aliases, if any, so that we can parse operands correctly.904applyMnemonicAliases(Name, getAvailableFeatures(), 0);905906if (getLexer().isNot(AsmToken::EndOfStatement)) {907// Read the first operand.908if (getLexer().is(AsmToken::Comma)) {909if (!parseBranchModifiers(Operands).isSuccess()) {910SMLoc Loc = getLexer().getLoc();911return Error(Loc, "unexpected token");912}913}914if (!parseOperand(Operands, Name).isSuccess()) {915SMLoc Loc = getLexer().getLoc();916return Error(Loc, "unexpected token");917}918919while (getLexer().is(AsmToken::Comma) || getLexer().is(AsmToken::Plus)) {920if (getLexer().is(AsmToken::Plus)) {921// Plus tokens are significant in software_traps (p83, sparcv8.pdf). We must capture them.922Operands.push_back(SparcOperand::CreateToken("+", Parser.getTok().getLoc()));923}924Parser.Lex(); // Eat the comma or plus.925// Parse and remember the operand.926if (!parseOperand(Operands, Name).isSuccess()) {927SMLoc Loc = getLexer().getLoc();928return Error(Loc, "unexpected token");929}930}931}932if (getLexer().isNot(AsmToken::EndOfStatement)) {933SMLoc Loc = getLexer().getLoc();934return Error(Loc, "unexpected token");935}936Parser.Lex(); // Consume the EndOfStatement.937return false;938}939940ParseStatus SparcAsmParser::parseDirective(AsmToken DirectiveID) {941StringRef IDVal = DirectiveID.getString();942943if (IDVal == ".register") {944// For now, ignore .register directive.945Parser.eatToEndOfStatement();946return ParseStatus::Success;947}948if (IDVal == ".proc") {949// For compatibility, ignore this directive.950// (It's supposed to be an "optimization" in the Sun assembler)951Parser.eatToEndOfStatement();952return ParseStatus::Success;953}954955// Let the MC layer to handle other directives.956return ParseStatus::NoMatch;957}958959ParseStatus SparcAsmParser::parseMEMOperand(OperandVector &Operands) {960SMLoc S, E;961962std::unique_ptr<SparcOperand> LHS;963if (!parseSparcAsmOperand(LHS).isSuccess())964return ParseStatus::NoMatch;965966// Single immediate operand967if (LHS->isImm()) {968Operands.push_back(SparcOperand::MorphToMEMri(Sparc::G0, std::move(LHS)));969return ParseStatus::Success;970}971972if (!LHS->isIntReg())973return Error(LHS->getStartLoc(), "invalid register kind for this operand");974975AsmToken Tok = getLexer().getTok();976// The plus token may be followed by a register or an immediate value, the977// minus one is always interpreted as sign for the immediate value978if (Tok.is(AsmToken::Plus) || Tok.is(AsmToken::Minus)) {979(void)Parser.parseOptionalToken(AsmToken::Plus);980981std::unique_ptr<SparcOperand> RHS;982if (!parseSparcAsmOperand(RHS).isSuccess())983return ParseStatus::NoMatch;984985if (RHS->isReg() && !RHS->isIntReg())986return Error(RHS->getStartLoc(),987"invalid register kind for this operand");988989Operands.push_back(990RHS->isImm()991? SparcOperand::MorphToMEMri(LHS->getReg(), std::move(RHS))992: SparcOperand::MorphToMEMrr(LHS->getReg(), std::move(RHS)));993994return ParseStatus::Success;995}996997Operands.push_back(SparcOperand::CreateMEMr(LHS->getReg(), S, E));998return ParseStatus::Success;999}10001001template <unsigned N>1002ParseStatus SparcAsmParser::parseShiftAmtImm(OperandVector &Operands) {1003SMLoc S = Parser.getTok().getLoc();1004SMLoc E = SMLoc::getFromPointer(S.getPointer() - 1);10051006// This is a register, not an immediate1007if (getLexer().getKind() == AsmToken::Percent)1008return ParseStatus::NoMatch;10091010const MCExpr *Expr;1011if (getParser().parseExpression(Expr))1012return ParseStatus::Failure;10131014const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);1015if (!CE)1016return Error(S, "constant expression expected");10171018if (!isUInt<N>(CE->getValue()))1019return Error(S, "immediate shift value out of range");10201021Operands.push_back(SparcOperand::CreateImm(Expr, S, E));1022return ParseStatus::Success;1023}10241025template <SparcAsmParser::TailRelocKind Kind>1026ParseStatus SparcAsmParser::parseTailRelocSym(OperandVector &Operands) {1027SMLoc S = getLoc();1028SMLoc E = SMLoc::getFromPointer(S.getPointer() - 1);10291030auto MatchesKind = [](SparcMCExpr::VariantKind VK) -> bool {1031switch (Kind) {1032case TailRelocKind::Load_GOT:1033// Non-TLS relocations on ld (or ldx).1034// ld [%rr + %rr], %rr, %rel(sym)1035return VK == SparcMCExpr::VK_Sparc_GOTDATA_OP;1036case TailRelocKind::Add_TLS:1037// TLS relocations on add.1038// add %rr, %rr, %rr, %rel(sym)1039switch (VK) {1040case SparcMCExpr::VK_Sparc_TLS_GD_ADD:1041case SparcMCExpr::VK_Sparc_TLS_IE_ADD:1042case SparcMCExpr::VK_Sparc_TLS_LDM_ADD:1043case SparcMCExpr::VK_Sparc_TLS_LDO_ADD:1044return true;1045default:1046return false;1047}1048case TailRelocKind::Load_TLS:1049// TLS relocations on ld (or ldx).1050// ld[x] %addr, %rr, %rel(sym)1051switch (VK) {1052case SparcMCExpr::VK_Sparc_TLS_IE_LD:1053case SparcMCExpr::VK_Sparc_TLS_IE_LDX:1054return true;1055default:1056return false;1057}1058case TailRelocKind::Call_TLS:1059// TLS relocations on call.1060// call sym, %rel(sym)1061switch (VK) {1062case SparcMCExpr::VK_Sparc_TLS_GD_CALL:1063case SparcMCExpr::VK_Sparc_TLS_LDM_CALL:1064return true;1065default:1066return false;1067}1068}1069llvm_unreachable("Unhandled SparcAsmParser::TailRelocKind enum");1070};10711072if (getLexer().getKind() != AsmToken::Percent)1073return Error(getLoc(), "expected '%' for operand modifier");10741075const AsmToken Tok = Parser.getTok();1076getParser().Lex(); // Eat '%'10771078if (getLexer().getKind() != AsmToken::Identifier)1079return Error(getLoc(), "expected valid identifier for operand modifier");10801081StringRef Name = getParser().getTok().getIdentifier();1082SparcMCExpr::VariantKind VK = SparcMCExpr::parseVariantKind(Name);1083if (VK == SparcMCExpr::VK_Sparc_None)1084return Error(getLoc(), "invalid operand modifier");10851086if (!MatchesKind(VK)) {1087// Did not match the specified set of relocation types, put '%' back.1088getLexer().UnLex(Tok);1089return ParseStatus::NoMatch;1090}10911092Parser.Lex(); // Eat the identifier.1093if (getLexer().getKind() != AsmToken::LParen)1094return Error(getLoc(), "expected '('");10951096getParser().Lex(); // Eat '('1097const MCExpr *SubExpr;1098if (getParser().parseParenExpression(SubExpr, E))1099return ParseStatus::Failure;11001101const MCExpr *Val = adjustPICRelocation(VK, SubExpr);1102Operands.push_back(SparcOperand::CreateImm(Val, S, E));1103return ParseStatus::Success;1104}11051106ParseStatus SparcAsmParser::parseMembarTag(OperandVector &Operands) {1107SMLoc S = Parser.getTok().getLoc();1108const MCExpr *EVal;1109int64_t ImmVal = 0;11101111std::unique_ptr<SparcOperand> Mask;1112if (parseSparcAsmOperand(Mask).isSuccess()) {1113if (!Mask->isImm() || !Mask->getImm()->evaluateAsAbsolute(ImmVal) ||1114ImmVal < 0 || ImmVal > 127)1115return Error(S, "invalid membar mask number");1116}11171118while (getLexer().getKind() == AsmToken::Hash) {1119SMLoc TagStart = getLexer().getLoc();1120Parser.Lex(); // Eat the '#'.1121unsigned MaskVal = StringSwitch<unsigned>(Parser.getTok().getString())1122.Case("LoadLoad", 0x1)1123.Case("StoreLoad", 0x2)1124.Case("LoadStore", 0x4)1125.Case("StoreStore", 0x8)1126.Case("Lookaside", 0x10)1127.Case("MemIssue", 0x20)1128.Case("Sync", 0x40)1129.Default(0);11301131Parser.Lex(); // Eat the identifier token.11321133if (!MaskVal)1134return Error(TagStart, "unknown membar tag");11351136ImmVal |= MaskVal;11371138if (getLexer().getKind() == AsmToken::Pipe)1139Parser.Lex(); // Eat the '|'.1140}11411142EVal = MCConstantExpr::create(ImmVal, getContext());1143SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);1144Operands.push_back(SparcOperand::CreateImm(EVal, S, E));1145return ParseStatus::Success;1146}11471148ParseStatus SparcAsmParser::parseASITag(OperandVector &Operands) {1149SMLoc S = Parser.getTok().getLoc();1150SMLoc E = Parser.getTok().getEndLoc();1151int64_t ASIVal = 0;11521153if (getLexer().getKind() != AsmToken::Hash) {1154// If the ASI tag provided is not a named tag, then it1155// must be a constant expression.1156ParseStatus ParseExprStatus = parseExpression(ASIVal);1157if (!ParseExprStatus.isSuccess())1158return ParseExprStatus;11591160if (!isUInt<8>(ASIVal))1161return Error(S, "invalid ASI number, must be between 0 and 255");11621163Operands.push_back(SparcOperand::CreateASITag(ASIVal, S, E));1164return ParseStatus::Success;1165}11661167// For now we only support named tags for 64-bit/V9 systems.1168// TODO: add support for 32-bit/V8 systems.1169SMLoc TagStart = getLexer().peekTok(false).getLoc();1170Parser.Lex(); // Eat the '#'.1171const StringRef ASIName = Parser.getTok().getString();1172const SparcASITag::ASITag *ASITag = SparcASITag::lookupASITagByName(ASIName);1173if (!ASITag)1174ASITag = SparcASITag::lookupASITagByAltName(ASIName);1175Parser.Lex(); // Eat the identifier token.11761177if (!ASITag)1178return Error(TagStart, "unknown ASI tag");11791180ASIVal = ASITag->Encoding;11811182Operands.push_back(SparcOperand::CreateASITag(ASIVal, S, E));1183return ParseStatus::Success;1184}11851186ParseStatus SparcAsmParser::parsePrefetchTag(OperandVector &Operands) {1187SMLoc S = Parser.getTok().getLoc();1188SMLoc E = Parser.getTok().getEndLoc();1189int64_t PrefetchVal = 0;11901191if (getLexer().getKind() != AsmToken::Hash) {1192// If the prefetch tag provided is not a named tag, then it1193// must be a constant expression.1194ParseStatus ParseExprStatus = parseExpression(PrefetchVal);1195if (!ParseExprStatus.isSuccess())1196return ParseExprStatus;11971198if (!isUInt<8>(PrefetchVal))1199return Error(S, "invalid prefetch number, must be between 0 and 31");12001201Operands.push_back(SparcOperand::CreatePrefetchTag(PrefetchVal, S, E));1202return ParseStatus::Success;1203}12041205SMLoc TagStart = getLexer().peekTok(false).getLoc();1206Parser.Lex(); // Eat the '#'.1207const StringRef PrefetchName = Parser.getTok().getString();1208const SparcPrefetchTag::PrefetchTag *PrefetchTag =1209SparcPrefetchTag::lookupPrefetchTagByName(PrefetchName);1210Parser.Lex(); // Eat the identifier token.12111212if (!PrefetchTag)1213return Error(TagStart, "unknown prefetch tag");12141215PrefetchVal = PrefetchTag->Encoding;12161217Operands.push_back(SparcOperand::CreatePrefetchTag(PrefetchVal, S, E));1218return ParseStatus::Success;1219}12201221ParseStatus SparcAsmParser::parseCallTarget(OperandVector &Operands) {1222SMLoc S = Parser.getTok().getLoc();1223SMLoc E = SMLoc::getFromPointer(S.getPointer() - 1);12241225switch (getLexer().getKind()) {1226default:1227return ParseStatus::NoMatch;1228case AsmToken::LParen:1229case AsmToken::Integer:1230case AsmToken::Identifier:1231case AsmToken::Dot:1232break;1233}12341235const MCExpr *DestValue;1236if (getParser().parseExpression(DestValue))1237return ParseStatus::NoMatch;12381239bool IsPic = getContext().getObjectFileInfo()->isPositionIndependent();1240SparcMCExpr::VariantKind Kind =1241IsPic ? SparcMCExpr::VK_Sparc_WPLT30 : SparcMCExpr::VK_Sparc_WDISP30;12421243const MCExpr *DestExpr = SparcMCExpr::create(Kind, DestValue, getContext());1244Operands.push_back(SparcOperand::CreateImm(DestExpr, S, E));1245return ParseStatus::Success;1246}12471248ParseStatus SparcAsmParser::parseOperand(OperandVector &Operands,1249StringRef Mnemonic) {12501251ParseStatus Res = MatchOperandParserImpl(Operands, Mnemonic);12521253// If there wasn't a custom match, try the generic matcher below. Otherwise,1254// there was a match, but an error occurred, in which case, just return that1255// the operand parsing failed.1256if (Res.isSuccess() || Res.isFailure())1257return Res;12581259if (getLexer().is(AsmToken::LBrac)) {1260// Memory operand1261Operands.push_back(SparcOperand::CreateToken("[",1262Parser.getTok().getLoc()));1263Parser.Lex(); // Eat the [12641265if (Mnemonic == "cas" || Mnemonic == "casl" || Mnemonic == "casa" ||1266Mnemonic == "casx" || Mnemonic == "casxl" || Mnemonic == "casxa") {1267SMLoc S = Parser.getTok().getLoc();1268if (getLexer().getKind() != AsmToken::Percent)1269return ParseStatus::NoMatch;1270Parser.Lex(); // eat %12711272unsigned RegKind;1273MCRegister Reg = matchRegisterName(Parser.getTok(), RegKind);1274if (!Reg)1275return ParseStatus::NoMatch;12761277Parser.Lex(); // Eat the identifier token.1278SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer()-1);1279Operands.push_back(SparcOperand::CreateReg(Reg, RegKind, S, E));1280Res = ParseStatus::Success;1281} else {1282Res = parseMEMOperand(Operands);1283}12841285if (!Res.isSuccess())1286return Res;12871288if (!getLexer().is(AsmToken::RBrac))1289return ParseStatus::Failure;12901291Operands.push_back(SparcOperand::CreateToken("]",1292Parser.getTok().getLoc()));1293Parser.Lex(); // Eat the ]12941295// Parse an optional address-space identifier after the address.1296// This will be either an immediate constant expression, or, on 64-bit1297// processors, the %asi register.1298if (getLexer().is(AsmToken::Percent)) {1299SMLoc S = Parser.getTok().getLoc();1300if (!is64Bit())1301return Error(1302S, "malformed ASI tag, must be a constant integer expression");13031304Parser.Lex(); // Eat the %.1305const AsmToken Tok = Parser.getTok();1306if (Tok.is(AsmToken::Identifier) && Tok.getString() == "asi") {1307// Here we patch the MEM operand from [base + %g0] into [base + 0]1308// as memory operations with ASI tag stored in %asi register needs1309// to use immediate offset. We need to do this because Reg addressing1310// will be parsed as Reg+G0 initially.1311// This allows forms such as `ldxa [%o0] %asi, %o0` to parse correctly.1312SparcOperand &OldMemOp = (SparcOperand &)*Operands[Operands.size() - 2];1313if (OldMemOp.isMEMrr()) {1314if (OldMemOp.getMemOffsetReg() != Sparc::G0) {1315return Error(S, "invalid operand for instruction");1316}1317Operands[Operands.size() - 2] = SparcOperand::MorphToMEMri(1318OldMemOp.getMemBase(),1319SparcOperand::CreateImm(MCConstantExpr::create(0, getContext()),1320OldMemOp.getStartLoc(),1321OldMemOp.getEndLoc()));1322}1323Parser.Lex(); // Eat the identifier.1324// In this context, we convert the register operand into1325// a plain "%asi" token since the register access is already1326// implicit in the instruction definition and encoding.1327// See LoadASI/StoreASI in SparcInstrInfo.td.1328Operands.push_back(SparcOperand::CreateToken("%asi", S));1329return ParseStatus::Success;1330}13311332return Error(S, "malformed ASI tag, must be %asi, a constant integer "1333"expression, or a named tag");1334}13351336// If we're not at the end of statement and the next token is not a comma,1337// then it is an immediate ASI value.1338if (getLexer().isNot(AsmToken::EndOfStatement) &&1339getLexer().isNot(AsmToken::Comma))1340return parseASITag(Operands);1341return ParseStatus::Success;1342}13431344std::unique_ptr<SparcOperand> Op;13451346Res = parseSparcAsmOperand(Op, (Mnemonic == "call"));1347if (!Res.isSuccess() || !Op)1348return ParseStatus::Failure;13491350// Push the parsed operand into the list of operands1351Operands.push_back(std::move(Op));13521353return ParseStatus::Success;1354}13551356ParseStatus1357SparcAsmParser::parseSparcAsmOperand(std::unique_ptr<SparcOperand> &Op,1358bool isCall) {1359SMLoc S = Parser.getTok().getLoc();1360SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);1361const MCExpr *EVal;13621363Op = nullptr;1364switch (getLexer().getKind()) {1365default: break;13661367case AsmToken::Percent: {1368Parser.Lex(); // Eat the '%'.1369unsigned RegKind;1370if (MCRegister Reg = matchRegisterName(Parser.getTok(), RegKind)) {1371StringRef Name = Parser.getTok().getString();1372Parser.Lex(); // Eat the identifier token.1373E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);1374if (Reg == Sparc::ICC && Name == "xcc")1375Op = SparcOperand::CreateToken("%xcc", S);1376else1377Op = SparcOperand::CreateReg(Reg, RegKind, S, E);1378break;1379}1380if (matchSparcAsmModifiers(EVal, E)) {1381E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);1382Op = SparcOperand::CreateImm(EVal, S, E);1383}1384break;1385}13861387case AsmToken::Plus:1388case AsmToken::Minus:1389case AsmToken::Integer:1390case AsmToken::LParen:1391case AsmToken::Dot:1392case AsmToken::Identifier:1393if (getParser().parseExpression(EVal, E))1394break;13951396int64_t Res;1397if (!EVal->evaluateAsAbsolute(Res)) {1398SparcMCExpr::VariantKind Kind = SparcMCExpr::VK_Sparc_13;13991400if (getContext().getObjectFileInfo()->isPositionIndependent()) {1401if (isCall)1402Kind = SparcMCExpr::VK_Sparc_WPLT30;1403else1404Kind = SparcMCExpr::VK_Sparc_GOT13;1405}1406EVal = SparcMCExpr::create(Kind, EVal, getContext());1407}1408Op = SparcOperand::CreateImm(EVal, S, E);1409break;1410}1411return Op ? ParseStatus::Success : ParseStatus::Failure;1412}14131414ParseStatus SparcAsmParser::parseBranchModifiers(OperandVector &Operands) {1415// parse (,a|,pn|,pt)+14161417while (getLexer().is(AsmToken::Comma)) {1418Parser.Lex(); // Eat the comma14191420if (!getLexer().is(AsmToken::Identifier))1421return ParseStatus::Failure;1422StringRef modName = Parser.getTok().getString();1423if (modName == "a" || modName == "pn" || modName == "pt") {1424Operands.push_back(SparcOperand::CreateToken(modName,1425Parser.getTok().getLoc()));1426Parser.Lex(); // eat the identifier.1427}1428}1429return ParseStatus::Success;1430}14311432ParseStatus SparcAsmParser::parseExpression(int64_t &Val) {1433AsmToken Tok = getLexer().getTok();14341435if (!isPossibleExpression(Tok))1436return ParseStatus::NoMatch;14371438return getParser().parseAbsoluteExpression(Val);1439}14401441MCRegister SparcAsmParser::matchRegisterName(const AsmToken &Tok,1442unsigned &RegKind) {1443RegKind = SparcOperand::rk_None;1444if (!Tok.is(AsmToken::Identifier))1445return SP::NoRegister;14461447StringRef Name = Tok.getString();1448MCRegister Reg = MatchRegisterName(Name.lower());1449if (!Reg)1450Reg = MatchRegisterAltName(Name.lower());14511452if (Reg) {1453// Some registers have identical spellings. The generated matcher might1454// have chosen one or another spelling, e.g. "%fp" or "%i6" might have been1455// matched to either SP::I6 or SP::I6_I7. Other parts of SparcAsmParser1456// are not prepared for this, so we do some canonicalization.14571458// See the note in SparcRegisterInfo.td near ASRRegs register class.1459if (Reg == SP::ASR4 && Name == "tick") {1460RegKind = SparcOperand::rk_Special;1461return SP::TICK;1462}14631464if (MRI.getRegClass(SP::IntRegsRegClassID).contains(Reg)) {1465RegKind = SparcOperand::rk_IntReg;1466return Reg;1467}1468if (MRI.getRegClass(SP::FPRegsRegClassID).contains(Reg)) {1469RegKind = SparcOperand::rk_FloatReg;1470return Reg;1471}1472if (MRI.getRegClass(SP::CoprocRegsRegClassID).contains(Reg)) {1473RegKind = SparcOperand::rk_CoprocReg;1474return Reg;1475}14761477// Canonicalize G0_G1 ... G30_G31 etc. to G0 ... G30.1478if (MRI.getRegClass(SP::IntPairRegClassID).contains(Reg)) {1479RegKind = SparcOperand::rk_IntReg;1480return MRI.getSubReg(Reg, SP::sub_even);1481}14821483// Canonicalize D0 ... D15 to F0 ... F30.1484if (MRI.getRegClass(SP::DFPRegsRegClassID).contains(Reg)) {1485// D16 ... D31 do not have sub-registers.1486if (MCRegister SubReg = MRI.getSubReg(Reg, SP::sub_even)) {1487RegKind = SparcOperand::rk_FloatReg;1488return SubReg;1489}1490RegKind = SparcOperand::rk_DoubleReg;1491return Reg;1492}14931494// The generated matcher does not currently return QFP registers.1495// If it changes, we will need to handle them in a similar way.1496assert(!MRI.getRegClass(SP::QFPRegsRegClassID).contains(Reg));14971498// Canonicalize C0_C1 ... C30_C31 to C0 ... C30.1499if (MRI.getRegClass(SP::CoprocPairRegClassID).contains(Reg)) {1500RegKind = SparcOperand::rk_CoprocReg;1501return MRI.getSubReg(Reg, SP::sub_even);1502}15031504// Other registers do not need special handling.1505RegKind = SparcOperand::rk_Special;1506return Reg;1507}15081509// If we still have no match, try custom parsing.1510// Not all registers and their spellings are modeled in td files.15111512// %r0 - %r311513int64_t RegNo = 0;1514if (Name.starts_with_insensitive("r") &&1515!Name.substr(1, 2).getAsInteger(10, RegNo) && RegNo < 31) {1516RegKind = SparcOperand::rk_IntReg;1517return IntRegs[RegNo];1518}15191520if (Name == "xcc") {1521// FIXME:: check 64bit.1522RegKind = SparcOperand::rk_Special;1523return SP::ICC;1524}15251526// JPS1 extension - aliases for ASRs1527// Section 5.2.11 - Ancillary State Registers (ASRs)1528if (Name == "pcr") {1529RegKind = SparcOperand::rk_Special;1530return SP::ASR16;1531}1532if (Name == "pic") {1533RegKind = SparcOperand::rk_Special;1534return SP::ASR17;1535}1536if (Name == "dcr") {1537RegKind = SparcOperand::rk_Special;1538return SP::ASR18;1539}1540if (Name == "gsr") {1541RegKind = SparcOperand::rk_Special;1542return SP::ASR19;1543}1544if (Name == "set_softint") {1545RegKind = SparcOperand::rk_Special;1546return SP::ASR20;1547}1548if (Name == "clear_softint") {1549RegKind = SparcOperand::rk_Special;1550return SP::ASR21;1551}1552if (Name == "softint") {1553RegKind = SparcOperand::rk_Special;1554return SP::ASR22;1555}1556if (Name == "tick_cmpr") {1557RegKind = SparcOperand::rk_Special;1558return SP::ASR23;1559}1560if (Name == "stick" || Name == "sys_tick") {1561RegKind = SparcOperand::rk_Special;1562return SP::ASR24;1563}1564if (Name == "stick_cmpr" || Name == "sys_tick_cmpr") {1565RegKind = SparcOperand::rk_Special;1566return SP::ASR25;1567}15681569return SP::NoRegister;1570}15711572// Determine if an expression contains a reference to the symbol1573// "_GLOBAL_OFFSET_TABLE_".1574static bool hasGOTReference(const MCExpr *Expr) {1575switch (Expr->getKind()) {1576case MCExpr::Target:1577if (const SparcMCExpr *SE = dyn_cast<SparcMCExpr>(Expr))1578return hasGOTReference(SE->getSubExpr());1579break;15801581case MCExpr::Constant:1582break;15831584case MCExpr::Binary: {1585const MCBinaryExpr *BE = cast<MCBinaryExpr>(Expr);1586return hasGOTReference(BE->getLHS()) || hasGOTReference(BE->getRHS());1587}15881589case MCExpr::SymbolRef: {1590const MCSymbolRefExpr &SymRef = *cast<MCSymbolRefExpr>(Expr);1591return (SymRef.getSymbol().getName() == "_GLOBAL_OFFSET_TABLE_");1592}15931594case MCExpr::Unary:1595return hasGOTReference(cast<MCUnaryExpr>(Expr)->getSubExpr());1596}1597return false;1598}15991600const SparcMCExpr *1601SparcAsmParser::adjustPICRelocation(SparcMCExpr::VariantKind VK,1602const MCExpr *subExpr) {1603// When in PIC mode, "%lo(...)" and "%hi(...)" behave differently.1604// If the expression refers contains _GLOBAL_OFFSET_TABLE, it is1605// actually a %pc10 or %pc22 relocation. Otherwise, they are interpreted1606// as %got10 or %got22 relocation.16071608if (getContext().getObjectFileInfo()->isPositionIndependent()) {1609switch(VK) {1610default: break;1611case SparcMCExpr::VK_Sparc_LO:1612VK = (hasGOTReference(subExpr) ? SparcMCExpr::VK_Sparc_PC101613: SparcMCExpr::VK_Sparc_GOT10);1614break;1615case SparcMCExpr::VK_Sparc_HI:1616VK = (hasGOTReference(subExpr) ? SparcMCExpr::VK_Sparc_PC221617: SparcMCExpr::VK_Sparc_GOT22);1618break;1619}1620}16211622return SparcMCExpr::create(VK, subExpr, getContext());1623}16241625bool SparcAsmParser::matchSparcAsmModifiers(const MCExpr *&EVal,1626SMLoc &EndLoc) {1627AsmToken Tok = Parser.getTok();1628if (!Tok.is(AsmToken::Identifier))1629return false;16301631StringRef name = Tok.getString();16321633SparcMCExpr::VariantKind VK = SparcMCExpr::parseVariantKind(name);1634switch (VK) {1635case SparcMCExpr::VK_Sparc_None:1636Error(getLoc(), "invalid operand modifier");1637return false;16381639case SparcMCExpr::VK_Sparc_GOTDATA_OP:1640case SparcMCExpr::VK_Sparc_TLS_GD_ADD:1641case SparcMCExpr::VK_Sparc_TLS_GD_CALL:1642case SparcMCExpr::VK_Sparc_TLS_IE_ADD:1643case SparcMCExpr::VK_Sparc_TLS_IE_LD:1644case SparcMCExpr::VK_Sparc_TLS_IE_LDX:1645case SparcMCExpr::VK_Sparc_TLS_LDM_ADD:1646case SparcMCExpr::VK_Sparc_TLS_LDM_CALL:1647case SparcMCExpr::VK_Sparc_TLS_LDO_ADD:1648// These are special-cased at tablegen level.1649return false;16501651default:1652break;1653}16541655Parser.Lex(); // Eat the identifier.1656if (Parser.getTok().getKind() != AsmToken::LParen)1657return false;16581659Parser.Lex(); // Eat the LParen token.1660const MCExpr *subExpr;1661if (Parser.parseParenExpression(subExpr, EndLoc))1662return false;16631664EVal = adjustPICRelocation(VK, subExpr);1665return true;1666}16671668bool SparcAsmParser::isPossibleExpression(const AsmToken &Token) {1669switch (Token.getKind()) {1670case AsmToken::LParen:1671case AsmToken::Integer:1672case AsmToken::Identifier:1673case AsmToken::Plus:1674case AsmToken::Minus:1675case AsmToken::Tilde:1676return true;1677default:1678return false;1679}1680}16811682extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeSparcAsmParser() {1683RegisterMCAsmParser<SparcAsmParser> A(getTheSparcTarget());1684RegisterMCAsmParser<SparcAsmParser> B(getTheSparcV9Target());1685RegisterMCAsmParser<SparcAsmParser> C(getTheSparcelTarget());1686}16871688unsigned SparcAsmParser::validateTargetOperandClass(MCParsedAsmOperand &GOp,1689unsigned Kind) {1690SparcOperand &Op = (SparcOperand &)GOp;1691if (Op.isFloatOrDoubleReg()) {1692switch (Kind) {1693default: break;1694case MCK_DFPRegs:1695if (!Op.isFloatReg() || SparcOperand::MorphToDoubleReg(Op))1696return MCTargetAsmParser::Match_Success;1697break;1698case MCK_QFPRegs:1699if (SparcOperand::MorphToQuadReg(Op))1700return MCTargetAsmParser::Match_Success;1701break;1702}1703}1704if (Op.isIntReg() && Kind == MCK_IntPair) {1705if (SparcOperand::MorphToIntPairReg(Op))1706return MCTargetAsmParser::Match_Success;1707}1708if (Op.isCoprocReg() && Kind == MCK_CoprocPair) {1709if (SparcOperand::MorphToCoprocPairReg(Op))1710return MCTargetAsmParser::Match_Success;1711}1712return Match_InvalidOperand;1713}171417151716