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