LLVM 19.0.0git
SparcAsmParser.cpp
Go to the documentation of this file.
1//===-- SparcAsmParser.cpp - Parse Sparc assembly to MCInst instructions --===//
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
12#include "llvm/ADT/STLExtras.h"
14#include "llvm/ADT/StringRef.h"
15#include "llvm/MC/MCAsmMacro.h"
16#include "llvm/MC/MCContext.h"
17#include "llvm/MC/MCExpr.h"
18#include "llvm/MC/MCInst.h"
20#include "llvm/MC/MCInstrInfo.h"
27#include "llvm/MC/MCStreamer.h"
29#include "llvm/MC/MCSymbol.h"
34#include "llvm/Support/SMLoc.h"
37#include <algorithm>
38#include <cassert>
39#include <cstdint>
40#include <memory>
41
42using namespace llvm;
43
44// The generated AsmMatcher SparcGenAsmMatcher uses "Sparc" as the target
45// namespace. But SPARC backend uses "SP" as its namespace.
46namespace llvm {
47namespace Sparc {
48
49 using namespace SP;
50
51} // end namespace Sparc
52} // end namespace llvm
53
54namespace {
55
56class SparcOperand;
57
58class SparcAsmParser : public MCTargetAsmParser {
59 MCAsmParser &Parser;
60 const MCRegisterInfo &MRI;
61
62 enum class TailRelocKind { Load_GOT, Add_TLS, Load_TLS, Call_TLS };
63
64 /// @name Auto-generated Match Functions
65 /// {
66
67#define GET_ASSEMBLER_HEADER
68#include "SparcGenAsmMatcher.inc"
69
70 /// }
71
72 // public interface of the MCTargetAsmParser.
73 bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
76 bool MatchingInlineAsm) override;
77 bool parseRegister(MCRegister &Reg, SMLoc &StartLoc, SMLoc &EndLoc) override;
79 SMLoc &EndLoc) override;
81 SMLoc NameLoc, OperandVector &Operands) override;
82 ParseStatus parseDirective(AsmToken DirectiveID) override;
83
85 unsigned Kind) override;
86
87 // Custom parse functions for Sparc specific operands.
88 ParseStatus parseMEMOperand(OperandVector &Operands);
89
90 ParseStatus parseMembarTag(OperandVector &Operands);
91
93
94 template <TailRelocKind Kind>
95 ParseStatus parseTailRelocSym(OperandVector &Operands);
96
97 template <unsigned N> ParseStatus parseShiftAmtImm(OperandVector &Operands);
98
99 ParseStatus parseCallTarget(OperandVector &Operands);
100
102
103 ParseStatus parseSparcAsmOperand(std::unique_ptr<SparcOperand> &Operand,
104 bool isCall = false);
105
106 ParseStatus parseBranchModifiers(OperandVector &Operands);
107
108 // Helper function for dealing with %lo / %hi in PIC mode.
109 const SparcMCExpr *adjustPICRelocation(SparcMCExpr::VariantKind VK,
110 const MCExpr *subExpr);
111
112 // returns true if Tok is matched to a register and returns register in RegNo.
113 MCRegister matchRegisterName(const AsmToken &Tok, unsigned &RegKind);
114
115 bool matchSparcAsmModifiers(const MCExpr *&EVal, SMLoc &EndLoc);
116
117 bool is64Bit() const {
119 }
120
121 bool expandSET(MCInst &Inst, SMLoc IDLoc,
122 SmallVectorImpl<MCInst> &Instructions);
123
124 bool expandSETX(MCInst &Inst, SMLoc IDLoc,
125 SmallVectorImpl<MCInst> &Instructions);
126
127 SMLoc getLoc() const { return getParser().getTok().getLoc(); }
128
129public:
130 SparcAsmParser(const MCSubtargetInfo &sti, MCAsmParser &parser,
131 const MCInstrInfo &MII, const MCTargetOptions &Options)
132 : MCTargetAsmParser(Options, sti, MII), Parser(parser),
133 MRI(*Parser.getContext().getRegisterInfo()) {
134 Parser.addAliasForDirective(".half", ".2byte");
135 Parser.addAliasForDirective(".uahalf", ".2byte");
136 Parser.addAliasForDirective(".word", ".4byte");
137 Parser.addAliasForDirective(".uaword", ".4byte");
138 Parser.addAliasForDirective(".nword", is64Bit() ? ".8byte" : ".4byte");
139 if (is64Bit())
140 Parser.addAliasForDirective(".xword", ".8byte");
141
142 // Initialize the set of available features.
143 setAvailableFeatures(ComputeAvailableFeatures(getSTI().getFeatureBits()));
144 }
145};
146
147} // end anonymous namespace
148
149 static const MCPhysReg IntRegs[32] = {
150 Sparc::G0, Sparc::G1, Sparc::G2, Sparc::G3,
151 Sparc::G4, Sparc::G5, Sparc::G6, Sparc::G7,
152 Sparc::O0, Sparc::O1, Sparc::O2, Sparc::O3,
153 Sparc::O4, Sparc::O5, Sparc::O6, Sparc::O7,
154 Sparc::L0, Sparc::L1, Sparc::L2, Sparc::L3,
155 Sparc::L4, Sparc::L5, Sparc::L6, Sparc::L7,
156 Sparc::I0, Sparc::I1, Sparc::I2, Sparc::I3,
157 Sparc::I4, Sparc::I5, Sparc::I6, Sparc::I7 };
158
159 static const MCPhysReg DoubleRegs[32] = {
160 Sparc::D0, Sparc::D1, Sparc::D2, Sparc::D3,
161 Sparc::D4, Sparc::D5, Sparc::D6, Sparc::D7,
162 Sparc::D8, Sparc::D9, Sparc::D10, Sparc::D11,
163 Sparc::D12, Sparc::D13, Sparc::D14, Sparc::D15,
164 Sparc::D16, Sparc::D17, Sparc::D18, Sparc::D19,
165 Sparc::D20, Sparc::D21, Sparc::D22, Sparc::D23,
166 Sparc::D24, Sparc::D25, Sparc::D26, Sparc::D27,
167 Sparc::D28, Sparc::D29, Sparc::D30, Sparc::D31 };
168
169 static const MCPhysReg QuadFPRegs[32] = {
170 Sparc::Q0, Sparc::Q1, Sparc::Q2, Sparc::Q3,
171 Sparc::Q4, Sparc::Q5, Sparc::Q6, Sparc::Q7,
172 Sparc::Q8, Sparc::Q9, Sparc::Q10, Sparc::Q11,
173 Sparc::Q12, Sparc::Q13, Sparc::Q14, Sparc::Q15 };
174
175 static const MCPhysReg IntPairRegs[] = {
176 Sparc::G0_G1, Sparc::G2_G3, Sparc::G4_G5, Sparc::G6_G7,
177 Sparc::O0_O1, Sparc::O2_O3, Sparc::O4_O5, Sparc::O6_O7,
178 Sparc::L0_L1, Sparc::L2_L3, Sparc::L4_L5, Sparc::L6_L7,
179 Sparc::I0_I1, Sparc::I2_I3, Sparc::I4_I5, Sparc::I6_I7};
180
181 static const MCPhysReg CoprocPairRegs[] = {
182 Sparc::C0_C1, Sparc::C2_C3, Sparc::C4_C5, Sparc::C6_C7,
183 Sparc::C8_C9, Sparc::C10_C11, Sparc::C12_C13, Sparc::C14_C15,
184 Sparc::C16_C17, Sparc::C18_C19, Sparc::C20_C21, Sparc::C22_C23,
185 Sparc::C24_C25, Sparc::C26_C27, Sparc::C28_C29, Sparc::C30_C31};
186
187namespace {
188
189/// SparcOperand - Instances of this class represent a parsed Sparc machine
190/// instruction.
191class SparcOperand : public MCParsedAsmOperand {
192public:
193 enum RegisterKind {
194 rk_None,
195 rk_IntReg,
196 rk_IntPairReg,
197 rk_FloatReg,
198 rk_DoubleReg,
199 rk_QuadReg,
200 rk_CoprocReg,
201 rk_CoprocPairReg,
202 rk_Special,
203 };
204
205private:
206 enum KindTy {
207 k_Token,
208 k_Register,
209 k_Immediate,
210 k_MemoryReg,
211 k_MemoryImm,
212 k_ASITag
213 } Kind;
214
215 SMLoc StartLoc, EndLoc;
216
217 struct Token {
218 const char *Data;
219 unsigned Length;
220 };
221
222 struct RegOp {
223 unsigned RegNum;
224 RegisterKind Kind;
225 };
226
227 struct ImmOp {
228 const MCExpr *Val;
229 };
230
231 struct MemOp {
232 unsigned Base;
233 unsigned OffsetReg;
234 const MCExpr *Off;
235 };
236
237 union {
238 struct Token Tok;
239 struct RegOp Reg;
240 struct ImmOp Imm;
241 struct MemOp Mem;
242 unsigned ASI;
243 };
244
245public:
246 SparcOperand(KindTy K) : Kind(K) {}
247
248 bool isToken() const override { return Kind == k_Token; }
249 bool isReg() const override { return Kind == k_Register; }
250 bool isImm() const override { return Kind == k_Immediate; }
251 bool isMem() const override { return isMEMrr() || isMEMri(); }
252 bool isMEMrr() const { return Kind == k_MemoryReg; }
253 bool isMEMri() const { return Kind == k_MemoryImm; }
254 bool isMembarTag() const { return Kind == k_Immediate; }
255 bool isASITag() const { return Kind == k_ASITag; }
256 bool isTailRelocSym() const { return Kind == k_Immediate; }
257
258 bool isCallTarget() const {
259 if (!isImm())
260 return false;
261
262 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val))
263 return CE->getValue() % 4 == 0;
264
265 return true;
266 }
267
268 bool isShiftAmtImm5() const {
269 if (!isImm())
270 return false;
271
272 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val))
273 return isUInt<5>(CE->getValue());
274
275 return false;
276 }
277
278 bool isShiftAmtImm6() const {
279 if (!isImm())
280 return false;
281
282 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val))
283 return isUInt<6>(CE->getValue());
284
285 return false;
286 }
287
288 bool isIntReg() const {
289 return (Kind == k_Register && Reg.Kind == rk_IntReg);
290 }
291
292 bool isFloatReg() const {
293 return (Kind == k_Register && Reg.Kind == rk_FloatReg);
294 }
295
296 bool isFloatOrDoubleReg() const {
297 return (Kind == k_Register && (Reg.Kind == rk_FloatReg
298 || Reg.Kind == rk_DoubleReg));
299 }
300
301 bool isCoprocReg() const {
302 return (Kind == k_Register && Reg.Kind == rk_CoprocReg);
303 }
304
305 StringRef getToken() const {
306 assert(Kind == k_Token && "Invalid access!");
307 return StringRef(Tok.Data, Tok.Length);
308 }
309
310 MCRegister getReg() const override {
311 assert((Kind == k_Register) && "Invalid access!");
312 return Reg.RegNum;
313 }
314
315 const MCExpr *getImm() const {
316 assert((Kind == k_Immediate) && "Invalid access!");
317 return Imm.Val;
318 }
319
320 unsigned getMemBase() const {
321 assert((Kind == k_MemoryReg || Kind == k_MemoryImm) && "Invalid access!");
322 return Mem.Base;
323 }
324
325 unsigned getMemOffsetReg() const {
326 assert((Kind == k_MemoryReg) && "Invalid access!");
327 return Mem.OffsetReg;
328 }
329
330 const MCExpr *getMemOff() const {
331 assert((Kind == k_MemoryImm) && "Invalid access!");
332 return Mem.Off;
333 }
334
335 unsigned getASITag() const {
336 assert((Kind == k_ASITag) && "Invalid access!");
337 return ASI;
338 }
339
340 /// getStartLoc - Get the location of the first token of this operand.
341 SMLoc getStartLoc() const override {
342 return StartLoc;
343 }
344 /// getEndLoc - Get the location of the last token of this operand.
345 SMLoc getEndLoc() const override {
346 return EndLoc;
347 }
348
349 void print(raw_ostream &OS) const override {
350 switch (Kind) {
351 case k_Token: OS << "Token: " << getToken() << "\n"; break;
352 case k_Register: OS << "Reg: #" << getReg() << "\n"; break;
353 case k_Immediate: OS << "Imm: " << getImm() << "\n"; break;
354 case k_MemoryReg: OS << "Mem: " << getMemBase() << "+"
355 << getMemOffsetReg() << "\n"; break;
356 case k_MemoryImm: assert(getMemOff() != nullptr);
357 OS << "Mem: " << getMemBase()
358 << "+" << *getMemOff()
359 << "\n"; break;
360 case k_ASITag:
361 OS << "ASI tag: " << getASITag() << "\n";
362 break;
363 }
364 }
365
366 void addRegOperands(MCInst &Inst, unsigned N) const {
367 assert(N == 1 && "Invalid number of operands!");
369 }
370
371 void addImmOperands(MCInst &Inst, unsigned N) const {
372 assert(N == 1 && "Invalid number of operands!");
373 const MCExpr *Expr = getImm();
374 addExpr(Inst, Expr);
375 }
376
377 void addShiftAmtImm5Operands(MCInst &Inst, unsigned N) const {
378 assert(N == 1 && "Invalid number of operands!");
379 addExpr(Inst, getImm());
380 }
381 void addShiftAmtImm6Operands(MCInst &Inst, unsigned N) const {
382 assert(N == 1 && "Invalid number of operands!");
383 addExpr(Inst, getImm());
384 }
385
386 void addExpr(MCInst &Inst, const MCExpr *Expr) const{
387 // Add as immediate when possible. Null MCExpr = 0.
388 if (!Expr)
390 else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
391 Inst.addOperand(MCOperand::createImm(CE->getValue()));
392 else
394 }
395
396 void addMEMrrOperands(MCInst &Inst, unsigned N) const {
397 assert(N == 2 && "Invalid number of operands!");
398
399 Inst.addOperand(MCOperand::createReg(getMemBase()));
400
401 assert(getMemOffsetReg() != 0 && "Invalid offset");
402 Inst.addOperand(MCOperand::createReg(getMemOffsetReg()));
403 }
404
405 void addMEMriOperands(MCInst &Inst, unsigned N) const {
406 assert(N == 2 && "Invalid number of operands!");
407
408 Inst.addOperand(MCOperand::createReg(getMemBase()));
409
410 const MCExpr *Expr = getMemOff();
411 addExpr(Inst, Expr);
412 }
413
414 void addASITagOperands(MCInst &Inst, unsigned N) const {
415 assert(N == 1 && "Invalid number of operands!");
416 Inst.addOperand(MCOperand::createImm(getASITag()));
417 }
418
419 void addMembarTagOperands(MCInst &Inst, unsigned N) const {
420 assert(N == 1 && "Invalid number of operands!");
421 const MCExpr *Expr = getImm();
422 addExpr(Inst, Expr);
423 }
424
425 void addCallTargetOperands(MCInst &Inst, unsigned N) const {
426 assert(N == 1 && "Invalid number of operands!");
427 addExpr(Inst, getImm());
428 }
429
430 void addTailRelocSymOperands(MCInst &Inst, unsigned N) const {
431 assert(N == 1 && "Invalid number of operands!");
432 addExpr(Inst, getImm());
433 }
434
435 static std::unique_ptr<SparcOperand> CreateToken(StringRef Str, SMLoc S) {
436 auto Op = std::make_unique<SparcOperand>(k_Token);
437 Op->Tok.Data = Str.data();
438 Op->Tok.Length = Str.size();
439 Op->StartLoc = S;
440 Op->EndLoc = S;
441 return Op;
442 }
443
444 static std::unique_ptr<SparcOperand> CreateReg(unsigned RegNum, unsigned Kind,
445 SMLoc S, SMLoc E) {
446 auto Op = std::make_unique<SparcOperand>(k_Register);
447 Op->Reg.RegNum = RegNum;
448 Op->Reg.Kind = (SparcOperand::RegisterKind)Kind;
449 Op->StartLoc = S;
450 Op->EndLoc = E;
451 return Op;
452 }
453
454 static std::unique_ptr<SparcOperand> CreateImm(const MCExpr *Val, SMLoc S,
455 SMLoc E) {
456 auto Op = std::make_unique<SparcOperand>(k_Immediate);
457 Op->Imm.Val = Val;
458 Op->StartLoc = S;
459 Op->EndLoc = E;
460 return Op;
461 }
462
463 static std::unique_ptr<SparcOperand> CreateASITag(unsigned Val, SMLoc S,
464 SMLoc E) {
465 auto Op = std::make_unique<SparcOperand>(k_ASITag);
466 Op->ASI = Val;
467 Op->StartLoc = S;
468 Op->EndLoc = E;
469 return Op;
470 }
471
472 static bool MorphToIntPairReg(SparcOperand &Op) {
473 unsigned Reg = Op.getReg();
474 assert(Op.Reg.Kind == rk_IntReg);
475 unsigned regIdx = 32;
476 if (Reg >= Sparc::G0 && Reg <= Sparc::G7)
477 regIdx = Reg - Sparc::G0;
478 else if (Reg >= Sparc::O0 && Reg <= Sparc::O7)
479 regIdx = Reg - Sparc::O0 + 8;
480 else if (Reg >= Sparc::L0 && Reg <= Sparc::L7)
481 regIdx = Reg - Sparc::L0 + 16;
482 else if (Reg >= Sparc::I0 && Reg <= Sparc::I7)
483 regIdx = Reg - Sparc::I0 + 24;
484 if (regIdx % 2 || regIdx > 31)
485 return false;
486 Op.Reg.RegNum = IntPairRegs[regIdx / 2];
487 Op.Reg.Kind = rk_IntPairReg;
488 return true;
489 }
490
491 static bool MorphToDoubleReg(SparcOperand &Op) {
492 unsigned Reg = Op.getReg();
493 assert(Op.Reg.Kind == rk_FloatReg);
494 unsigned regIdx = Reg - Sparc::F0;
495 if (regIdx % 2 || regIdx > 31)
496 return false;
497 Op.Reg.RegNum = DoubleRegs[regIdx / 2];
498 Op.Reg.Kind = rk_DoubleReg;
499 return true;
500 }
501
502 static bool MorphToQuadReg(SparcOperand &Op) {
503 unsigned Reg = Op.getReg();
504 unsigned regIdx = 0;
505 switch (Op.Reg.Kind) {
506 default: llvm_unreachable("Unexpected register kind!");
507 case rk_FloatReg:
508 regIdx = Reg - Sparc::F0;
509 if (regIdx % 4 || regIdx > 31)
510 return false;
511 Reg = QuadFPRegs[regIdx / 4];
512 break;
513 case rk_DoubleReg:
514 regIdx = Reg - Sparc::D0;
515 if (regIdx % 2 || regIdx > 31)
516 return false;
517 Reg = QuadFPRegs[regIdx / 2];
518 break;
519 }
520 Op.Reg.RegNum = Reg;
521 Op.Reg.Kind = rk_QuadReg;
522 return true;
523 }
524
525 static bool MorphToCoprocPairReg(SparcOperand &Op) {
526 unsigned Reg = Op.getReg();
527 assert(Op.Reg.Kind == rk_CoprocReg);
528 unsigned regIdx = 32;
529 if (Reg >= Sparc::C0 && Reg <= Sparc::C31)
530 regIdx = Reg - Sparc::C0;
531 if (regIdx % 2 || regIdx > 31)
532 return false;
533 Op.Reg.RegNum = CoprocPairRegs[regIdx / 2];
534 Op.Reg.Kind = rk_CoprocPairReg;
535 return true;
536 }
537
538 static std::unique_ptr<SparcOperand>
539 MorphToMEMrr(unsigned Base, std::unique_ptr<SparcOperand> Op) {
540 unsigned offsetReg = Op->getReg();
541 Op->Kind = k_MemoryReg;
542 Op->Mem.Base = Base;
543 Op->Mem.OffsetReg = offsetReg;
544 Op->Mem.Off = nullptr;
545 return Op;
546 }
547
548 static std::unique_ptr<SparcOperand>
549 CreateMEMr(unsigned Base, SMLoc S, SMLoc E) {
550 auto Op = std::make_unique<SparcOperand>(k_MemoryReg);
551 Op->Mem.Base = Base;
552 Op->Mem.OffsetReg = Sparc::G0; // always 0
553 Op->Mem.Off = nullptr;
554 Op->StartLoc = S;
555 Op->EndLoc = E;
556 return Op;
557 }
558
559 static std::unique_ptr<SparcOperand>
560 MorphToMEMri(unsigned Base, std::unique_ptr<SparcOperand> Op) {
561 const MCExpr *Imm = Op->getImm();
562 Op->Kind = k_MemoryImm;
563 Op->Mem.Base = Base;
564 Op->Mem.OffsetReg = 0;
565 Op->Mem.Off = Imm;
566 return Op;
567 }
568};
569
570} // end anonymous namespace
571
572bool SparcAsmParser::expandSET(MCInst &Inst, SMLoc IDLoc,
573 SmallVectorImpl<MCInst> &Instructions) {
574 MCOperand MCRegOp = Inst.getOperand(0);
575 MCOperand MCValOp = Inst.getOperand(1);
576 assert(MCRegOp.isReg());
577 assert(MCValOp.isImm() || MCValOp.isExpr());
578
579 // the imm operand can be either an expression or an immediate.
580 bool IsImm = Inst.getOperand(1).isImm();
581 int64_t RawImmValue = IsImm ? MCValOp.getImm() : 0;
582
583 // Allow either a signed or unsigned 32-bit immediate.
584 if (RawImmValue < -2147483648LL || RawImmValue > 4294967295LL) {
585 return Error(IDLoc,
586 "set: argument must be between -2147483648 and 4294967295");
587 }
588
589 // If the value was expressed as a large unsigned number, that's ok.
590 // We want to see if it "looks like" a small signed number.
591 int32_t ImmValue = RawImmValue;
592 // For 'set' you can't use 'or' with a negative operand on V9 because
593 // that would splat the sign bit across the upper half of the destination
594 // register, whereas 'set' is defined to zero the high 32 bits.
595 bool IsEffectivelyImm13 =
596 IsImm && ((is64Bit() ? 0 : -4096) <= ImmValue && ImmValue < 4096);
597 const MCExpr *ValExpr;
598 if (IsImm)
599 ValExpr = MCConstantExpr::create(ImmValue, getContext());
600 else
601 ValExpr = MCValOp.getExpr();
602
603 MCOperand PrevReg = MCOperand::createReg(Sparc::G0);
604
605 // If not just a signed imm13 value, then either we use a 'sethi' with a
606 // following 'or', or a 'sethi' by itself if there are no more 1 bits.
607 // In either case, start with the 'sethi'.
608 if (!IsEffectivelyImm13) {
609 MCInst TmpInst;
610 const MCExpr *Expr = adjustPICRelocation(SparcMCExpr::VK_Sparc_HI, ValExpr);
611 TmpInst.setLoc(IDLoc);
612 TmpInst.setOpcode(SP::SETHIi);
613 TmpInst.addOperand(MCRegOp);
614 TmpInst.addOperand(MCOperand::createExpr(Expr));
615 Instructions.push_back(TmpInst);
616 PrevReg = MCRegOp;
617 }
618
619 // The low bits require touching in 3 cases:
620 // * A non-immediate value will always require both instructions.
621 // * An effectively imm13 value needs only an 'or' instruction.
622 // * Otherwise, an immediate that is not effectively imm13 requires the
623 // 'or' only if bits remain after clearing the 22 bits that 'sethi' set.
624 // If the low bits are known zeros, there's nothing to do.
625 // In the second case, and only in that case, must we NOT clear
626 // bits of the immediate value via the %lo() assembler function.
627 // Note also, the 'or' instruction doesn't mind a large value in the case
628 // where the operand to 'set' was 0xFFFFFzzz - it does exactly what you mean.
629 if (!IsImm || IsEffectivelyImm13 || (ImmValue & 0x3ff)) {
630 MCInst TmpInst;
631 const MCExpr *Expr;
632 if (IsEffectivelyImm13)
633 Expr = ValExpr;
634 else
635 Expr = adjustPICRelocation(SparcMCExpr::VK_Sparc_LO, ValExpr);
636 TmpInst.setLoc(IDLoc);
637 TmpInst.setOpcode(SP::ORri);
638 TmpInst.addOperand(MCRegOp);
639 TmpInst.addOperand(PrevReg);
640 TmpInst.addOperand(MCOperand::createExpr(Expr));
641 Instructions.push_back(TmpInst);
642 }
643 return false;
644}
645
646bool SparcAsmParser::expandSETX(MCInst &Inst, SMLoc IDLoc,
647 SmallVectorImpl<MCInst> &Instructions) {
648 MCOperand MCRegOp = Inst.getOperand(0);
649 MCOperand MCValOp = Inst.getOperand(1);
650 MCOperand MCTmpOp = Inst.getOperand(2);
651 assert(MCRegOp.isReg() && MCTmpOp.isReg());
652 assert(MCValOp.isImm() || MCValOp.isExpr());
653
654 // the imm operand can be either an expression or an immediate.
655 bool IsImm = MCValOp.isImm();
656 int64_t ImmValue = IsImm ? MCValOp.getImm() : 0;
657
658 const MCExpr *ValExpr = IsImm ? MCConstantExpr::create(ImmValue, getContext())
659 : MCValOp.getExpr();
660
661 // Very small immediates can be expressed directly as a single `or`.
662 if (IsImm && isInt<13>(ImmValue)) {
663 // or rd, val, rd
664 Instructions.push_back(MCInstBuilder(SP::ORri)
665 .addReg(MCRegOp.getReg())
666 .addReg(Sparc::G0)
667 .addExpr(ValExpr));
668 return false;
669 }
670
671 // Otherwise, first we set the lower half of the register.
672
673 // sethi %hi(val), rd
674 Instructions.push_back(
675 MCInstBuilder(SP::SETHIi)
676 .addReg(MCRegOp.getReg())
677 .addExpr(adjustPICRelocation(SparcMCExpr::VK_Sparc_HI, ValExpr)));
678 // or rd, %lo(val), rd
679 Instructions.push_back(
680 MCInstBuilder(SP::ORri)
681 .addReg(MCRegOp.getReg())
682 .addReg(MCRegOp.getReg())
683 .addExpr(adjustPICRelocation(SparcMCExpr::VK_Sparc_LO, ValExpr)));
684
685 // Small positive immediates can be expressed as a single `sethi`+`or`
686 // combination, so we can just return here.
687 if (IsImm && isUInt<32>(ImmValue))
688 return false;
689
690 // For bigger immediates, we need to generate the upper half, then shift and
691 // merge it with the lower half that has just been generated above.
692
693 // sethi %hh(val), tmp
694 Instructions.push_back(
695 MCInstBuilder(SP::SETHIi)
696 .addReg(MCTmpOp.getReg())
697 .addExpr(adjustPICRelocation(SparcMCExpr::VK_Sparc_HH, ValExpr)));
698 // or tmp, %hm(val), tmp
699 Instructions.push_back(
700 MCInstBuilder(SP::ORri)
701 .addReg(MCTmpOp.getReg())
702 .addReg(MCTmpOp.getReg())
703 .addExpr(adjustPICRelocation(SparcMCExpr::VK_Sparc_HM, ValExpr)));
704 // sllx tmp, 32, tmp
705 Instructions.push_back(MCInstBuilder(SP::SLLXri)
706 .addReg(MCTmpOp.getReg())
707 .addReg(MCTmpOp.getReg())
708 .addImm(32));
709 // or tmp, rd, rd
710 Instructions.push_back(MCInstBuilder(SP::ORrr)
711 .addReg(MCRegOp.getReg())
712 .addReg(MCTmpOp.getReg())
713 .addReg(MCRegOp.getReg()));
714
715 return false;
716}
717
718bool SparcAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
720 MCStreamer &Out,
722 bool MatchingInlineAsm) {
723 MCInst Inst;
725 unsigned MatchResult = MatchInstructionImpl(Operands, Inst, ErrorInfo,
726 MatchingInlineAsm);
727 switch (MatchResult) {
728 case Match_Success: {
729 switch (Inst.getOpcode()) {
730 default:
731 Inst.setLoc(IDLoc);
732 Instructions.push_back(Inst);
733 break;
734 case SP::SET:
735 if (expandSET(Inst, IDLoc, Instructions))
736 return true;
737 break;
738 case SP::SETX:
739 if (expandSETX(Inst, IDLoc, Instructions))
740 return true;
741 break;
742 }
743
744 for (const MCInst &I : Instructions) {
745 Out.emitInstruction(I, getSTI());
746 }
747 return false;
748 }
749
750 case Match_MissingFeature:
751 return Error(IDLoc,
752 "instruction requires a CPU feature not currently enabled");
753
754 case Match_InvalidOperand: {
755 SMLoc ErrorLoc = IDLoc;
756 if (ErrorInfo != ~0ULL) {
757 if (ErrorInfo >= Operands.size())
758 return Error(IDLoc, "too few operands for instruction");
759
760 ErrorLoc = ((SparcOperand &)*Operands[ErrorInfo]).getStartLoc();
761 if (ErrorLoc == SMLoc())
762 ErrorLoc = IDLoc;
763 }
764
765 return Error(ErrorLoc, "invalid operand for instruction");
766 }
767 case Match_MnemonicFail:
768 return Error(IDLoc, "invalid instruction mnemonic");
769 }
770 llvm_unreachable("Implement any new match types added!");
771}
772
773bool SparcAsmParser::parseRegister(MCRegister &Reg, SMLoc &StartLoc,
774 SMLoc &EndLoc) {
775 if (!tryParseRegister(Reg, StartLoc, EndLoc).isSuccess())
776 return Error(StartLoc, "invalid register name");
777 return false;
778}
779
780ParseStatus SparcAsmParser::tryParseRegister(MCRegister &Reg, SMLoc &StartLoc,
781 SMLoc &EndLoc) {
782 const AsmToken &Tok = Parser.getTok();
783 StartLoc = Tok.getLoc();
784 EndLoc = Tok.getEndLoc();
785 Reg = Sparc::NoRegister;
786 if (getLexer().getKind() != AsmToken::Percent)
788 Parser.Lex();
789 unsigned RegKind = SparcOperand::rk_None;
790 Reg = matchRegisterName(Tok, RegKind);
791 if (Reg) {
792 Parser.Lex();
794 }
795
796 getLexer().UnLex(Tok);
798}
799
800static void applyMnemonicAliases(StringRef &Mnemonic,
801 const FeatureBitset &Features,
802 unsigned VariantID);
803
804bool SparcAsmParser::ParseInstruction(ParseInstructionInfo &Info,
805 StringRef Name, SMLoc NameLoc,
807
808 // First operand in MCInst is instruction mnemonic.
809 Operands.push_back(SparcOperand::CreateToken(Name, NameLoc));
810
811 // apply mnemonic aliases, if any, so that we can parse operands correctly.
812 applyMnemonicAliases(Name, getAvailableFeatures(), 0);
813
814 if (getLexer().isNot(AsmToken::EndOfStatement)) {
815 // Read the first operand.
816 if (getLexer().is(AsmToken::Comma)) {
817 if (!parseBranchModifiers(Operands).isSuccess()) {
818 SMLoc Loc = getLexer().getLoc();
819 return Error(Loc, "unexpected token");
820 }
821 }
822 if (!parseOperand(Operands, Name).isSuccess()) {
823 SMLoc Loc = getLexer().getLoc();
824 return Error(Loc, "unexpected token");
825 }
826
827 while (getLexer().is(AsmToken::Comma) || getLexer().is(AsmToken::Plus)) {
828 if (getLexer().is(AsmToken::Plus)) {
829 // Plus tokens are significant in software_traps (p83, sparcv8.pdf). We must capture them.
830 Operands.push_back(SparcOperand::CreateToken("+", Parser.getTok().getLoc()));
831 }
832 Parser.Lex(); // Eat the comma or plus.
833 // Parse and remember the operand.
834 if (!parseOperand(Operands, Name).isSuccess()) {
835 SMLoc Loc = getLexer().getLoc();
836 return Error(Loc, "unexpected token");
837 }
838 }
839 }
840 if (getLexer().isNot(AsmToken::EndOfStatement)) {
841 SMLoc Loc = getLexer().getLoc();
842 return Error(Loc, "unexpected token");
843 }
844 Parser.Lex(); // Consume the EndOfStatement.
845 return false;
846}
847
848ParseStatus SparcAsmParser::parseDirective(AsmToken DirectiveID) {
849 StringRef IDVal = DirectiveID.getString();
850
851 if (IDVal == ".register") {
852 // For now, ignore .register directive.
853 Parser.eatToEndOfStatement();
855 }
856 if (IDVal == ".proc") {
857 // For compatibility, ignore this directive.
858 // (It's supposed to be an "optimization" in the Sun assembler)
859 Parser.eatToEndOfStatement();
861 }
862
863 // Let the MC layer to handle other directives.
865}
866
867ParseStatus SparcAsmParser::parseMEMOperand(OperandVector &Operands) {
868 SMLoc S, E;
869
870 std::unique_ptr<SparcOperand> LHS;
871 if (!parseSparcAsmOperand(LHS).isSuccess())
873
874 // Single immediate operand
875 if (LHS->isImm()) {
876 Operands.push_back(SparcOperand::MorphToMEMri(Sparc::G0, std::move(LHS)));
878 }
879
880 if (!LHS->isIntReg())
881 return Error(LHS->getStartLoc(), "invalid register kind for this operand");
882
883 AsmToken Tok = getLexer().getTok();
884 // The plus token may be followed by a register or an immediate value, the
885 // minus one is always interpreted as sign for the immediate value
886 if (Tok.is(AsmToken::Plus) || Tok.is(AsmToken::Minus)) {
888
889 std::unique_ptr<SparcOperand> RHS;
890 if (!parseSparcAsmOperand(RHS).isSuccess())
892
893 if (RHS->isReg() && !RHS->isIntReg())
894 return Error(RHS->getStartLoc(),
895 "invalid register kind for this operand");
896
897 Operands.push_back(
898 RHS->isImm()
899 ? SparcOperand::MorphToMEMri(LHS->getReg(), std::move(RHS))
900 : SparcOperand::MorphToMEMrr(LHS->getReg(), std::move(RHS)));
901
903 }
904
905 Operands.push_back(SparcOperand::CreateMEMr(LHS->getReg(), S, E));
907}
908
909template <unsigned N>
910ParseStatus SparcAsmParser::parseShiftAmtImm(OperandVector &Operands) {
911 SMLoc S = Parser.getTok().getLoc();
913
914 // This is a register, not an immediate
915 if (getLexer().getKind() == AsmToken::Percent)
917
918 const MCExpr *Expr;
919 if (getParser().parseExpression(Expr))
921
922 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
923 if (!CE)
924 return Error(S, "constant expression expected");
925
926 if (!isUInt<N>(CE->getValue()))
927 return Error(S, "immediate shift value out of range");
928
929 Operands.push_back(SparcOperand::CreateImm(Expr, S, E));
931}
932
933template <SparcAsmParser::TailRelocKind Kind>
934ParseStatus SparcAsmParser::parseTailRelocSym(OperandVector &Operands) {
935 SMLoc S = getLoc();
937
938 auto MatchesKind = [](SparcMCExpr::VariantKind VK) -> bool {
939 switch (Kind) {
940 case TailRelocKind::Load_GOT:
941 // Non-TLS relocations on ld (or ldx).
942 // ld [%rr + %rr], %rr, %rel(sym)
944 case TailRelocKind::Add_TLS:
945 // TLS relocations on add.
946 // add %rr, %rr, %rr, %rel(sym)
947 switch (VK) {
952 return true;
953 default:
954 return false;
955 }
956 case TailRelocKind::Load_TLS:
957 // TLS relocations on ld (or ldx).
958 // ld[x] %addr, %rr, %rel(sym)
959 switch (VK) {
962 return true;
963 default:
964 return false;
965 }
966 case TailRelocKind::Call_TLS:
967 // TLS relocations on call.
968 // call sym, %rel(sym)
969 switch (VK) {
972 return true;
973 default:
974 return false;
975 }
976 }
977 llvm_unreachable("Unhandled SparcAsmParser::TailRelocKind enum");
978 };
979
980 if (getLexer().getKind() != AsmToken::Percent)
981 return Error(getLoc(), "expected '%' for operand modifier");
982
983 const AsmToken Tok = Parser.getTok();
984 getParser().Lex(); // Eat '%'
985
986 if (getLexer().getKind() != AsmToken::Identifier)
987 return Error(getLoc(), "expected valid identifier for operand modifier");
988
989 StringRef Name = getParser().getTok().getIdentifier();
992 return Error(getLoc(), "invalid operand modifier");
993
994 if (!MatchesKind(VK)) {
995 // Did not match the specified set of relocation types, put '%' back.
996 getLexer().UnLex(Tok);
998 }
999
1000 Parser.Lex(); // Eat the identifier.
1001 if (getLexer().getKind() != AsmToken::LParen)
1002 return Error(getLoc(), "expected '('");
1003
1004 getParser().Lex(); // Eat '('
1005 const MCExpr *SubExpr;
1006 if (getParser().parseParenExpression(SubExpr, E))
1007 return ParseStatus::Failure;
1008
1009 const MCExpr *Val = adjustPICRelocation(VK, SubExpr);
1010 Operands.push_back(SparcOperand::CreateImm(Val, S, E));
1011 return ParseStatus::Success;
1012}
1013
1014ParseStatus SparcAsmParser::parseMembarTag(OperandVector &Operands) {
1015 SMLoc S = Parser.getTok().getLoc();
1016 const MCExpr *EVal;
1017 int64_t ImmVal = 0;
1018
1019 std::unique_ptr<SparcOperand> Mask;
1020 if (parseSparcAsmOperand(Mask).isSuccess()) {
1021 if (!Mask->isImm() || !Mask->getImm()->evaluateAsAbsolute(ImmVal) ||
1022 ImmVal < 0 || ImmVal > 127)
1023 return Error(S, "invalid membar mask number");
1024 }
1025
1026 while (getLexer().getKind() == AsmToken::Hash) {
1027 SMLoc TagStart = getLexer().getLoc();
1028 Parser.Lex(); // Eat the '#'.
1029 unsigned MaskVal = StringSwitch<unsigned>(Parser.getTok().getString())
1030 .Case("LoadLoad", 0x1)
1031 .Case("StoreLoad", 0x2)
1032 .Case("LoadStore", 0x4)
1033 .Case("StoreStore", 0x8)
1034 .Case("Lookaside", 0x10)
1035 .Case("MemIssue", 0x20)
1036 .Case("Sync", 0x40)
1037 .Default(0);
1038
1039 Parser.Lex(); // Eat the identifier token.
1040
1041 if (!MaskVal)
1042 return Error(TagStart, "unknown membar tag");
1043
1044 ImmVal |= MaskVal;
1045
1046 if (getLexer().getKind() == AsmToken::Pipe)
1047 Parser.Lex(); // Eat the '|'.
1048 }
1049
1050 EVal = MCConstantExpr::create(ImmVal, getContext());
1051 SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1052 Operands.push_back(SparcOperand::CreateImm(EVal, S, E));
1053 return ParseStatus::Success;
1054}
1055
1056ParseStatus SparcAsmParser::parseASITag(OperandVector &Operands) {
1057 SMLoc S = Parser.getTok().getLoc();
1058 SMLoc E = Parser.getTok().getEndLoc();
1059 int64_t ASIVal = 0;
1060
1061 if (is64Bit() && (getLexer().getKind() == AsmToken::Hash)) {
1062 // For now we only support named tags for 64-bit/V9 systems.
1063 // TODO: add support for 32-bit/V8 systems.
1064 SMLoc TagStart = getLexer().peekTok(false).getLoc();
1065 Parser.Lex(); // Eat the '#'.
1066 auto ASIName = Parser.getTok().getString();
1067 auto ASITag = SparcASITag::lookupASITagByName(ASIName);
1068 if (!ASITag)
1069 ASITag = SparcASITag::lookupASITagByAltName(ASIName);
1070 Parser.Lex(); // Eat the identifier token.
1071
1072 if (!ASITag)
1073 return Error(TagStart, "unknown ASI tag");
1074
1075 ASIVal = ASITag->Encoding;
1076 } else if (!getParser().parseAbsoluteExpression(ASIVal)) {
1077 if (!isUInt<8>(ASIVal))
1078 return Error(S, "invalid ASI number, must be between 0 and 255");
1079 } else {
1080 return Error(
1081 S, is64Bit()
1082 ? "malformed ASI tag, must be %asi, a constant integer "
1083 "expression, or a named tag"
1084 : "malformed ASI tag, must be a constant integer expression");
1085 }
1086
1087 Operands.push_back(SparcOperand::CreateASITag(ASIVal, S, E));
1088 return ParseStatus::Success;
1089}
1090
1091ParseStatus SparcAsmParser::parseCallTarget(OperandVector &Operands) {
1092 SMLoc S = Parser.getTok().getLoc();
1094
1095 switch (getLexer().getKind()) {
1096 default:
1097 return ParseStatus::NoMatch;
1098 case AsmToken::LParen:
1099 case AsmToken::Integer:
1101 case AsmToken::Dot:
1102 break;
1103 }
1104
1105 const MCExpr *DestValue;
1106 if (getParser().parseExpression(DestValue))
1107 return ParseStatus::NoMatch;
1108
1109 bool IsPic = getContext().getObjectFileInfo()->isPositionIndependent();
1112
1113 const MCExpr *DestExpr = SparcMCExpr::create(Kind, DestValue, getContext());
1114 Operands.push_back(SparcOperand::CreateImm(DestExpr, S, E));
1115 return ParseStatus::Success;
1116}
1117
1118ParseStatus SparcAsmParser::parseOperand(OperandVector &Operands,
1119 StringRef Mnemonic) {
1120
1121 ParseStatus Res = MatchOperandParserImpl(Operands, Mnemonic);
1122
1123 // If there wasn't a custom match, try the generic matcher below. Otherwise,
1124 // there was a match, but an error occurred, in which case, just return that
1125 // the operand parsing failed.
1126 if (Res.isSuccess() || Res.isFailure())
1127 return Res;
1128
1129 if (getLexer().is(AsmToken::LBrac)) {
1130 // Memory operand
1131 Operands.push_back(SparcOperand::CreateToken("[",
1132 Parser.getTok().getLoc()));
1133 Parser.Lex(); // Eat the [
1134
1135 if (Mnemonic == "cas" || Mnemonic == "casl" || Mnemonic == "casa" ||
1136 Mnemonic == "casx" || Mnemonic == "casxl" || Mnemonic == "casxa") {
1137 SMLoc S = Parser.getTok().getLoc();
1138 if (getLexer().getKind() != AsmToken::Percent)
1139 return ParseStatus::NoMatch;
1140 Parser.Lex(); // eat %
1141
1142 unsigned RegKind;
1143 MCRegister Reg = matchRegisterName(Parser.getTok(), RegKind);
1144 if (!Reg)
1145 return ParseStatus::NoMatch;
1146
1147 Parser.Lex(); // Eat the identifier token.
1149 Operands.push_back(SparcOperand::CreateReg(Reg, RegKind, S, E));
1151 } else {
1152 Res = parseMEMOperand(Operands);
1153 }
1154
1155 if (!Res.isSuccess())
1156 return Res;
1157
1158 if (!getLexer().is(AsmToken::RBrac))
1159 return ParseStatus::Failure;
1160
1161 Operands.push_back(SparcOperand::CreateToken("]",
1162 Parser.getTok().getLoc()));
1163 Parser.Lex(); // Eat the ]
1164
1165 // Parse an optional address-space identifier after the address.
1166 // This will be either an immediate constant expression, or, on 64-bit
1167 // processors, the %asi register.
1168 if (is64Bit() && getLexer().is(AsmToken::Percent)) {
1169 SMLoc S = Parser.getTok().getLoc();
1170 Parser.Lex(); // Eat the %.
1171 const AsmToken Tok = Parser.getTok();
1172 if (Tok.is(AsmToken::Identifier) && Tok.getString() == "asi") {
1173 // Here we patch the MEM operand from [base + %g0] into [base + 0]
1174 // as memory operations with ASI tag stored in %asi register needs
1175 // to use immediate offset. We need to do this because Reg addressing
1176 // will be parsed as Reg+G0 initially.
1177 // This allows forms such as `ldxa [%o0] %asi, %o0` to parse correctly.
1178 SparcOperand &OldMemOp = (SparcOperand &)*Operands[Operands.size() - 2];
1179 if (OldMemOp.isMEMrr()) {
1180 if (OldMemOp.getMemOffsetReg() != Sparc::G0) {
1181 return Error(S, "invalid operand for instruction");
1182 }
1183 Operands[Operands.size() - 2] = SparcOperand::MorphToMEMri(
1184 OldMemOp.getMemBase(),
1185 SparcOperand::CreateImm(MCConstantExpr::create(0, getContext()),
1186 OldMemOp.getStartLoc(),
1187 OldMemOp.getEndLoc()));
1188 }
1189 Parser.Lex(); // Eat the identifier.
1190 // In this context, we convert the register operand into
1191 // a plain "%asi" token since the register access is already
1192 // implicit in the instruction definition and encoding.
1193 // See LoadASI/StoreASI in SparcInstrInfo.td.
1194 Operands.push_back(SparcOperand::CreateToken("%asi", S));
1195 return ParseStatus::Success;
1196 }
1197
1198 return Error(S, "malformed ASI tag, must be %asi, a constant integer "
1199 "expression, or a named tag");
1200 }
1201
1202 // If we're not at the end of statement and the next token is not a comma,
1203 // then it is an immediate ASI value.
1204 if (getLexer().isNot(AsmToken::EndOfStatement) &&
1205 getLexer().isNot(AsmToken::Comma))
1206 return parseASITag(Operands);
1207 return ParseStatus::Success;
1208 }
1209
1210 std::unique_ptr<SparcOperand> Op;
1211
1212 Res = parseSparcAsmOperand(Op, (Mnemonic == "call"));
1213 if (!Res.isSuccess() || !Op)
1214 return ParseStatus::Failure;
1215
1216 // Push the parsed operand into the list of operands
1217 Operands.push_back(std::move(Op));
1218
1219 return ParseStatus::Success;
1220}
1221
1223SparcAsmParser::parseSparcAsmOperand(std::unique_ptr<SparcOperand> &Op,
1224 bool isCall) {
1225 SMLoc S = Parser.getTok().getLoc();
1226 SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1227 const MCExpr *EVal;
1228
1229 Op = nullptr;
1230 switch (getLexer().getKind()) {
1231 default: break;
1232
1233 case AsmToken::Percent: {
1234 Parser.Lex(); // Eat the '%'.
1235 unsigned RegKind;
1236 if (MCRegister Reg = matchRegisterName(Parser.getTok(), RegKind)) {
1237 StringRef Name = Parser.getTok().getString();
1238 Parser.Lex(); // Eat the identifier token.
1239 E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1240 if (Reg == Sparc::ICC && Name == "xcc")
1241 Op = SparcOperand::CreateToken("%xcc", S);
1242 else
1243 Op = SparcOperand::CreateReg(Reg, RegKind, S, E);
1244 break;
1245 }
1246 if (matchSparcAsmModifiers(EVal, E)) {
1247 E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1248 Op = SparcOperand::CreateImm(EVal, S, E);
1249 }
1250 break;
1251 }
1252
1253 case AsmToken::Plus:
1254 case AsmToken::Minus:
1255 case AsmToken::Integer:
1256 case AsmToken::LParen:
1257 case AsmToken::Dot:
1259 if (getParser().parseExpression(EVal, E))
1260 break;
1261
1262 int64_t Res;
1263 if (!EVal->evaluateAsAbsolute(Res)) {
1265
1266 if (getContext().getObjectFileInfo()->isPositionIndependent()) {
1267 if (isCall)
1269 else
1271 }
1272 EVal = SparcMCExpr::create(Kind, EVal, getContext());
1273 }
1274 Op = SparcOperand::CreateImm(EVal, S, E);
1275 break;
1276 }
1278}
1279
1280ParseStatus SparcAsmParser::parseBranchModifiers(OperandVector &Operands) {
1281 // parse (,a|,pn|,pt)+
1282
1283 while (getLexer().is(AsmToken::Comma)) {
1284 Parser.Lex(); // Eat the comma
1285
1286 if (!getLexer().is(AsmToken::Identifier))
1287 return ParseStatus::Failure;
1288 StringRef modName = Parser.getTok().getString();
1289 if (modName == "a" || modName == "pn" || modName == "pt") {
1290 Operands.push_back(SparcOperand::CreateToken(modName,
1291 Parser.getTok().getLoc()));
1292 Parser.Lex(); // eat the identifier.
1293 }
1294 }
1295 return ParseStatus::Success;
1296}
1297
1298#define GET_REGISTER_MATCHER
1299#include "SparcGenAsmMatcher.inc"
1300
1301MCRegister SparcAsmParser::matchRegisterName(const AsmToken &Tok,
1302 unsigned &RegKind) {
1303 RegKind = SparcOperand::rk_None;
1304 if (!Tok.is(AsmToken::Identifier))
1305 return SP::NoRegister;
1306
1307 StringRef Name = Tok.getString();
1308 MCRegister Reg = MatchRegisterName(Name.lower());
1309 if (!Reg)
1310 Reg = MatchRegisterAltName(Name.lower());
1311
1312 if (Reg) {
1313 // Some registers have identical spellings. The generated matcher might
1314 // have chosen one or another spelling, e.g. "%fp" or "%i6" might have been
1315 // matched to either SP::I6 or SP::I6_I7. Other parts of SparcAsmParser
1316 // are not prepared for this, so we do some canonicalization.
1317
1318 // See the note in SparcRegisterInfo.td near ASRRegs register class.
1319 if (Reg == SP::ASR4 && Name == "tick") {
1320 RegKind = SparcOperand::rk_Special;
1321 return SP::TICK;
1322 }
1323
1324 if (MRI.getRegClass(SP::IntRegsRegClassID).contains(Reg)) {
1325 RegKind = SparcOperand::rk_IntReg;
1326 return Reg;
1327 }
1328 if (MRI.getRegClass(SP::FPRegsRegClassID).contains(Reg)) {
1329 RegKind = SparcOperand::rk_FloatReg;
1330 return Reg;
1331 }
1332 if (MRI.getRegClass(SP::CoprocRegsRegClassID).contains(Reg)) {
1333 RegKind = SparcOperand::rk_CoprocReg;
1334 return Reg;
1335 }
1336
1337 // Canonicalize G0_G1 ... G30_G31 etc. to G0 ... G30.
1338 if (MRI.getRegClass(SP::IntPairRegClassID).contains(Reg)) {
1339 RegKind = SparcOperand::rk_IntReg;
1340 return MRI.getSubReg(Reg, SP::sub_even);
1341 }
1342
1343 // Canonicalize D0 ... D15 to F0 ... F30.
1344 if (MRI.getRegClass(SP::DFPRegsRegClassID).contains(Reg)) {
1345 // D16 ... D31 do not have sub-registers.
1346 if (MCRegister SubReg = MRI.getSubReg(Reg, SP::sub_even)) {
1347 RegKind = SparcOperand::rk_FloatReg;
1348 return SubReg;
1349 }
1350 RegKind = SparcOperand::rk_DoubleReg;
1351 return Reg;
1352 }
1353
1354 // The generated matcher does not currently return QFP registers.
1355 // If it changes, we will need to handle them in a similar way.
1356 assert(!MRI.getRegClass(SP::QFPRegsRegClassID).contains(Reg));
1357
1358 // Canonicalize C0_C1 ... C30_C31 to C0 ... C30.
1359 if (MRI.getRegClass(SP::CoprocPairRegClassID).contains(Reg)) {
1360 RegKind = SparcOperand::rk_CoprocReg;
1361 return MRI.getSubReg(Reg, SP::sub_even);
1362 }
1363
1364 // Other registers do not need special handling.
1365 RegKind = SparcOperand::rk_Special;
1366 return Reg;
1367 }
1368
1369 // If we still have no match, try custom parsing.
1370 // Not all registers and their spellings are modeled in td files.
1371
1372 // %r0 - %r31
1373 int64_t RegNo = 0;
1374 if (Name.starts_with_insensitive("r") &&
1375 !Name.substr(1, 2).getAsInteger(10, RegNo) && RegNo < 31) {
1376 RegKind = SparcOperand::rk_IntReg;
1377 return IntRegs[RegNo];
1378 }
1379
1380 if (Name.equals("xcc")) {
1381 // FIXME:: check 64bit.
1382 RegKind = SparcOperand::rk_Special;
1383 return SP::ICC;
1384 }
1385
1386 // JPS1 extension - aliases for ASRs
1387 // Section A.51 - Read State Register
1388 if (Name.equals("pcr")) {
1389 RegKind = SparcOperand::rk_Special;
1390 return SP::ASR16;
1391 }
1392
1393 if (Name.equals("pic")) {
1394 RegKind = SparcOperand::rk_Special;
1395 return SP::ASR17;
1396 }
1397 if (Name.equals("dcr")) {
1398 RegKind = SparcOperand::rk_Special;
1399 return SP::ASR18;
1400 }
1401 if (Name.equals("gsr")) {
1402 RegKind = SparcOperand::rk_Special;
1403 return SP::ASR19;
1404 }
1405 if (Name.equals("softint")) {
1406 RegKind = SparcOperand::rk_Special;
1407 return SP::ASR22;
1408 }
1409 if (Name.equals("tick_cmpr")) {
1410 RegKind = SparcOperand::rk_Special;
1411 return SP::ASR23;
1412 }
1413 if (Name.equals("stick") || Name.equals("sys_tick")) {
1414 RegKind = SparcOperand::rk_Special;
1415 return SP::ASR24;
1416 }
1417 if (Name.equals("stick_cmpr") || Name.equals("sys_tick_cmpr")) {
1418 RegKind = SparcOperand::rk_Special;
1419 return SP::ASR25;
1420 }
1421
1422 return SP::NoRegister;
1423}
1424
1425// Determine if an expression contains a reference to the symbol
1426// "_GLOBAL_OFFSET_TABLE_".
1427static bool hasGOTReference(const MCExpr *Expr) {
1428 switch (Expr->getKind()) {
1429 case MCExpr::Target:
1430 if (const SparcMCExpr *SE = dyn_cast<SparcMCExpr>(Expr))
1431 return hasGOTReference(SE->getSubExpr());
1432 break;
1433
1434 case MCExpr::Constant:
1435 break;
1436
1437 case MCExpr::Binary: {
1438 const MCBinaryExpr *BE = cast<MCBinaryExpr>(Expr);
1439 return hasGOTReference(BE->getLHS()) || hasGOTReference(BE->getRHS());
1440 }
1441
1442 case MCExpr::SymbolRef: {
1443 const MCSymbolRefExpr &SymRef = *cast<MCSymbolRefExpr>(Expr);
1444 return (SymRef.getSymbol().getName() == "_GLOBAL_OFFSET_TABLE_");
1445 }
1446
1447 case MCExpr::Unary:
1448 return hasGOTReference(cast<MCUnaryExpr>(Expr)->getSubExpr());
1449 }
1450 return false;
1451}
1452
1453const SparcMCExpr *
1454SparcAsmParser::adjustPICRelocation(SparcMCExpr::VariantKind VK,
1455 const MCExpr *subExpr) {
1456 // When in PIC mode, "%lo(...)" and "%hi(...)" behave differently.
1457 // If the expression refers contains _GLOBAL_OFFSET_TABLE, it is
1458 // actually a %pc10 or %pc22 relocation. Otherwise, they are interpreted
1459 // as %got10 or %got22 relocation.
1460
1461 if (getContext().getObjectFileInfo()->isPositionIndependent()) {
1462 switch(VK) {
1463 default: break;
1467 break;
1471 break;
1472 }
1473 }
1474
1475 return SparcMCExpr::create(VK, subExpr, getContext());
1476}
1477
1478bool SparcAsmParser::matchSparcAsmModifiers(const MCExpr *&EVal,
1479 SMLoc &EndLoc) {
1480 AsmToken Tok = Parser.getTok();
1481 if (!Tok.is(AsmToken::Identifier))
1482 return false;
1483
1484 StringRef name = Tok.getString();
1485
1487 switch (VK) {
1489 Error(getLoc(), "invalid operand modifier");
1490 return false;
1491
1501 // These are special-cased at tablegen level.
1502 return false;
1503
1504 default:
1505 break;
1506 }
1507
1508 Parser.Lex(); // Eat the identifier.
1509 if (Parser.getTok().getKind() != AsmToken::LParen)
1510 return false;
1511
1512 Parser.Lex(); // Eat the LParen token.
1513 const MCExpr *subExpr;
1514 if (Parser.parseParenExpression(subExpr, EndLoc))
1515 return false;
1516
1517 EVal = adjustPICRelocation(VK, subExpr);
1518 return true;
1519}
1520
1525}
1526
1527#define GET_MATCHER_IMPLEMENTATION
1528#include "SparcGenAsmMatcher.inc"
1529
1530unsigned SparcAsmParser::validateTargetOperandClass(MCParsedAsmOperand &GOp,
1531 unsigned Kind) {
1532 SparcOperand &Op = (SparcOperand &)GOp;
1533 if (Op.isFloatOrDoubleReg()) {
1534 switch (Kind) {
1535 default: break;
1536 case MCK_DFPRegs:
1537 if (!Op.isFloatReg() || SparcOperand::MorphToDoubleReg(Op))
1539 break;
1540 case MCK_QFPRegs:
1541 if (SparcOperand::MorphToQuadReg(Op))
1543 break;
1544 }
1545 }
1546 if (Op.isIntReg() && Kind == MCK_IntPair) {
1547 if (SparcOperand::MorphToIntPairReg(Op))
1549 }
1550 if (Op.isCoprocReg() && Kind == MCK_CoprocPair) {
1551 if (SparcOperand::MorphToCoprocPairReg(Op))
1553 }
1554 return Match_InvalidOperand;
1555}
unsigned SubReg
unsigned const MachineRegisterInfo * MRI
static MCRegister MatchRegisterName(StringRef Name)
static bool addCallTargetOperands(MachineInstrBuilder &CallInst, MachineIRBuilder &MIRBuilder, AMDGPUCallLowering::CallLoweringInfo &Info)
static bool isNot(const MachineRegisterInfo &MRI, const MachineInstr &MI)
static MCRegister MatchRegisterAltName(StringRef Name)
Maps from the set of all alternative registernames to a register number.
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_EXTERNAL_VISIBILITY
Definition: Compiler.h:135
std::string Name
static LVOptions Options
Definition: LVOptions.cpp:25
#define I(x, y, z)
Definition: MD5.cpp:58
mir Rename Register Operands
unsigned Reg
static unsigned getReg(const MCDisassembler *D, unsigned RC, unsigned RegNo)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static const char * name
Definition: SMEABIPass.cpp:49
This file contains some templates that are useful if you are working with the STL at all.
raw_pwrite_stream & OS
This file defines the SmallVector class.
static const MCPhysReg DoubleRegs[32]
static bool hasGOTReference(const MCExpr *Expr)
static const MCPhysReg IntRegs[32]
static void applyMnemonicAliases(StringRef &Mnemonic, const FeatureBitset &Features, unsigned VariantID)
LLVM_EXTERNAL_VISIBILITY void LLVMInitializeSparcAsmParser()
static const MCPhysReg IntPairRegs[]
static const MCPhysReg QuadFPRegs[32]
static const MCPhysReg CoprocPairRegs[]
static bool is64Bit(const char *name)
Value * RHS
Value * LHS
Target independent representation for an assembler token.
Definition: MCAsmMacro.h:21
SMLoc getLoc() const
Definition: MCAsmLexer.cpp:26
StringRef getString() const
Get the string for the current token, this includes all characters (for example, the quotes on string...
Definition: MCAsmMacro.h:110
bool is(TokenKind K) const
Definition: MCAsmMacro.h:82
TokenKind getKind() const
Definition: MCAsmMacro.h:81
SMLoc getEndLoc() const
Definition: MCAsmLexer.cpp:30
This class represents an Operation in the Expression.
Base class for user error types.
Definition: Error.h:352
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
Container class for subtarget features.
Generic assembler parser interface, for use by target specific assembly parsers.
Definition: MCAsmParser.h:123
virtual void eatToEndOfStatement()=0
Skip to the end of the current statement, for error recovery.
const AsmToken & getTok() const
Get the current AsmToken from the stream.
Definition: MCAsmParser.cpp:40
virtual bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc)=0
Parse an arbitrary expression, assuming that an initial '(' has already been consumed.
bool parseOptionalToken(AsmToken::TokenKind T)
Attempt to parse and consume token, returning true on success.
Definition: MCAsmParser.cpp:80
virtual const AsmToken & Lex()=0
Get the next AsmToken in the stream, possibly handling file inclusion first.
virtual void addAliasForDirective(StringRef Directive, StringRef Alias)=0
Binary assembler expressions.
Definition: MCExpr.h:492
const MCExpr * getLHS() const
Get the left-hand side expression of the binary operator.
Definition: MCExpr.h:639
const MCExpr * getRHS() const
Get the right-hand side expression of the binary operator.
Definition: MCExpr.h:642
static const MCConstantExpr * create(int64_t Value, MCContext &Ctx, bool PrintInHex=false, unsigned SizeInBytes=0)
Definition: MCExpr.cpp:194
Base class for the full range of assembler expressions which are needed for parsing.
Definition: MCExpr.h:35
@ Unary
Unary expressions.
Definition: MCExpr.h:41
@ Constant
Constant expressions.
Definition: MCExpr.h:39
@ SymbolRef
References to labels and assigned expressions.
Definition: MCExpr.h:40
@ Target
Target specific expression.
Definition: MCExpr.h:42
@ Binary
Binary expressions.
Definition: MCExpr.h:38
ExprKind getKind() const
Definition: MCExpr.h:81
MCInstBuilder & addReg(unsigned Reg)
Add a new register operand.
Definition: MCInstBuilder.h:37
MCInstBuilder & addImm(int64_t Val)
Add a new integer immediate operand.
Definition: MCInstBuilder.h:43
MCInstBuilder & addExpr(const MCExpr *Val)
Add a new MCExpr operand.
Definition: MCInstBuilder.h:61
Instances of this class represent a single low-level machine instruction.
Definition: MCInst.h:184
void setLoc(SMLoc loc)
Definition: MCInst.h:203
unsigned getOpcode() const
Definition: MCInst.h:198
void addOperand(const MCOperand Op)
Definition: MCInst.h:210
void setOpcode(unsigned Op)
Definition: MCInst.h:197
const MCOperand & getOperand(unsigned i) const
Definition: MCInst.h:206
Interface to description of machine instruction set.
Definition: MCInstrInfo.h:26
Instances of this class represent operands of the MCInst class.
Definition: MCInst.h:36
static MCOperand createReg(unsigned Reg)
Definition: MCInst.h:134
static MCOperand createExpr(const MCExpr *Val)
Definition: MCInst.h:162
int64_t getImm() const
Definition: MCInst.h:80
static MCOperand createImm(int64_t Val)
Definition: MCInst.h:141
bool isImm() const
Definition: MCInst.h:62
unsigned getReg() const
Returns the register number.
Definition: MCInst.h:69
bool isReg() const
Definition: MCInst.h:61
const MCExpr * getExpr() const
Definition: MCInst.h:114
bool isExpr() const
Definition: MCInst.h:65
MCParsedAsmOperand - This abstract class represents a source-level assembly instruction operand.
virtual SMLoc getStartLoc() const =0
getStartLoc - Get the location of the first token of this operand.
virtual bool isReg() const =0
isReg - Is this a register operand?
virtual bool isMem() const =0
isMem - Is this a memory operand?
virtual MCRegister getReg() const =0
virtual void print(raw_ostream &OS) const =0
print - Print a debug representation of the operand to the given stream.
virtual bool isToken() const =0
isToken - Is this a token operand?
virtual bool isImm() const =0
isImm - Is this an immediate operand?
virtual SMLoc getEndLoc() const =0
getEndLoc - Get the location of the last token of this operand.
MCRegisterInfo base class - We assume that the target defines a static array of MCRegisterDesc object...
Wrapper class representing physical registers. Should be passed by value.
Definition: MCRegister.h:33
Streaming machine code generation interface.
Definition: MCStreamer.h:212
virtual void emitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI)
Emit the given Instruction into the current section.
Generic base class for all target subtargets.
const Triple & getTargetTriple() const
Represent a reference to a symbol from inside an expression.
Definition: MCExpr.h:192
const MCSymbol & getSymbol() const
Definition: MCExpr.h:410
StringRef getName() const
getName - Get the symbol name.
Definition: MCSymbol.h:205
MCTargetAsmParser - Generic interface to target specific assembly parsers.
virtual ParseStatus parseDirective(AsmToken DirectiveID)
Parses a target-specific assembler directive.
virtual bool parseRegister(MCRegister &Reg, SMLoc &StartLoc, SMLoc &EndLoc)=0
virtual ParseStatus tryParseRegister(MCRegister &Reg, SMLoc &StartLoc, SMLoc &EndLoc)=0
tryParseRegister - parse one register if possible
void setAvailableFeatures(const FeatureBitset &Value)
const MCSubtargetInfo & getSTI() const
virtual unsigned validateTargetOperandClass(MCParsedAsmOperand &Op, unsigned Kind)
Allow a target to add special case operand matching for things that tblgen doesn't/can't handle effec...
virtual bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name, SMLoc NameLoc, OperandVector &Operands)=0
ParseInstruction - Parse one assembly instruction.
virtual bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode, OperandVector &Operands, MCStreamer &Out, uint64_t &ErrorInfo, bool MatchingInlineAsm)=0
MatchAndEmitInstruction - Recognize a series of operands of a parsed instruction as an actual MCInst ...
Ternary parse status returned by various parse* methods.
constexpr bool isFailure() const
static constexpr StatusTy Failure
constexpr bool isSuccess() const
static constexpr StatusTy Success
static constexpr StatusTy NoMatch
Represents a location in source code.
Definition: SMLoc.h:23
static SMLoc getFromPointer(const char *Ptr)
Definition: SMLoc.h:36
constexpr const char * getPointer() const
Definition: SMLoc.h:34
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:586
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
static const SparcMCExpr * create(VariantKind Kind, const MCExpr *Expr, MCContext &Ctx)
Definition: SparcMCExpr.cpp:27
static VariantKind parseVariantKind(StringRef name)
Definition: SparcMCExpr.cpp:93
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
A switch()-like statement whose cases are string literals.
Definition: StringSwitch.h:44
StringSwitch & Case(StringLiteral S, T Value)
Definition: StringSwitch.h:69
R Default(T Value)
Definition: StringSwitch.h:182
ArchType getArch() const
Get the parsed architecture type of this triple.
Definition: Triple.h:361
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
Definition: BitmaskEnum.h:121
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
MCExpr const & getExpr(MCExpr const &Expr)
@ CE
Windows NT (Windows on ARM)
Reg
All possible values of the reg field in the ModR/M byte.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Length
Definition: DWP.cpp:456
Target & getTheSparcTarget()
Target & getTheSparcV9Target()
DWARFExpression::Operation Op
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1858
Target & getTheSparcelTarget()
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:858
#define N
RegisterMCAsmParser - Helper template for registering a target specific assembly parser,...