[ARM64] Add WZR to isGPR32Register, since every use needs to check for this anyway.
[oota-llvm.git] / lib / Target / ARM64 / AsmParser / ARM64AsmParser.cpp
1 //===-- ARM64AsmParser.cpp - Parse ARM64 assembly to MCInst instructions --===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "MCTargetDesc/ARM64AddressingModes.h"
11 #include "MCTargetDesc/ARM64MCExpr.h"
12 #include "Utils/ARM64BaseInfo.h"
13 #include "llvm/MC/MCParser/MCAsmLexer.h"
14 #include "llvm/MC/MCParser/MCAsmParser.h"
15 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
16 #include "llvm/MC/MCContext.h"
17 #include "llvm/MC/MCExpr.h"
18 #include "llvm/MC/MCInst.h"
19 #include "llvm/MC/MCRegisterInfo.h"
20 #include "llvm/MC/MCStreamer.h"
21 #include "llvm/MC/MCSubtargetInfo.h"
22 #include "llvm/MC/MCSymbol.h"
23 #include "llvm/MC/MCTargetAsmParser.h"
24 #include "llvm/Support/SourceMgr.h"
25 #include "llvm/Support/TargetRegistry.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/ADT/SmallString.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/ADT/StringSwitch.h"
32 #include "llvm/ADT/Twine.h"
33 #include <cstdio>
34 using namespace llvm;
35
36 namespace {
37
38 class ARM64Operand;
39
40 class ARM64AsmParser : public MCTargetAsmParser {
41 public:
42   typedef SmallVectorImpl<MCParsedAsmOperand *> OperandVector;
43
44 private:
45   StringRef Mnemonic; ///< Instruction mnemonic.
46   MCSubtargetInfo &STI;
47   MCAsmParser &Parser;
48
49   MCAsmParser &getParser() const { return Parser; }
50   MCAsmLexer &getLexer() const { return Parser.getLexer(); }
51
52   SMLoc getLoc() const { return Parser.getTok().getLoc(); }
53
54   bool parseSysAlias(StringRef Name, SMLoc NameLoc, OperandVector &Operands);
55   unsigned parseCondCodeString(StringRef Cond);
56   bool parseCondCode(OperandVector &Operands, bool invertCondCode);
57   int tryParseRegister();
58   int tryMatchVectorRegister(StringRef &Kind, bool expected);
59   bool parseOptionalShift(OperandVector &Operands);
60   bool parseOptionalExtend(OperandVector &Operands);
61   bool parseRegister(OperandVector &Operands);
62   bool parseMemory(OperandVector &Operands);
63   bool parseSymbolicImmVal(const MCExpr *&ImmVal);
64   bool parseVectorList(OperandVector &Operands);
65   bool parseOperand(OperandVector &Operands, bool isCondCode,
66                     bool invertCondCode);
67
68   void Warning(SMLoc L, const Twine &Msg) { Parser.Warning(L, Msg); }
69   bool Error(SMLoc L, const Twine &Msg) { return Parser.Error(L, Msg); }
70   bool showMatchError(SMLoc Loc, unsigned ErrCode);
71
72   bool parseDirectiveWord(unsigned Size, SMLoc L);
73   bool parseDirectiveTLSDescCall(SMLoc L);
74
75   bool parseDirectiveLOH(StringRef LOH, SMLoc L);
76
77   bool validateInstruction(MCInst &Inst, SmallVectorImpl<SMLoc> &Loc);
78   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
79                                OperandVector &Operands, MCStreamer &Out,
80                                unsigned &ErrorInfo, bool MatchingInlineAsm);
81 /// @name Auto-generated Match Functions
82 /// {
83
84 #define GET_ASSEMBLER_HEADER
85 #include "ARM64GenAsmMatcher.inc"
86
87   /// }
88
89   OperandMatchResultTy tryParseNoIndexMemory(OperandVector &Operands);
90   OperandMatchResultTy tryParseBarrierOperand(OperandVector &Operands);
91   OperandMatchResultTy tryParseMRSSystemRegister(OperandVector &Operands);
92   OperandMatchResultTy tryParseMSRSystemRegister(OperandVector &Operands);
93   OperandMatchResultTy tryParseCPSRField(OperandVector &Operands);
94   OperandMatchResultTy tryParseSysCROperand(OperandVector &Operands);
95   OperandMatchResultTy tryParsePrefetch(OperandVector &Operands);
96   OperandMatchResultTy tryParseAdrpLabel(OperandVector &Operands);
97   OperandMatchResultTy tryParseAdrLabel(OperandVector &Operands);
98   OperandMatchResultTy tryParseFPImm(OperandVector &Operands);
99   bool tryParseVectorRegister(OperandVector &Operands);
100
101 public:
102   enum ARM64MatchResultTy {
103     Match_InvalidSuffix = FIRST_TARGET_MATCH_RESULT_TY,
104 #define GET_OPERAND_DIAGNOSTIC_TYPES
105 #include "ARM64GenAsmMatcher.inc"
106   };
107   ARM64AsmParser(MCSubtargetInfo &_STI, MCAsmParser &_Parser,
108                  const MCInstrInfo &MII)
109       : MCTargetAsmParser(), STI(_STI), Parser(_Parser) {
110     MCAsmParserExtension::Initialize(_Parser);
111   }
112
113   virtual bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
114                                 SMLoc NameLoc, OperandVector &Operands);
115   virtual bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
116   virtual bool ParseDirective(AsmToken DirectiveID);
117   unsigned validateTargetOperandClass(MCParsedAsmOperand *Op, unsigned Kind);
118
119   static bool classifySymbolRef(const MCExpr *Expr,
120                                 ARM64MCExpr::VariantKind &ELFRefKind,
121                                 MCSymbolRefExpr::VariantKind &DarwinRefKind,
122                                 const MCConstantExpr *&Addend);
123 };
124 } // end anonymous namespace
125
126 namespace {
127
128 /// ARM64Operand - Instances of this class represent a parsed ARM64 machine
129 /// instruction.
130 class ARM64Operand : public MCParsedAsmOperand {
131 public:
132   enum MemIdxKindTy {
133     ImmediateOffset, // pre-indexed, no writeback
134     RegisterOffset   // register offset, with optional extend
135   };
136
137 private:
138   enum KindTy {
139     k_Immediate,
140     k_Memory,
141     k_Register,
142     k_VectorList,
143     k_VectorIndex,
144     k_Token,
145     k_SysCR,
146     k_Prefetch,
147     k_Shifter,
148     k_Extend,
149     k_FPImm,
150     k_Barrier,
151     k_SystemRegister,
152     k_CPSRField
153   } Kind;
154
155   SMLoc StartLoc, EndLoc, OffsetLoc;
156
157   struct TokOp {
158     const char *Data;
159     unsigned Length;
160     bool IsSuffix; // Is the operand actually a suffix on the mnemonic.
161   };
162
163   struct RegOp {
164     unsigned RegNum;
165     bool isVector;
166   };
167
168   struct VectorListOp {
169     unsigned RegNum;
170     unsigned Count;
171     unsigned NumElements;
172     unsigned ElementKind;
173   };
174
175   struct VectorIndexOp {
176     unsigned Val;
177   };
178
179   struct ImmOp {
180     const MCExpr *Val;
181   };
182
183   struct FPImmOp {
184     unsigned Val; // Encoded 8-bit representation.
185   };
186
187   struct BarrierOp {
188     unsigned Val; // Not the enum since not all values have names.
189   };
190
191   struct SystemRegisterOp {
192     // 16-bit immediate, usually from the ARM64SysReg::SysRegValues enum
193     // but not limited to those values.
194     uint16_t Val;
195   };
196
197   struct CPSRFieldOp {
198     ARM64PState::PStateValues Field;
199   };
200
201   struct SysCRImmOp {
202     unsigned Val;
203   };
204
205   struct PrefetchOp {
206     unsigned Val;
207   };
208
209   struct ShifterOp {
210     unsigned Val;
211   };
212
213   struct ExtendOp {
214     unsigned Val;
215   };
216
217   // This is for all forms of ARM64 address expressions
218   struct MemOp {
219     unsigned BaseRegNum, OffsetRegNum;
220     ARM64_AM::ExtendType ExtType;
221     unsigned ShiftVal;
222     bool ExplicitShift;
223     const MCExpr *OffsetImm;
224     MemIdxKindTy Mode;
225   };
226
227   union {
228     struct TokOp Tok;
229     struct RegOp Reg;
230     struct VectorListOp VectorList;
231     struct VectorIndexOp VectorIndex;
232     struct ImmOp Imm;
233     struct FPImmOp FPImm;
234     struct BarrierOp Barrier;
235     struct SystemRegisterOp SystemRegister;
236     struct CPSRFieldOp CPSRField;
237     struct SysCRImmOp SysCRImm;
238     struct PrefetchOp Prefetch;
239     struct ShifterOp Shifter;
240     struct ExtendOp Extend;
241     struct MemOp Mem;
242   };
243
244   // Keep the MCContext around as the MCExprs may need manipulated during
245   // the add<>Operands() calls.
246   MCContext &Ctx;
247
248   ARM64Operand(KindTy K, MCContext &_Ctx)
249       : MCParsedAsmOperand(), Kind(K), Ctx(_Ctx) {}
250
251 public:
252   ARM64Operand(const ARM64Operand &o) : MCParsedAsmOperand(), Ctx(o.Ctx) {
253     Kind = o.Kind;
254     StartLoc = o.StartLoc;
255     EndLoc = o.EndLoc;
256     switch (Kind) {
257     case k_Token:
258       Tok = o.Tok;
259       break;
260     case k_Immediate:
261       Imm = o.Imm;
262       break;
263     case k_FPImm:
264       FPImm = o.FPImm;
265       break;
266     case k_Barrier:
267       Barrier = o.Barrier;
268       break;
269     case k_SystemRegister:
270       SystemRegister = o.SystemRegister;
271       break;
272     case k_CPSRField:
273       CPSRField = o.CPSRField;
274       break;
275     case k_Register:
276       Reg = o.Reg;
277       break;
278     case k_VectorList:
279       VectorList = o.VectorList;
280       break;
281     case k_VectorIndex:
282       VectorIndex = o.VectorIndex;
283       break;
284     case k_SysCR:
285       SysCRImm = o.SysCRImm;
286       break;
287     case k_Prefetch:
288       Prefetch = o.Prefetch;
289       break;
290     case k_Memory:
291       Mem = o.Mem;
292       break;
293     case k_Shifter:
294       Shifter = o.Shifter;
295       break;
296     case k_Extend:
297       Extend = o.Extend;
298       break;
299     }
300   }
301
302   /// getStartLoc - Get the location of the first token of this operand.
303   SMLoc getStartLoc() const { return StartLoc; }
304   /// getEndLoc - Get the location of the last token of this operand.
305   SMLoc getEndLoc() const { return EndLoc; }
306   /// getOffsetLoc - Get the location of the offset of this memory operand.
307   SMLoc getOffsetLoc() const { return OffsetLoc; }
308
309   StringRef getToken() const {
310     assert(Kind == k_Token && "Invalid access!");
311     return StringRef(Tok.Data, Tok.Length);
312   }
313
314   bool isTokenSuffix() const {
315     assert(Kind == k_Token && "Invalid access!");
316     return Tok.IsSuffix;
317   }
318
319   const MCExpr *getImm() const {
320     assert(Kind == k_Immediate && "Invalid access!");
321     return Imm.Val;
322   }
323
324   unsigned getFPImm() const {
325     assert(Kind == k_FPImm && "Invalid access!");
326     return FPImm.Val;
327   }
328
329   unsigned getBarrier() const {
330     assert(Kind == k_Barrier && "Invalid access!");
331     return Barrier.Val;
332   }
333
334   uint16_t getSystemRegister() const {
335     assert(Kind == k_SystemRegister && "Invalid access!");
336     return SystemRegister.Val;
337   }
338
339   ARM64PState::PStateValues getCPSRField() const {
340     assert(Kind == k_CPSRField && "Invalid access!");
341     return CPSRField.Field;
342   }
343
344   unsigned getReg() const {
345     assert(Kind == k_Register && "Invalid access!");
346     return Reg.RegNum;
347   }
348
349   unsigned getVectorListStart() const {
350     assert(Kind == k_VectorList && "Invalid access!");
351     return VectorList.RegNum;
352   }
353
354   unsigned getVectorListCount() const {
355     assert(Kind == k_VectorList && "Invalid access!");
356     return VectorList.Count;
357   }
358
359   unsigned getVectorIndex() const {
360     assert(Kind == k_VectorIndex && "Invalid access!");
361     return VectorIndex.Val;
362   }
363
364   unsigned getSysCR() const {
365     assert(Kind == k_SysCR && "Invalid access!");
366     return SysCRImm.Val;
367   }
368
369   unsigned getPrefetch() const {
370     assert(Kind == k_Prefetch && "Invalid access!");
371     return Prefetch.Val;
372   }
373
374   unsigned getShifter() const {
375     assert(Kind == k_Shifter && "Invalid access!");
376     return Shifter.Val;
377   }
378
379   unsigned getExtend() const {
380     assert(Kind == k_Extend && "Invalid access!");
381     return Extend.Val;
382   }
383
384   bool isImm() const { return Kind == k_Immediate; }
385   bool isSImm9() const {
386     if (!isImm())
387       return false;
388     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
389     if (!MCE)
390       return false;
391     int64_t Val = MCE->getValue();
392     return (Val >= -256 && Val < 256);
393   }
394   bool isSImm7s4() const {
395     if (!isImm())
396       return false;
397     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
398     if (!MCE)
399       return false;
400     int64_t Val = MCE->getValue();
401     return (Val >= -256 && Val <= 252 && (Val & 3) == 0);
402   }
403   bool isSImm7s8() const {
404     if (!isImm())
405       return false;
406     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
407     if (!MCE)
408       return false;
409     int64_t Val = MCE->getValue();
410     return (Val >= -512 && Val <= 504 && (Val & 7) == 0);
411   }
412   bool isSImm7s16() const {
413     if (!isImm())
414       return false;
415     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
416     if (!MCE)
417       return false;
418     int64_t Val = MCE->getValue();
419     return (Val >= -1024 && Val <= 1008 && (Val & 15) == 0);
420   }
421   bool isImm0_7() const {
422     if (!isImm())
423       return false;
424     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
425     if (!MCE)
426       return false;
427     int64_t Val = MCE->getValue();
428     return (Val >= 0 && Val < 8);
429   }
430   bool isImm1_8() const {
431     if (!isImm())
432       return false;
433     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
434     if (!MCE)
435       return false;
436     int64_t Val = MCE->getValue();
437     return (Val > 0 && Val < 9);
438   }
439   bool isImm0_15() const {
440     if (!isImm())
441       return false;
442     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
443     if (!MCE)
444       return false;
445     int64_t Val = MCE->getValue();
446     return (Val >= 0 && Val < 16);
447   }
448   bool isImm1_16() const {
449     if (!isImm())
450       return false;
451     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
452     if (!MCE)
453       return false;
454     int64_t Val = MCE->getValue();
455     return (Val > 0 && Val < 17);
456   }
457   bool isImm0_31() const {
458     if (!isImm())
459       return false;
460     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
461     if (!MCE)
462       return false;
463     int64_t Val = MCE->getValue();
464     return (Val >= 0 && Val < 32);
465   }
466   bool isImm1_31() const {
467     if (!isImm())
468       return false;
469     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
470     if (!MCE)
471       return false;
472     int64_t Val = MCE->getValue();
473     return (Val >= 1 && Val < 32);
474   }
475   bool isImm1_32() const {
476     if (!isImm())
477       return false;
478     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
479     if (!MCE)
480       return false;
481     int64_t Val = MCE->getValue();
482     return (Val >= 1 && Val < 33);
483   }
484   bool isImm0_63() const {
485     if (!isImm())
486       return false;
487     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
488     if (!MCE)
489       return false;
490     int64_t Val = MCE->getValue();
491     return (Val >= 0 && Val < 64);
492   }
493   bool isImm1_63() const {
494     if (!isImm())
495       return false;
496     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
497     if (!MCE)
498       return false;
499     int64_t Val = MCE->getValue();
500     return (Val >= 1 && Val < 64);
501   }
502   bool isImm1_64() const {
503     if (!isImm())
504       return false;
505     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
506     if (!MCE)
507       return false;
508     int64_t Val = MCE->getValue();
509     return (Val >= 1 && Val < 65);
510   }
511   bool isImm0_127() const {
512     if (!isImm())
513       return false;
514     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
515     if (!MCE)
516       return false;
517     int64_t Val = MCE->getValue();
518     return (Val >= 0 && Val < 128);
519   }
520   bool isImm0_255() const {
521     if (!isImm())
522       return false;
523     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
524     if (!MCE)
525       return false;
526     int64_t Val = MCE->getValue();
527     return (Val >= 0 && Val < 256);
528   }
529   bool isImm0_65535() const {
530     if (!isImm())
531       return false;
532     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
533     if (!MCE)
534       return false;
535     int64_t Val = MCE->getValue();
536     return (Val >= 0 && Val < 65536);
537   }
538   bool isLogicalImm32() const {
539     if (!isImm())
540       return false;
541     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
542     if (!MCE)
543       return false;
544     return ARM64_AM::isLogicalImmediate(MCE->getValue(), 32);
545   }
546   bool isLogicalImm64() const {
547     if (!isImm())
548       return false;
549     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
550     if (!MCE)
551       return false;
552     return ARM64_AM::isLogicalImmediate(MCE->getValue(), 64);
553   }
554   bool isSIMDImmType10() const {
555     if (!isImm())
556       return false;
557     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
558     if (!MCE)
559       return false;
560     return ARM64_AM::isAdvSIMDModImmType10(MCE->getValue());
561   }
562   bool isBranchTarget26() const {
563     if (!isImm())
564       return false;
565     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
566     if (!MCE)
567       return true;
568     int64_t Val = MCE->getValue();
569     if (Val & 0x3)
570       return false;
571     return (Val >= -(0x2000000 << 2) && Val <= (0x1ffffff << 2));
572   }
573   bool isBranchTarget19() const {
574     if (!isImm())
575       return false;
576     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
577     if (!MCE)
578       return true;
579     int64_t Val = MCE->getValue();
580     if (Val & 0x3)
581       return false;
582     return (Val >= -(0x40000 << 2) && Val <= (0x3ffff << 2));
583   }
584   bool isBranchTarget14() const {
585     if (!isImm())
586       return false;
587     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
588     if (!MCE)
589       return true;
590     int64_t Val = MCE->getValue();
591     if (Val & 0x3)
592       return false;
593     return (Val >= -(0x2000 << 2) && Val <= (0x1fff << 2));
594   }
595
596   bool isMovWSymbol(ArrayRef<ARM64MCExpr::VariantKind> AllowedModifiers) const {
597     if (!isImm())
598       return false;
599
600     ARM64MCExpr::VariantKind ELFRefKind;
601     MCSymbolRefExpr::VariantKind DarwinRefKind;
602     const MCConstantExpr *Addend;
603     if (!ARM64AsmParser::classifySymbolRef(getImm(), ELFRefKind, DarwinRefKind,
604                                            Addend)) {
605       return false;
606     }
607     if (DarwinRefKind != MCSymbolRefExpr::VK_None)
608       return false;
609
610     for (unsigned i = 0; i != AllowedModifiers.size(); ++i) {
611       if (ELFRefKind == AllowedModifiers[i])
612         return Addend == 0;
613     }
614
615     return false;
616   }
617
618   bool isMovZSymbolG3() const {
619     static ARM64MCExpr::VariantKind Variants[] = { ARM64MCExpr::VK_ABS_G3 };
620     return isMovWSymbol(Variants);
621   }
622
623   bool isMovZSymbolG2() const {
624     static ARM64MCExpr::VariantKind Variants[] = { ARM64MCExpr::VK_ABS_G2,
625                                                    ARM64MCExpr::VK_TPREL_G2,
626                                                    ARM64MCExpr::VK_DTPREL_G2 };
627     return isMovWSymbol(Variants);
628   }
629
630   bool isMovZSymbolG1() const {
631     static ARM64MCExpr::VariantKind Variants[] = { ARM64MCExpr::VK_ABS_G1,
632                                                    ARM64MCExpr::VK_GOTTPREL_G1,
633                                                    ARM64MCExpr::VK_TPREL_G1,
634                                                    ARM64MCExpr::VK_DTPREL_G1, };
635     return isMovWSymbol(Variants);
636   }
637
638   bool isMovZSymbolG0() const {
639     static ARM64MCExpr::VariantKind Variants[] = { ARM64MCExpr::VK_ABS_G0,
640                                                    ARM64MCExpr::VK_TPREL_G0,
641                                                    ARM64MCExpr::VK_DTPREL_G0 };
642     return isMovWSymbol(Variants);
643   }
644
645   bool isMovKSymbolG2() const {
646     static ARM64MCExpr::VariantKind Variants[] = { ARM64MCExpr::VK_ABS_G2_NC };
647     return isMovWSymbol(Variants);
648   }
649
650   bool isMovKSymbolG1() const {
651     static ARM64MCExpr::VariantKind Variants[] = {
652       ARM64MCExpr::VK_ABS_G1_NC, ARM64MCExpr::VK_TPREL_G1_NC,
653       ARM64MCExpr::VK_DTPREL_G1_NC
654     };
655     return isMovWSymbol(Variants);
656   }
657
658   bool isMovKSymbolG0() const {
659     static ARM64MCExpr::VariantKind Variants[] = {
660       ARM64MCExpr::VK_ABS_G0_NC,   ARM64MCExpr::VK_GOTTPREL_G0_NC,
661       ARM64MCExpr::VK_TPREL_G0_NC, ARM64MCExpr::VK_DTPREL_G0_NC
662     };
663     return isMovWSymbol(Variants);
664   }
665
666   bool isFPImm() const { return Kind == k_FPImm; }
667   bool isBarrier() const { return Kind == k_Barrier; }
668   bool isSystemRegister() const {
669     if (Kind == k_SystemRegister)
670       return true;
671     // SPSel is legal for both the system register and the CPSR-field
672     // variants of MSR, so special case that. Fugly.
673     return (Kind == k_CPSRField && getCPSRField() == ARM64PState::SPSel);
674   }
675   bool isSystemCPSRField() const { return Kind == k_CPSRField; }
676   bool isReg() const { return Kind == k_Register && !Reg.isVector; }
677   bool isVectorReg() const { return Kind == k_Register && Reg.isVector; }
678
679   /// Is this a vector list with the type implicit (presumably attached to the
680   /// instruction itself)?
681   template <unsigned NumRegs> bool isImplicitlyTypedVectorList() const {
682     return Kind == k_VectorList && VectorList.Count == NumRegs &&
683            !VectorList.ElementKind;
684   }
685
686   template <unsigned NumRegs, unsigned NumElements, char ElementKind>
687   bool isTypedVectorList() const {
688     if (Kind != k_VectorList)
689       return false;
690     if (VectorList.Count != NumRegs)
691       return false;
692     if (VectorList.ElementKind != ElementKind)
693       return false;
694     return VectorList.NumElements == NumElements;
695   }
696
697   bool isVectorIndexB() const {
698     return Kind == k_VectorIndex && VectorIndex.Val < 16;
699   }
700   bool isVectorIndexH() const {
701     return Kind == k_VectorIndex && VectorIndex.Val < 8;
702   }
703   bool isVectorIndexS() const {
704     return Kind == k_VectorIndex && VectorIndex.Val < 4;
705   }
706   bool isVectorIndexD() const {
707     return Kind == k_VectorIndex && VectorIndex.Val < 2;
708   }
709   bool isToken() const { return Kind == k_Token; }
710   bool isTokenEqual(StringRef Str) const {
711     return Kind == k_Token && getToken() == Str;
712   }
713   bool isMem() const { return Kind == k_Memory; }
714   bool isSysCR() const { return Kind == k_SysCR; }
715   bool isPrefetch() const { return Kind == k_Prefetch; }
716   bool isShifter() const { return Kind == k_Shifter; }
717   bool isExtend() const {
718     // lsl is an alias for UXTW but will be a parsed as a k_Shifter operand.
719     if (isShifter()) {
720       ARM64_AM::ShiftType ST = ARM64_AM::getShiftType(Shifter.Val);
721       return ST == ARM64_AM::LSL;
722     }
723     return Kind == k_Extend;
724   }
725   bool isExtend64() const {
726     if (Kind != k_Extend)
727       return false;
728     // UXTX and SXTX require a 64-bit source register (the ExtendLSL64 class).
729     ARM64_AM::ExtendType ET = ARM64_AM::getArithExtendType(Extend.Val);
730     return ET != ARM64_AM::UXTX && ET != ARM64_AM::SXTX;
731   }
732   bool isExtendLSL64() const {
733     // lsl is an alias for UXTX but will be a parsed as a k_Shifter operand.
734     if (isShifter()) {
735       ARM64_AM::ShiftType ST = ARM64_AM::getShiftType(Shifter.Val);
736       return ST == ARM64_AM::LSL;
737     }
738     if (Kind != k_Extend)
739       return false;
740     ARM64_AM::ExtendType ET = ARM64_AM::getArithExtendType(Extend.Val);
741     return ET == ARM64_AM::UXTX || ET == ARM64_AM::SXTX;
742   }
743
744   bool isArithmeticShifter() const {
745     if (!isShifter())
746       return false;
747
748     // An arithmetic shifter is LSL, LSR, or ASR.
749     ARM64_AM::ShiftType ST = ARM64_AM::getShiftType(Shifter.Val);
750     return ST == ARM64_AM::LSL || ST == ARM64_AM::LSR || ST == ARM64_AM::ASR;
751   }
752
753   bool isMovImm32Shifter() const {
754     if (!isShifter())
755       return false;
756
757     // A MOVi shifter is LSL of 0, 16, 32, or 48.
758     ARM64_AM::ShiftType ST = ARM64_AM::getShiftType(Shifter.Val);
759     if (ST != ARM64_AM::LSL)
760       return false;
761     uint64_t Val = ARM64_AM::getShiftValue(Shifter.Val);
762     return (Val == 0 || Val == 16);
763   }
764
765   bool isMovImm64Shifter() const {
766     if (!isShifter())
767       return false;
768
769     // A MOVi shifter is LSL of 0 or 16.
770     ARM64_AM::ShiftType ST = ARM64_AM::getShiftType(Shifter.Val);
771     if (ST != ARM64_AM::LSL)
772       return false;
773     uint64_t Val = ARM64_AM::getShiftValue(Shifter.Val);
774     return (Val == 0 || Val == 16 || Val == 32 || Val == 48);
775   }
776
777   bool isAddSubShifter() const {
778     if (!isShifter())
779       return false;
780
781     // An ADD/SUB shifter is either 'lsl #0' or 'lsl #12'.
782     unsigned Val = Shifter.Val;
783     return ARM64_AM::getShiftType(Val) == ARM64_AM::LSL &&
784            (ARM64_AM::getShiftValue(Val) == 0 ||
785             ARM64_AM::getShiftValue(Val) == 12);
786   }
787
788   bool isLogicalVecShifter() const {
789     if (!isShifter())
790       return false;
791
792     // A logical vector shifter is a left shift by 0, 8, 16, or 24.
793     unsigned Val = Shifter.Val;
794     unsigned Shift = ARM64_AM::getShiftValue(Val);
795     return ARM64_AM::getShiftType(Val) == ARM64_AM::LSL &&
796            (Shift == 0 || Shift == 8 || Shift == 16 || Shift == 24);
797   }
798
799   bool isLogicalVecHalfWordShifter() const {
800     if (!isLogicalVecShifter())
801       return false;
802
803     // A logical vector shifter is a left shift by 0 or 8.
804     unsigned Val = Shifter.Val;
805     unsigned Shift = ARM64_AM::getShiftValue(Val);
806     return ARM64_AM::getShiftType(Val) == ARM64_AM::LSL &&
807            (Shift == 0 || Shift == 8);
808   }
809
810   bool isMoveVecShifter() const {
811     if (!isShifter())
812       return false;
813
814     // A logical vector shifter is a left shift by 8 or 16.
815     unsigned Val = Shifter.Val;
816     unsigned Shift = ARM64_AM::getShiftValue(Val);
817     return ARM64_AM::getShiftType(Val) == ARM64_AM::MSL &&
818            (Shift == 8 || Shift == 16);
819   }
820
821   bool isMemoryRegisterOffset8() const {
822     return isMem() && Mem.Mode == RegisterOffset && Mem.ShiftVal == 0;
823   }
824
825   bool isMemoryRegisterOffset16() const {
826     return isMem() && Mem.Mode == RegisterOffset &&
827            (Mem.ShiftVal == 0 || Mem.ShiftVal == 1);
828   }
829
830   bool isMemoryRegisterOffset32() const {
831     return isMem() && Mem.Mode == RegisterOffset &&
832            (Mem.ShiftVal == 0 || Mem.ShiftVal == 2);
833   }
834
835   bool isMemoryRegisterOffset64() const {
836     return isMem() && Mem.Mode == RegisterOffset &&
837            (Mem.ShiftVal == 0 || Mem.ShiftVal == 3);
838   }
839
840   bool isMemoryRegisterOffset128() const {
841     return isMem() && Mem.Mode == RegisterOffset &&
842            (Mem.ShiftVal == 0 || Mem.ShiftVal == 4);
843   }
844
845   bool isMemoryUnscaled() const {
846     if (!isMem())
847       return false;
848     if (Mem.Mode != ImmediateOffset)
849       return false;
850     if (!Mem.OffsetImm)
851       return true;
852     // Make sure the immediate value is valid.
853     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Mem.OffsetImm);
854     if (!CE)
855       return false;
856     // The offset must fit in a signed 9-bit unscaled immediate.
857     int64_t Value = CE->getValue();
858     return (Value >= -256 && Value < 256);
859   }
860   // Fallback unscaled operands are for aliases of LDR/STR that fall back
861   // to LDUR/STUR when the offset is not legal for the former but is for
862   // the latter. As such, in addition to checking for being a legal unscaled
863   // address, also check that it is not a legal scaled address. This avoids
864   // ambiguity in the matcher.
865   bool isMemoryUnscaledFB8() const {
866     return isMemoryUnscaled() && !isMemoryIndexed8();
867   }
868   bool isMemoryUnscaledFB16() const {
869     return isMemoryUnscaled() && !isMemoryIndexed16();
870   }
871   bool isMemoryUnscaledFB32() const {
872     return isMemoryUnscaled() && !isMemoryIndexed32();
873   }
874   bool isMemoryUnscaledFB64() const {
875     return isMemoryUnscaled() && !isMemoryIndexed64();
876   }
877   bool isMemoryUnscaledFB128() const {
878     return isMemoryUnscaled() && !isMemoryIndexed128();
879   }
880   bool isMemoryIndexed(unsigned Scale) const {
881     if (!isMem())
882       return false;
883     if (Mem.Mode != ImmediateOffset)
884       return false;
885     if (!Mem.OffsetImm)
886       return true;
887     // Make sure the immediate value is valid.
888     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Mem.OffsetImm);
889
890     if (CE) {
891       // The offset must be a positive multiple of the scale and in range of
892       // encoding with a 12-bit immediate.
893       int64_t Value = CE->getValue();
894       return (Value >= 0 && (Value % Scale) == 0 && Value <= (4095 * Scale));
895     }
896
897     // If it's not a constant, check for some expressions we know.
898     const MCExpr *Expr = Mem.OffsetImm;
899     ARM64MCExpr::VariantKind ELFRefKind;
900     MCSymbolRefExpr::VariantKind DarwinRefKind;
901     const MCConstantExpr *Addend;
902     if (!ARM64AsmParser::classifySymbolRef(Expr, ELFRefKind, DarwinRefKind,
903                                            Addend)) {
904       // If we don't understand the expression, assume the best and
905       // let the fixup and relocation code deal with it.
906       return true;
907     }
908
909     if (DarwinRefKind == MCSymbolRefExpr::VK_PAGEOFF ||
910         ELFRefKind == ARM64MCExpr::VK_LO12 ||
911         ELFRefKind == ARM64MCExpr::VK_GOT_LO12 ||
912         ELFRefKind == ARM64MCExpr::VK_DTPREL_LO12 ||
913         ELFRefKind == ARM64MCExpr::VK_DTPREL_LO12_NC ||
914         ELFRefKind == ARM64MCExpr::VK_TPREL_LO12 ||
915         ELFRefKind == ARM64MCExpr::VK_TPREL_LO12_NC ||
916         ELFRefKind == ARM64MCExpr::VK_GOTTPREL_LO12_NC ||
917         ELFRefKind == ARM64MCExpr::VK_TLSDESC_LO12) {
918       // Note that we don't range-check the addend. It's adjusted modulo page
919       // size when converted, so there is no "out of range" condition when using
920       // @pageoff.
921       int64_t Value = Addend ? Addend->getValue() : 0;
922       return Value >= 0 && (Value % Scale) == 0;
923     } else if (DarwinRefKind == MCSymbolRefExpr::VK_GOTPAGEOFF ||
924                DarwinRefKind == MCSymbolRefExpr::VK_TLVPPAGEOFF) {
925       // @gotpageoff/@tlvppageoff can only be used directly, not with an addend.
926       return Addend == 0;
927     }
928
929     return false;
930   }
931   bool isMemoryIndexed128() const { return isMemoryIndexed(16); }
932   bool isMemoryIndexed64() const { return isMemoryIndexed(8); }
933   bool isMemoryIndexed32() const { return isMemoryIndexed(4); }
934   bool isMemoryIndexed16() const { return isMemoryIndexed(2); }
935   bool isMemoryIndexed8() const { return isMemoryIndexed(1); }
936   bool isMemoryNoIndex() const {
937     if (!isMem())
938       return false;
939     if (Mem.Mode != ImmediateOffset)
940       return false;
941     if (!Mem.OffsetImm)
942       return true;
943
944     // Make sure the immediate value is valid. Only zero is allowed.
945     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Mem.OffsetImm);
946     if (!CE || CE->getValue() != 0)
947       return false;
948     return true;
949   }
950   bool isMemorySIMDNoIndex() const {
951     if (!isMem())
952       return false;
953     if (Mem.Mode != ImmediateOffset)
954       return false;
955     return Mem.OffsetImm == 0;
956   }
957   bool isMemoryIndexedSImm9() const {
958     if (!isMem() || Mem.Mode != ImmediateOffset)
959       return false;
960     if (!Mem.OffsetImm)
961       return true;
962     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Mem.OffsetImm);
963     assert(CE && "Non-constant pre-indexed offset!");
964     int64_t Value = CE->getValue();
965     return Value >= -256 && Value <= 255;
966   }
967   bool isMemoryIndexed32SImm7() const {
968     if (!isMem() || Mem.Mode != ImmediateOffset)
969       return false;
970     if (!Mem.OffsetImm)
971       return true;
972     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Mem.OffsetImm);
973     assert(CE && "Non-constant pre-indexed offset!");
974     int64_t Value = CE->getValue();
975     return ((Value % 4) == 0) && Value >= -256 && Value <= 252;
976   }
977   bool isMemoryIndexed64SImm7() const {
978     if (!isMem() || Mem.Mode != ImmediateOffset)
979       return false;
980     if (!Mem.OffsetImm)
981       return true;
982     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Mem.OffsetImm);
983     assert(CE && "Non-constant pre-indexed offset!");
984     int64_t Value = CE->getValue();
985     return ((Value % 8) == 0) && Value >= -512 && Value <= 504;
986   }
987   bool isMemoryIndexed128SImm7() const {
988     if (!isMem() || Mem.Mode != ImmediateOffset)
989       return false;
990     if (!Mem.OffsetImm)
991       return true;
992     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Mem.OffsetImm);
993     assert(CE && "Non-constant pre-indexed offset!");
994     int64_t Value = CE->getValue();
995     return ((Value % 16) == 0) && Value >= -1024 && Value <= 1008;
996   }
997
998   bool isAdrpLabel() const {
999     // Validation was handled during parsing, so we just sanity check that
1000     // something didn't go haywire.
1001     return isImm();
1002   }
1003
1004   bool isAdrLabel() const {
1005     // Validation was handled during parsing, so we just sanity check that
1006     // something didn't go haywire.
1007     return isImm();
1008   }
1009
1010   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
1011     // Add as immediates when possible.  Null MCExpr = 0.
1012     if (Expr == 0)
1013       Inst.addOperand(MCOperand::CreateImm(0));
1014     else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
1015       Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
1016     else
1017       Inst.addOperand(MCOperand::CreateExpr(Expr));
1018   }
1019
1020   void addRegOperands(MCInst &Inst, unsigned N) const {
1021     assert(N == 1 && "Invalid number of operands!");
1022     Inst.addOperand(MCOperand::CreateReg(getReg()));
1023   }
1024
1025   void addVectorRegOperands(MCInst &Inst, unsigned N) const {
1026     assert(N == 1 && "Invalid number of operands!");
1027     Inst.addOperand(MCOperand::CreateReg(getReg()));
1028   }
1029
1030   template <unsigned NumRegs>
1031   void addVectorList64Operands(MCInst &Inst, unsigned N) const {
1032     assert(N == 1 && "Invalid number of operands!");
1033     static unsigned FirstRegs[] = { ARM64::D0,       ARM64::D0_D1,
1034                                     ARM64::D0_D1_D2, ARM64::D0_D1_D2_D3 };
1035     unsigned FirstReg = FirstRegs[NumRegs - 1];
1036
1037     Inst.addOperand(
1038         MCOperand::CreateReg(FirstReg + getVectorListStart() - ARM64::Q0));
1039   }
1040
1041   template <unsigned NumRegs>
1042   void addVectorList128Operands(MCInst &Inst, unsigned N) const {
1043     assert(N == 1 && "Invalid number of operands!");
1044     static unsigned FirstRegs[] = { ARM64::Q0,       ARM64::Q0_Q1,
1045                                     ARM64::Q0_Q1_Q2, ARM64::Q0_Q1_Q2_Q3 };
1046     unsigned FirstReg = FirstRegs[NumRegs - 1];
1047
1048     Inst.addOperand(
1049         MCOperand::CreateReg(FirstReg + getVectorListStart() - ARM64::Q0));
1050   }
1051
1052   void addVectorIndexBOperands(MCInst &Inst, unsigned N) const {
1053     assert(N == 1 && "Invalid number of operands!");
1054     Inst.addOperand(MCOperand::CreateImm(getVectorIndex()));
1055   }
1056
1057   void addVectorIndexHOperands(MCInst &Inst, unsigned N) const {
1058     assert(N == 1 && "Invalid number of operands!");
1059     Inst.addOperand(MCOperand::CreateImm(getVectorIndex()));
1060   }
1061
1062   void addVectorIndexSOperands(MCInst &Inst, unsigned N) const {
1063     assert(N == 1 && "Invalid number of operands!");
1064     Inst.addOperand(MCOperand::CreateImm(getVectorIndex()));
1065   }
1066
1067   void addVectorIndexDOperands(MCInst &Inst, unsigned N) const {
1068     assert(N == 1 && "Invalid number of operands!");
1069     Inst.addOperand(MCOperand::CreateImm(getVectorIndex()));
1070   }
1071
1072   void addImmOperands(MCInst &Inst, unsigned N) const {
1073     assert(N == 1 && "Invalid number of operands!");
1074     // If this is a pageoff symrefexpr with an addend, adjust the addend
1075     // to be only the page-offset portion. Otherwise, just add the expr
1076     // as-is.
1077     addExpr(Inst, getImm());
1078   }
1079
1080   void addAdrpLabelOperands(MCInst &Inst, unsigned N) const {
1081     addImmOperands(Inst, N);
1082   }
1083
1084   void addAdrLabelOperands(MCInst &Inst, unsigned N) const {
1085     addImmOperands(Inst, N);
1086   }
1087
1088   void addSImm9Operands(MCInst &Inst, unsigned N) const {
1089     assert(N == 1 && "Invalid number of operands!");
1090     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
1091     assert(MCE && "Invalid constant immediate operand!");
1092     Inst.addOperand(MCOperand::CreateImm(MCE->getValue()));
1093   }
1094
1095   void addSImm7s4Operands(MCInst &Inst, unsigned N) const {
1096     assert(N == 1 && "Invalid number of operands!");
1097     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
1098     assert(MCE && "Invalid constant immediate operand!");
1099     Inst.addOperand(MCOperand::CreateImm(MCE->getValue() / 4));
1100   }
1101
1102   void addSImm7s8Operands(MCInst &Inst, unsigned N) const {
1103     assert(N == 1 && "Invalid number of operands!");
1104     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
1105     assert(MCE && "Invalid constant immediate operand!");
1106     Inst.addOperand(MCOperand::CreateImm(MCE->getValue() / 8));
1107   }
1108
1109   void addSImm7s16Operands(MCInst &Inst, unsigned N) const {
1110     assert(N == 1 && "Invalid number of operands!");
1111     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
1112     assert(MCE && "Invalid constant immediate operand!");
1113     Inst.addOperand(MCOperand::CreateImm(MCE->getValue() / 16));
1114   }
1115
1116   void addImm0_7Operands(MCInst &Inst, unsigned N) const {
1117     assert(N == 1 && "Invalid number of operands!");
1118     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
1119     assert(MCE && "Invalid constant immediate operand!");
1120     Inst.addOperand(MCOperand::CreateImm(MCE->getValue()));
1121   }
1122
1123   void addImm1_8Operands(MCInst &Inst, unsigned N) const {
1124     assert(N == 1 && "Invalid number of operands!");
1125     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
1126     assert(MCE && "Invalid constant immediate operand!");
1127     Inst.addOperand(MCOperand::CreateImm(MCE->getValue()));
1128   }
1129
1130   void addImm0_15Operands(MCInst &Inst, unsigned N) const {
1131     assert(N == 1 && "Invalid number of operands!");
1132     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
1133     assert(MCE && "Invalid constant immediate operand!");
1134     Inst.addOperand(MCOperand::CreateImm(MCE->getValue()));
1135   }
1136
1137   void addImm1_16Operands(MCInst &Inst, unsigned N) const {
1138     assert(N == 1 && "Invalid number of operands!");
1139     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
1140     assert(MCE && "Invalid constant immediate operand!");
1141     Inst.addOperand(MCOperand::CreateImm(MCE->getValue()));
1142   }
1143
1144   void addImm0_31Operands(MCInst &Inst, unsigned N) const {
1145     assert(N == 1 && "Invalid number of operands!");
1146     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
1147     assert(MCE && "Invalid constant immediate operand!");
1148     Inst.addOperand(MCOperand::CreateImm(MCE->getValue()));
1149   }
1150
1151   void addImm1_31Operands(MCInst &Inst, unsigned N) const {
1152     assert(N == 1 && "Invalid number of operands!");
1153     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
1154     assert(MCE && "Invalid constant immediate operand!");
1155     Inst.addOperand(MCOperand::CreateImm(MCE->getValue()));
1156   }
1157
1158   void addImm1_32Operands(MCInst &Inst, unsigned N) const {
1159     assert(N == 1 && "Invalid number of operands!");
1160     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
1161     assert(MCE && "Invalid constant immediate operand!");
1162     Inst.addOperand(MCOperand::CreateImm(MCE->getValue()));
1163   }
1164
1165   void addImm0_63Operands(MCInst &Inst, unsigned N) const {
1166     assert(N == 1 && "Invalid number of operands!");
1167     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
1168     assert(MCE && "Invalid constant immediate operand!");
1169     Inst.addOperand(MCOperand::CreateImm(MCE->getValue()));
1170   }
1171
1172   void addImm1_63Operands(MCInst &Inst, unsigned N) const {
1173     assert(N == 1 && "Invalid number of operands!");
1174     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
1175     assert(MCE && "Invalid constant immediate operand!");
1176     Inst.addOperand(MCOperand::CreateImm(MCE->getValue()));
1177   }
1178
1179   void addImm1_64Operands(MCInst &Inst, unsigned N) const {
1180     assert(N == 1 && "Invalid number of operands!");
1181     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
1182     assert(MCE && "Invalid constant immediate operand!");
1183     Inst.addOperand(MCOperand::CreateImm(MCE->getValue()));
1184   }
1185
1186   void addImm0_127Operands(MCInst &Inst, unsigned N) const {
1187     assert(N == 1 && "Invalid number of operands!");
1188     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
1189     assert(MCE && "Invalid constant immediate operand!");
1190     Inst.addOperand(MCOperand::CreateImm(MCE->getValue()));
1191   }
1192
1193   void addImm0_255Operands(MCInst &Inst, unsigned N) const {
1194     assert(N == 1 && "Invalid number of operands!");
1195     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
1196     assert(MCE && "Invalid constant immediate operand!");
1197     Inst.addOperand(MCOperand::CreateImm(MCE->getValue()));
1198   }
1199
1200   void addImm0_65535Operands(MCInst &Inst, unsigned N) const {
1201     assert(N == 1 && "Invalid number of operands!");
1202     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
1203     assert(MCE && "Invalid constant immediate operand!");
1204     Inst.addOperand(MCOperand::CreateImm(MCE->getValue()));
1205   }
1206
1207   void addLogicalImm32Operands(MCInst &Inst, unsigned N) const {
1208     assert(N == 1 && "Invalid number of operands!");
1209     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
1210     assert(MCE && "Invalid logical immediate operand!");
1211     uint64_t encoding = ARM64_AM::encodeLogicalImmediate(MCE->getValue(), 32);
1212     Inst.addOperand(MCOperand::CreateImm(encoding));
1213   }
1214
1215   void addLogicalImm64Operands(MCInst &Inst, unsigned N) const {
1216     assert(N == 1 && "Invalid number of operands!");
1217     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
1218     assert(MCE && "Invalid logical immediate operand!");
1219     uint64_t encoding = ARM64_AM::encodeLogicalImmediate(MCE->getValue(), 64);
1220     Inst.addOperand(MCOperand::CreateImm(encoding));
1221   }
1222
1223   void addSIMDImmType10Operands(MCInst &Inst, unsigned N) const {
1224     assert(N == 1 && "Invalid number of operands!");
1225     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
1226     assert(MCE && "Invalid immediate operand!");
1227     uint64_t encoding = ARM64_AM::encodeAdvSIMDModImmType10(MCE->getValue());
1228     Inst.addOperand(MCOperand::CreateImm(encoding));
1229   }
1230
1231   void addBranchTarget26Operands(MCInst &Inst, unsigned N) const {
1232     // Branch operands don't encode the low bits, so shift them off
1233     // here. If it's a label, however, just put it on directly as there's
1234     // not enough information now to do anything.
1235     assert(N == 1 && "Invalid number of operands!");
1236     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
1237     if (!MCE) {
1238       addExpr(Inst, getImm());
1239       return;
1240     }
1241     assert(MCE && "Invalid constant immediate operand!");
1242     Inst.addOperand(MCOperand::CreateImm(MCE->getValue() >> 2));
1243   }
1244
1245   void addBranchTarget19Operands(MCInst &Inst, unsigned N) const {
1246     // Branch operands don't encode the low bits, so shift them off
1247     // here. If it's a label, however, just put it on directly as there's
1248     // not enough information now to do anything.
1249     assert(N == 1 && "Invalid number of operands!");
1250     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
1251     if (!MCE) {
1252       addExpr(Inst, getImm());
1253       return;
1254     }
1255     assert(MCE && "Invalid constant immediate operand!");
1256     Inst.addOperand(MCOperand::CreateImm(MCE->getValue() >> 2));
1257   }
1258
1259   void addBranchTarget14Operands(MCInst &Inst, unsigned N) const {
1260     // Branch operands don't encode the low bits, so shift them off
1261     // here. If it's a label, however, just put it on directly as there's
1262     // not enough information now to do anything.
1263     assert(N == 1 && "Invalid number of operands!");
1264     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
1265     if (!MCE) {
1266       addExpr(Inst, getImm());
1267       return;
1268     }
1269     assert(MCE && "Invalid constant immediate operand!");
1270     Inst.addOperand(MCOperand::CreateImm(MCE->getValue() >> 2));
1271   }
1272
1273   void addFPImmOperands(MCInst &Inst, unsigned N) const {
1274     assert(N == 1 && "Invalid number of operands!");
1275     Inst.addOperand(MCOperand::CreateImm(getFPImm()));
1276   }
1277
1278   void addBarrierOperands(MCInst &Inst, unsigned N) const {
1279     assert(N == 1 && "Invalid number of operands!");
1280     Inst.addOperand(MCOperand::CreateImm(getBarrier()));
1281   }
1282
1283   void addSystemRegisterOperands(MCInst &Inst, unsigned N) const {
1284     assert(N == 1 && "Invalid number of operands!");
1285     if (Kind == k_SystemRegister)
1286       Inst.addOperand(MCOperand::CreateImm(getSystemRegister()));
1287     else {
1288       assert(Kind == k_CPSRField && getCPSRField() == ARM64PState::SPSel);
1289       Inst.addOperand(MCOperand::CreateImm(ARM64SysReg::SPSel));
1290     }
1291   }
1292
1293   void addSystemCPSRFieldOperands(MCInst &Inst, unsigned N) const {
1294     assert(N == 1 && "Invalid number of operands!");
1295     Inst.addOperand(MCOperand::CreateImm(getCPSRField()));
1296   }
1297
1298   void addSysCROperands(MCInst &Inst, unsigned N) const {
1299     assert(N == 1 && "Invalid number of operands!");
1300     Inst.addOperand(MCOperand::CreateImm(getSysCR()));
1301   }
1302
1303   void addPrefetchOperands(MCInst &Inst, unsigned N) const {
1304     assert(N == 1 && "Invalid number of operands!");
1305     Inst.addOperand(MCOperand::CreateImm(getPrefetch()));
1306   }
1307
1308   void addShifterOperands(MCInst &Inst, unsigned N) const {
1309     assert(N == 1 && "Invalid number of operands!");
1310     Inst.addOperand(MCOperand::CreateImm(getShifter()));
1311   }
1312
1313   void addArithmeticShifterOperands(MCInst &Inst, unsigned N) const {
1314     assert(N == 1 && "Invalid number of operands!");
1315     Inst.addOperand(MCOperand::CreateImm(getShifter()));
1316   }
1317
1318   void addMovImm32ShifterOperands(MCInst &Inst, unsigned N) const {
1319     assert(N == 1 && "Invalid number of operands!");
1320     Inst.addOperand(MCOperand::CreateImm(getShifter()));
1321   }
1322
1323   void addMovImm64ShifterOperands(MCInst &Inst, unsigned N) const {
1324     assert(N == 1 && "Invalid number of operands!");
1325     Inst.addOperand(MCOperand::CreateImm(getShifter()));
1326   }
1327
1328   void addAddSubShifterOperands(MCInst &Inst, unsigned N) const {
1329     assert(N == 1 && "Invalid number of operands!");
1330     Inst.addOperand(MCOperand::CreateImm(getShifter()));
1331   }
1332
1333   void addLogicalVecShifterOperands(MCInst &Inst, unsigned N) const {
1334     assert(N == 1 && "Invalid number of operands!");
1335     Inst.addOperand(MCOperand::CreateImm(getShifter()));
1336   }
1337
1338   void addLogicalVecHalfWordShifterOperands(MCInst &Inst, unsigned N) const {
1339     assert(N == 1 && "Invalid number of operands!");
1340     Inst.addOperand(MCOperand::CreateImm(getShifter()));
1341   }
1342
1343   void addMoveVecShifterOperands(MCInst &Inst, unsigned N) const {
1344     assert(N == 1 && "Invalid number of operands!");
1345     Inst.addOperand(MCOperand::CreateImm(getShifter()));
1346   }
1347
1348   void addExtendOperands(MCInst &Inst, unsigned N) const {
1349     assert(N == 1 && "Invalid number of operands!");
1350     // lsl is an alias for UXTW but will be a parsed as a k_Shifter operand.
1351     if (isShifter()) {
1352       assert(ARM64_AM::getShiftType(getShifter()) == ARM64_AM::LSL);
1353       unsigned imm = getArithExtendImm(ARM64_AM::UXTW,
1354                                        ARM64_AM::getShiftValue(getShifter()));
1355       Inst.addOperand(MCOperand::CreateImm(imm));
1356     } else
1357       Inst.addOperand(MCOperand::CreateImm(getExtend()));
1358   }
1359
1360   void addExtend64Operands(MCInst &Inst, unsigned N) const {
1361     assert(N == 1 && "Invalid number of operands!");
1362     Inst.addOperand(MCOperand::CreateImm(getExtend()));
1363   }
1364
1365   void addExtendLSL64Operands(MCInst &Inst, unsigned N) const {
1366     assert(N == 1 && "Invalid number of operands!");
1367     // lsl is an alias for UXTX but will be a parsed as a k_Shifter operand.
1368     if (isShifter()) {
1369       assert(ARM64_AM::getShiftType(getShifter()) == ARM64_AM::LSL);
1370       unsigned imm = getArithExtendImm(ARM64_AM::UXTX,
1371                                        ARM64_AM::getShiftValue(getShifter()));
1372       Inst.addOperand(MCOperand::CreateImm(imm));
1373     } else
1374       Inst.addOperand(MCOperand::CreateImm(getExtend()));
1375   }
1376
1377   void addMemoryRegisterOffsetOperands(MCInst &Inst, unsigned N, bool DoShift) {
1378     assert(N == 3 && "Invalid number of operands!");
1379
1380     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1381     Inst.addOperand(MCOperand::CreateReg(Mem.OffsetRegNum));
1382     unsigned ExtendImm = ARM64_AM::getMemExtendImm(Mem.ExtType, DoShift);
1383     Inst.addOperand(MCOperand::CreateImm(ExtendImm));
1384   }
1385
1386   void addMemoryRegisterOffset8Operands(MCInst &Inst, unsigned N) {
1387     addMemoryRegisterOffsetOperands(Inst, N, Mem.ExplicitShift);
1388   }
1389
1390   void addMemoryRegisterOffset16Operands(MCInst &Inst, unsigned N) {
1391     addMemoryRegisterOffsetOperands(Inst, N, Mem.ShiftVal == 1);
1392   }
1393
1394   void addMemoryRegisterOffset32Operands(MCInst &Inst, unsigned N) {
1395     addMemoryRegisterOffsetOperands(Inst, N, Mem.ShiftVal == 2);
1396   }
1397
1398   void addMemoryRegisterOffset64Operands(MCInst &Inst, unsigned N) {
1399     addMemoryRegisterOffsetOperands(Inst, N, Mem.ShiftVal == 3);
1400   }
1401
1402   void addMemoryRegisterOffset128Operands(MCInst &Inst, unsigned N) {
1403     addMemoryRegisterOffsetOperands(Inst, N, Mem.ShiftVal == 4);
1404   }
1405
1406   void addMemoryIndexedOperands(MCInst &Inst, unsigned N,
1407                                 unsigned Scale) const {
1408     // Add the base register operand.
1409     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1410
1411     if (!Mem.OffsetImm) {
1412       // There isn't an offset.
1413       Inst.addOperand(MCOperand::CreateImm(0));
1414       return;
1415     }
1416
1417     // Add the offset operand.
1418     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Mem.OffsetImm)) {
1419       assert(CE->getValue() % Scale == 0 &&
1420              "Offset operand must be multiple of the scale!");
1421
1422       // The MCInst offset operand doesn't include the low bits (like the
1423       // instruction encoding).
1424       Inst.addOperand(MCOperand::CreateImm(CE->getValue() / Scale));
1425     }
1426
1427     // If this is a pageoff symrefexpr with an addend, the linker will
1428     // do the scaling of the addend.
1429     //
1430     // Otherwise we don't know what this is, so just add the scaling divide to
1431     // the expression and let the MC fixup evaluation code deal with it.
1432     const MCExpr *Expr = Mem.OffsetImm;
1433     ARM64MCExpr::VariantKind ELFRefKind;
1434     MCSymbolRefExpr::VariantKind DarwinRefKind;
1435     const MCConstantExpr *Addend;
1436     if (Scale > 1 &&
1437         (!ARM64AsmParser::classifySymbolRef(Expr, ELFRefKind, DarwinRefKind,
1438                                             Addend) ||
1439          (Addend != 0 && DarwinRefKind != MCSymbolRefExpr::VK_PAGEOFF))) {
1440       Expr = MCBinaryExpr::CreateDiv(Expr, MCConstantExpr::Create(Scale, Ctx),
1441                                      Ctx);
1442     }
1443
1444     Inst.addOperand(MCOperand::CreateExpr(Expr));
1445   }
1446
1447   void addMemoryUnscaledOperands(MCInst &Inst, unsigned N) const {
1448     assert(N == 2 && isMemoryUnscaled() && "Invalid number of operands!");
1449     // Add the base register operand.
1450     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1451
1452     // Add the offset operand.
1453     if (!Mem.OffsetImm)
1454       Inst.addOperand(MCOperand::CreateImm(0));
1455     else {
1456       // Only constant offsets supported.
1457       const MCConstantExpr *CE = cast<MCConstantExpr>(Mem.OffsetImm);
1458       Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
1459     }
1460   }
1461
1462   void addMemoryIndexed128Operands(MCInst &Inst, unsigned N) const {
1463     assert(N == 2 && isMemoryIndexed128() && "Invalid number of operands!");
1464     addMemoryIndexedOperands(Inst, N, 16);
1465   }
1466
1467   void addMemoryIndexed64Operands(MCInst &Inst, unsigned N) const {
1468     assert(N == 2 && isMemoryIndexed64() && "Invalid number of operands!");
1469     addMemoryIndexedOperands(Inst, N, 8);
1470   }
1471
1472   void addMemoryIndexed32Operands(MCInst &Inst, unsigned N) const {
1473     assert(N == 2 && isMemoryIndexed32() && "Invalid number of operands!");
1474     addMemoryIndexedOperands(Inst, N, 4);
1475   }
1476
1477   void addMemoryIndexed16Operands(MCInst &Inst, unsigned N) const {
1478     assert(N == 2 && isMemoryIndexed16() && "Invalid number of operands!");
1479     addMemoryIndexedOperands(Inst, N, 2);
1480   }
1481
1482   void addMemoryIndexed8Operands(MCInst &Inst, unsigned N) const {
1483     assert(N == 2 && isMemoryIndexed8() && "Invalid number of operands!");
1484     addMemoryIndexedOperands(Inst, N, 1);
1485   }
1486
1487   void addMemoryNoIndexOperands(MCInst &Inst, unsigned N) const {
1488     assert(N == 1 && isMemoryNoIndex() && "Invalid number of operands!");
1489     // Add the base register operand (the offset is always zero, so ignore it).
1490     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1491   }
1492
1493   void addMemorySIMDNoIndexOperands(MCInst &Inst, unsigned N) const {
1494     assert(N == 1 && isMemorySIMDNoIndex() && "Invalid number of operands!");
1495     // Add the base register operand (the offset is always zero, so ignore it).
1496     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1497   }
1498
1499   void addMemoryWritebackIndexedOperands(MCInst &Inst, unsigned N,
1500                                          unsigned Scale) const {
1501     assert(N == 2 && "Invalid number of operands!");
1502
1503     // Add the base register operand.
1504     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1505
1506     // Add the offset operand.
1507     int64_t Offset = 0;
1508     if (Mem.OffsetImm) {
1509       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Mem.OffsetImm);
1510       assert(CE && "Non-constant indexed offset operand!");
1511       Offset = CE->getValue();
1512     }
1513
1514     if (Scale != 1) {
1515       assert(Offset % Scale == 0 &&
1516              "Offset operand must be a multiple of the scale!");
1517       Offset /= Scale;
1518     }
1519
1520     Inst.addOperand(MCOperand::CreateImm(Offset));
1521   }
1522
1523   void addMemoryIndexedSImm9Operands(MCInst &Inst, unsigned N) const {
1524     addMemoryWritebackIndexedOperands(Inst, N, 1);
1525   }
1526
1527   void addMemoryIndexed32SImm7Operands(MCInst &Inst, unsigned N) const {
1528     addMemoryWritebackIndexedOperands(Inst, N, 4);
1529   }
1530
1531   void addMemoryIndexed64SImm7Operands(MCInst &Inst, unsigned N) const {
1532     addMemoryWritebackIndexedOperands(Inst, N, 8);
1533   }
1534
1535   void addMemoryIndexed128SImm7Operands(MCInst &Inst, unsigned N) const {
1536     addMemoryWritebackIndexedOperands(Inst, N, 16);
1537   }
1538
1539   virtual void print(raw_ostream &OS) const;
1540
1541   static ARM64Operand *CreateToken(StringRef Str, bool IsSuffix, SMLoc S,
1542                                    MCContext &Ctx) {
1543     ARM64Operand *Op = new ARM64Operand(k_Token, Ctx);
1544     Op->Tok.Data = Str.data();
1545     Op->Tok.Length = Str.size();
1546     Op->Tok.IsSuffix = IsSuffix;
1547     Op->StartLoc = S;
1548     Op->EndLoc = S;
1549     return Op;
1550   }
1551
1552   static ARM64Operand *CreateReg(unsigned RegNum, bool isVector, SMLoc S,
1553                                  SMLoc E, MCContext &Ctx) {
1554     ARM64Operand *Op = new ARM64Operand(k_Register, Ctx);
1555     Op->Reg.RegNum = RegNum;
1556     Op->Reg.isVector = isVector;
1557     Op->StartLoc = S;
1558     Op->EndLoc = E;
1559     return Op;
1560   }
1561
1562   static ARM64Operand *CreateVectorList(unsigned RegNum, unsigned Count,
1563                                         unsigned NumElements, char ElementKind,
1564                                         SMLoc S, SMLoc E, MCContext &Ctx) {
1565     ARM64Operand *Op = new ARM64Operand(k_VectorList, Ctx);
1566     Op->VectorList.RegNum = RegNum;
1567     Op->VectorList.Count = Count;
1568     Op->VectorList.NumElements = NumElements;
1569     Op->VectorList.ElementKind = ElementKind;
1570     Op->StartLoc = S;
1571     Op->EndLoc = E;
1572     return Op;
1573   }
1574
1575   static ARM64Operand *CreateVectorIndex(unsigned Idx, SMLoc S, SMLoc E,
1576                                          MCContext &Ctx) {
1577     ARM64Operand *Op = new ARM64Operand(k_VectorIndex, Ctx);
1578     Op->VectorIndex.Val = Idx;
1579     Op->StartLoc = S;
1580     Op->EndLoc = E;
1581     return Op;
1582   }
1583
1584   static ARM64Operand *CreateImm(const MCExpr *Val, SMLoc S, SMLoc E,
1585                                  MCContext &Ctx) {
1586     ARM64Operand *Op = new ARM64Operand(k_Immediate, Ctx);
1587     Op->Imm.Val = Val;
1588     Op->StartLoc = S;
1589     Op->EndLoc = E;
1590     return Op;
1591   }
1592
1593   static ARM64Operand *CreateFPImm(unsigned Val, SMLoc S, MCContext &Ctx) {
1594     ARM64Operand *Op = new ARM64Operand(k_FPImm, Ctx);
1595     Op->FPImm.Val = Val;
1596     Op->StartLoc = S;
1597     Op->EndLoc = S;
1598     return Op;
1599   }
1600
1601   static ARM64Operand *CreateBarrier(unsigned Val, SMLoc S, MCContext &Ctx) {
1602     ARM64Operand *Op = new ARM64Operand(k_Barrier, Ctx);
1603     Op->Barrier.Val = Val;
1604     Op->StartLoc = S;
1605     Op->EndLoc = S;
1606     return Op;
1607   }
1608
1609   static ARM64Operand *CreateSystemRegister(uint16_t Val, SMLoc S,
1610                                             MCContext &Ctx) {
1611     ARM64Operand *Op = new ARM64Operand(k_SystemRegister, Ctx);
1612     Op->SystemRegister.Val = Val;
1613     Op->StartLoc = S;
1614     Op->EndLoc = S;
1615     return Op;
1616   }
1617
1618   static ARM64Operand *CreateCPSRField(ARM64PState::PStateValues Field, SMLoc S,
1619                                        MCContext &Ctx) {
1620     ARM64Operand *Op = new ARM64Operand(k_CPSRField, Ctx);
1621     Op->CPSRField.Field = Field;
1622     Op->StartLoc = S;
1623     Op->EndLoc = S;
1624     return Op;
1625   }
1626
1627   static ARM64Operand *CreateMem(unsigned BaseRegNum, const MCExpr *Off,
1628                                  SMLoc S, SMLoc E, SMLoc OffsetLoc,
1629                                  MCContext &Ctx) {
1630     ARM64Operand *Op = new ARM64Operand(k_Memory, Ctx);
1631     Op->Mem.BaseRegNum = BaseRegNum;
1632     Op->Mem.OffsetRegNum = 0;
1633     Op->Mem.OffsetImm = Off;
1634     Op->Mem.ExtType = ARM64_AM::UXTX;
1635     Op->Mem.ShiftVal = 0;
1636     Op->Mem.ExplicitShift = false;
1637     Op->Mem.Mode = ImmediateOffset;
1638     Op->OffsetLoc = OffsetLoc;
1639     Op->StartLoc = S;
1640     Op->EndLoc = E;
1641     return Op;
1642   }
1643
1644   static ARM64Operand *CreateRegOffsetMem(unsigned BaseReg, unsigned OffsetReg,
1645                                           ARM64_AM::ExtendType ExtType,
1646                                           unsigned ShiftVal, bool ExplicitShift,
1647                                           SMLoc S, SMLoc E, MCContext &Ctx) {
1648     ARM64Operand *Op = new ARM64Operand(k_Memory, Ctx);
1649     Op->Mem.BaseRegNum = BaseReg;
1650     Op->Mem.OffsetRegNum = OffsetReg;
1651     Op->Mem.OffsetImm = 0;
1652     Op->Mem.ExtType = ExtType;
1653     Op->Mem.ShiftVal = ShiftVal;
1654     Op->Mem.ExplicitShift = ExplicitShift;
1655     Op->Mem.Mode = RegisterOffset;
1656     Op->StartLoc = S;
1657     Op->EndLoc = E;
1658     return Op;
1659   }
1660
1661   static ARM64Operand *CreateSysCR(unsigned Val, SMLoc S, SMLoc E,
1662                                    MCContext &Ctx) {
1663     ARM64Operand *Op = new ARM64Operand(k_SysCR, Ctx);
1664     Op->SysCRImm.Val = Val;
1665     Op->StartLoc = S;
1666     Op->EndLoc = E;
1667     return Op;
1668   }
1669
1670   static ARM64Operand *CreatePrefetch(unsigned Val, SMLoc S, MCContext &Ctx) {
1671     ARM64Operand *Op = new ARM64Operand(k_Prefetch, Ctx);
1672     Op->Prefetch.Val = Val;
1673     Op->StartLoc = S;
1674     Op->EndLoc = S;
1675     return Op;
1676   }
1677
1678   static ARM64Operand *CreateShifter(ARM64_AM::ShiftType ShOp, unsigned Val,
1679                                      SMLoc S, SMLoc E, MCContext &Ctx) {
1680     ARM64Operand *Op = new ARM64Operand(k_Shifter, Ctx);
1681     Op->Shifter.Val = ARM64_AM::getShifterImm(ShOp, Val);
1682     Op->StartLoc = S;
1683     Op->EndLoc = E;
1684     return Op;
1685   }
1686
1687   static ARM64Operand *CreateExtend(ARM64_AM::ExtendType ExtOp, unsigned Val,
1688                                     SMLoc S, SMLoc E, MCContext &Ctx) {
1689     ARM64Operand *Op = new ARM64Operand(k_Extend, Ctx);
1690     Op->Extend.Val = ARM64_AM::getArithExtendImm(ExtOp, Val);
1691     Op->StartLoc = S;
1692     Op->EndLoc = E;
1693     return Op;
1694   }
1695 };
1696
1697 } // end anonymous namespace.
1698
1699 void ARM64Operand::print(raw_ostream &OS) const {
1700   switch (Kind) {
1701   case k_FPImm:
1702     OS << "<fpimm " << getFPImm() << "(" << ARM64_AM::getFPImmFloat(getFPImm())
1703        << ") >";
1704     break;
1705   case k_Barrier: {
1706     bool Valid;
1707     StringRef Name = ARM64DB::DBarrierMapper().toString(getBarrier(), Valid);
1708     if (Valid)
1709       OS << "<barrier " << Name << ">";
1710     else
1711       OS << "<barrier invalid #" << getCPSRField() << ">";
1712     break;
1713   }
1714   case k_SystemRegister: {
1715     bool Valid;
1716     StringRef Name = ARM64SysReg::MRSMapper().toString(getSystemRegister(), Valid);
1717     if (!Valid)
1718       Name = ARM64SysReg::MSRMapper().toString(getSystemRegister(), Valid);
1719     if (Valid)
1720       OS << "<systemreg " << Name << ">";
1721     else
1722       OS << "<systemreg invalid #" << getSystemRegister() << ">";
1723     break;
1724   }
1725   case k_CPSRField: {
1726     bool Valid;
1727     StringRef Name = ARM64PState::PStateMapper().toString(getCPSRField(), Valid);
1728     if (Valid)
1729       OS << "<cpsrfield " << Name << ">";
1730     else
1731       OS << "<cpsrfield invalid #" << getCPSRField() << ">";
1732     break;
1733   }
1734   case k_Immediate:
1735     getImm()->print(OS);
1736     break;
1737   case k_Memory:
1738     OS << "<memory>";
1739     break;
1740   case k_Register:
1741     OS << "<register " << getReg() << ">";
1742     break;
1743   case k_VectorList: {
1744     OS << "<vectorlist ";
1745     unsigned Reg = getVectorListStart();
1746     for (unsigned i = 0, e = getVectorListCount(); i != e; ++i)
1747       OS << Reg + i << " ";
1748     OS << ">";
1749     break;
1750   }
1751   case k_VectorIndex:
1752     OS << "<vectorindex " << getVectorIndex() << ">";
1753     break;
1754   case k_Token:
1755     OS << "'" << getToken() << "'";
1756     break;
1757   case k_SysCR:
1758     OS << "c" << getSysCR();
1759     break;
1760   case k_Prefetch:
1761     OS << "<prfop ";
1762     if (ARM64_AM::isNamedPrefetchOp(getPrefetch()))
1763       OS << ARM64_AM::getPrefetchOpName((ARM64_AM::PrefetchOp)getPrefetch());
1764     else
1765       OS << "#" << getPrefetch();
1766     OS << ">";
1767     break;
1768   case k_Shifter: {
1769     unsigned Val = getShifter();
1770     OS << "<" << ARM64_AM::getShiftName(ARM64_AM::getShiftType(Val)) << " #"
1771        << ARM64_AM::getShiftValue(Val) << ">";
1772     break;
1773   }
1774   case k_Extend: {
1775     unsigned Val = getExtend();
1776     OS << "<" << ARM64_AM::getExtendName(ARM64_AM::getArithExtendType(Val))
1777        << " #" << ARM64_AM::getArithShiftValue(Val) << ">";
1778     break;
1779   }
1780   }
1781 }
1782
1783 /// @name Auto-generated Match Functions
1784 /// {
1785
1786 static unsigned MatchRegisterName(StringRef Name);
1787
1788 /// }
1789
1790 static unsigned matchVectorRegName(StringRef Name) {
1791   return StringSwitch<unsigned>(Name)
1792       .Case("v0", ARM64::Q0)
1793       .Case("v1", ARM64::Q1)
1794       .Case("v2", ARM64::Q2)
1795       .Case("v3", ARM64::Q3)
1796       .Case("v4", ARM64::Q4)
1797       .Case("v5", ARM64::Q5)
1798       .Case("v6", ARM64::Q6)
1799       .Case("v7", ARM64::Q7)
1800       .Case("v8", ARM64::Q8)
1801       .Case("v9", ARM64::Q9)
1802       .Case("v10", ARM64::Q10)
1803       .Case("v11", ARM64::Q11)
1804       .Case("v12", ARM64::Q12)
1805       .Case("v13", ARM64::Q13)
1806       .Case("v14", ARM64::Q14)
1807       .Case("v15", ARM64::Q15)
1808       .Case("v16", ARM64::Q16)
1809       .Case("v17", ARM64::Q17)
1810       .Case("v18", ARM64::Q18)
1811       .Case("v19", ARM64::Q19)
1812       .Case("v20", ARM64::Q20)
1813       .Case("v21", ARM64::Q21)
1814       .Case("v22", ARM64::Q22)
1815       .Case("v23", ARM64::Q23)
1816       .Case("v24", ARM64::Q24)
1817       .Case("v25", ARM64::Q25)
1818       .Case("v26", ARM64::Q26)
1819       .Case("v27", ARM64::Q27)
1820       .Case("v28", ARM64::Q28)
1821       .Case("v29", ARM64::Q29)
1822       .Case("v30", ARM64::Q30)
1823       .Case("v31", ARM64::Q31)
1824       .Default(0);
1825 }
1826
1827 static bool isValidVectorKind(StringRef Name) {
1828   return StringSwitch<bool>(Name.lower())
1829       .Case(".8b", true)
1830       .Case(".16b", true)
1831       .Case(".4h", true)
1832       .Case(".8h", true)
1833       .Case(".2s", true)
1834       .Case(".4s", true)
1835       .Case(".1d", true)
1836       .Case(".2d", true)
1837       .Case(".1q", true)
1838       // Accept the width neutral ones, too, for verbose syntax. If those
1839       // aren't used in the right places, the token operand won't match so
1840       // all will work out.
1841       .Case(".b", true)
1842       .Case(".h", true)
1843       .Case(".s", true)
1844       .Case(".d", true)
1845       .Default(false);
1846 }
1847
1848 static void parseValidVectorKind(StringRef Name, unsigned &NumElements,
1849                                  char &ElementKind) {
1850   assert(isValidVectorKind(Name));
1851
1852   ElementKind = Name.lower()[Name.size() - 1];
1853   NumElements = 0;
1854
1855   if (Name.size() == 2)
1856     return;
1857
1858   // Parse the lane count
1859   Name = Name.drop_front();
1860   while (isdigit(Name.front())) {
1861     NumElements = 10 * NumElements + (Name.front() - '0');
1862     Name = Name.drop_front();
1863   }
1864 }
1865
1866 bool ARM64AsmParser::ParseRegister(unsigned &RegNo, SMLoc &StartLoc,
1867                                    SMLoc &EndLoc) {
1868   StartLoc = getLoc();
1869   RegNo = tryParseRegister();
1870   EndLoc = SMLoc::getFromPointer(getLoc().getPointer() - 1);
1871   return (RegNo == (unsigned)-1);
1872 }
1873
1874 /// tryParseRegister - Try to parse a register name. The token must be an
1875 /// Identifier when called, and if it is a register name the token is eaten and
1876 /// the register is added to the operand list.
1877 int ARM64AsmParser::tryParseRegister() {
1878   const AsmToken &Tok = Parser.getTok();
1879   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
1880
1881   std::string lowerCase = Tok.getString().lower();
1882   unsigned RegNum = MatchRegisterName(lowerCase);
1883   // Also handle a few aliases of registers.
1884   if (RegNum == 0)
1885     RegNum = StringSwitch<unsigned>(lowerCase)
1886                  .Case("x29", ARM64::FP)
1887                  .Case("x30", ARM64::LR)
1888                  .Case("x31", ARM64::XZR)
1889                  .Case("w31", ARM64::WZR)
1890                  .Default(0);
1891
1892   if (RegNum == 0)
1893     return -1;
1894
1895   Parser.Lex(); // Eat identifier token.
1896   return RegNum;
1897 }
1898
1899 /// tryMatchVectorRegister - Try to parse a vector register name with optional
1900 /// kind specifier. If it is a register specifier, eat the token and return it.
1901 int ARM64AsmParser::tryMatchVectorRegister(StringRef &Kind, bool expected) {
1902   if (Parser.getTok().isNot(AsmToken::Identifier)) {
1903     TokError("vector register expected");
1904     return -1;
1905   }
1906
1907   StringRef Name = Parser.getTok().getString();
1908   // If there is a kind specifier, it's separated from the register name by
1909   // a '.'.
1910   size_t Start = 0, Next = Name.find('.');
1911   StringRef Head = Name.slice(Start, Next);
1912   unsigned RegNum = matchVectorRegName(Head);
1913   if (RegNum) {
1914     if (Next != StringRef::npos) {
1915       Kind = Name.slice(Next, StringRef::npos);
1916       if (!isValidVectorKind(Kind)) {
1917         TokError("invalid vector kind qualifier");
1918         return -1;
1919       }
1920     }
1921     Parser.Lex(); // Eat the register token.
1922     return RegNum;
1923   }
1924
1925   if (expected)
1926     TokError("vector register expected");
1927   return -1;
1928 }
1929
1930 static int MatchSysCRName(StringRef Name) {
1931   // Use the same layout as the tablegen'erated register name matcher. Ugly,
1932   // but efficient.
1933   switch (Name.size()) {
1934   default:
1935     break;
1936   case 2:
1937     if (Name[0] != 'c' && Name[0] != 'C')
1938       return -1;
1939     switch (Name[1]) {
1940     default:
1941       return -1;
1942     case '0':
1943       return 0;
1944     case '1':
1945       return 1;
1946     case '2':
1947       return 2;
1948     case '3':
1949       return 3;
1950     case '4':
1951       return 4;
1952     case '5':
1953       return 5;
1954     case '6':
1955       return 6;
1956     case '7':
1957       return 7;
1958     case '8':
1959       return 8;
1960     case '9':
1961       return 9;
1962     }
1963     break;
1964   case 3:
1965     if ((Name[0] != 'c' && Name[0] != 'C') || Name[1] != '1')
1966       return -1;
1967     switch (Name[2]) {
1968     default:
1969       return -1;
1970     case '0':
1971       return 10;
1972     case '1':
1973       return 11;
1974     case '2':
1975       return 12;
1976     case '3':
1977       return 13;
1978     case '4':
1979       return 14;
1980     case '5':
1981       return 15;
1982     }
1983     break;
1984   }
1985
1986   llvm_unreachable("Unhandled SysCR operand string!");
1987   return -1;
1988 }
1989
1990 /// tryParseSysCROperand - Try to parse a system instruction CR operand name.
1991 ARM64AsmParser::OperandMatchResultTy
1992 ARM64AsmParser::tryParseSysCROperand(OperandVector &Operands) {
1993   SMLoc S = getLoc();
1994   const AsmToken &Tok = Parser.getTok();
1995   if (Tok.isNot(AsmToken::Identifier))
1996     return MatchOperand_NoMatch;
1997
1998   int Num = MatchSysCRName(Tok.getString());
1999   if (Num == -1)
2000     return MatchOperand_NoMatch;
2001
2002   Parser.Lex(); // Eat identifier token.
2003   Operands.push_back(ARM64Operand::CreateSysCR(Num, S, getLoc(), getContext()));
2004   return MatchOperand_Success;
2005 }
2006
2007 /// tryParsePrefetch - Try to parse a prefetch operand.
2008 ARM64AsmParser::OperandMatchResultTy
2009 ARM64AsmParser::tryParsePrefetch(OperandVector &Operands) {
2010   SMLoc S = getLoc();
2011   const AsmToken &Tok = Parser.getTok();
2012   // Either an identifier for named values or a 5-bit immediate.
2013   if (Tok.is(AsmToken::Hash)) {
2014     Parser.Lex(); // Eat hash token.
2015     const MCExpr *ImmVal;
2016     if (getParser().parseExpression(ImmVal))
2017       return MatchOperand_ParseFail;
2018
2019     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(ImmVal);
2020     if (!MCE) {
2021       TokError("immediate value expected for prefetch operand");
2022       return MatchOperand_ParseFail;
2023     }
2024     unsigned prfop = MCE->getValue();
2025     if (prfop > 31) {
2026       TokError("prefetch operand out of range, [0,31] expected");
2027       return MatchOperand_ParseFail;
2028     }
2029
2030     Operands.push_back(ARM64Operand::CreatePrefetch(prfop, S, getContext()));
2031     return MatchOperand_Success;
2032   }
2033
2034   if (Tok.isNot(AsmToken::Identifier)) {
2035     TokError("pre-fetch hint expected");
2036     return MatchOperand_ParseFail;
2037   }
2038
2039   unsigned prfop = StringSwitch<unsigned>(Tok.getString())
2040                        .Case("pldl1keep", ARM64_AM::PLDL1KEEP)
2041                        .Case("pldl1strm", ARM64_AM::PLDL1STRM)
2042                        .Case("pldl2keep", ARM64_AM::PLDL2KEEP)
2043                        .Case("pldl2strm", ARM64_AM::PLDL2STRM)
2044                        .Case("pldl3keep", ARM64_AM::PLDL3KEEP)
2045                        .Case("pldl3strm", ARM64_AM::PLDL3STRM)
2046                        .Case("pstl1keep", ARM64_AM::PSTL1KEEP)
2047                        .Case("pstl1strm", ARM64_AM::PSTL1STRM)
2048                        .Case("pstl2keep", ARM64_AM::PSTL2KEEP)
2049                        .Case("pstl2strm", ARM64_AM::PSTL2STRM)
2050                        .Case("pstl3keep", ARM64_AM::PSTL3KEEP)
2051                        .Case("pstl3strm", ARM64_AM::PSTL3STRM)
2052                        .Default(0xff);
2053   if (prfop == 0xff) {
2054     TokError("pre-fetch hint expected");
2055     return MatchOperand_ParseFail;
2056   }
2057
2058   Parser.Lex(); // Eat identifier token.
2059   Operands.push_back(ARM64Operand::CreatePrefetch(prfop, S, getContext()));
2060   return MatchOperand_Success;
2061 }
2062
2063 /// tryParseAdrpLabel - Parse and validate a source label for the ADRP
2064 /// instruction.
2065 ARM64AsmParser::OperandMatchResultTy
2066 ARM64AsmParser::tryParseAdrpLabel(OperandVector &Operands) {
2067   SMLoc S = getLoc();
2068   const MCExpr *Expr;
2069   if (parseSymbolicImmVal(Expr))
2070     return MatchOperand_ParseFail;
2071
2072   ARM64MCExpr::VariantKind ELFRefKind;
2073   MCSymbolRefExpr::VariantKind DarwinRefKind;
2074   const MCConstantExpr *Addend;
2075   if (!classifySymbolRef(Expr, ELFRefKind, DarwinRefKind, Addend)) {
2076     Error(S, "modified label reference + constant expected");
2077     return MatchOperand_ParseFail;
2078   }
2079
2080   if (DarwinRefKind == MCSymbolRefExpr::VK_None &&
2081       ELFRefKind == ARM64MCExpr::VK_INVALID) {
2082     // No modifier was specified at all; this is the syntax for an ELF basic
2083     // ADRP relocation (unfortunately).
2084     Expr = ARM64MCExpr::Create(Expr, ARM64MCExpr::VK_ABS_PAGE, getContext());
2085   } else if ((DarwinRefKind == MCSymbolRefExpr::VK_GOTPAGE ||
2086               DarwinRefKind == MCSymbolRefExpr::VK_TLVPPAGE) &&
2087              Addend != 0) {
2088     Error(S, "gotpage label reference not allowed an addend");
2089     return MatchOperand_ParseFail;
2090   } else if (DarwinRefKind != MCSymbolRefExpr::VK_PAGE &&
2091              DarwinRefKind != MCSymbolRefExpr::VK_GOTPAGE &&
2092              DarwinRefKind != MCSymbolRefExpr::VK_TLVPPAGE &&
2093              ELFRefKind != ARM64MCExpr::VK_GOT_PAGE &&
2094              ELFRefKind != ARM64MCExpr::VK_GOTTPREL_PAGE &&
2095              ELFRefKind != ARM64MCExpr::VK_TLSDESC_PAGE) {
2096     // The operand must be an @page or @gotpage qualified symbolref.
2097     Error(S, "page or gotpage label reference expected");
2098     return MatchOperand_ParseFail;
2099   }
2100
2101   // We have a label reference possibly with addend. The addend is a raw value
2102   // here. The linker will adjust it to only reference the page.
2103   SMLoc E = SMLoc::getFromPointer(getLoc().getPointer() - 1);
2104   Operands.push_back(ARM64Operand::CreateImm(Expr, S, E, getContext()));
2105
2106   return MatchOperand_Success;
2107 }
2108
2109 /// tryParseAdrLabel - Parse and validate a source label for the ADR
2110 /// instruction.
2111 ARM64AsmParser::OperandMatchResultTy
2112 ARM64AsmParser::tryParseAdrLabel(OperandVector &Operands) {
2113   SMLoc S = getLoc();
2114   const MCExpr *Expr;
2115   if (getParser().parseExpression(Expr))
2116     return MatchOperand_ParseFail;
2117
2118   // The operand must be an un-qualified assembler local symbolref.
2119   // FIXME: wrong for ELF.
2120   if (const MCSymbolRefExpr *SRE = dyn_cast<const MCSymbolRefExpr>(Expr)) {
2121     // FIXME: Should reference the MachineAsmInfo to get the private prefix.
2122     bool isTemporary = SRE->getSymbol().getName().startswith("L");
2123     if (!isTemporary || SRE->getKind() != MCSymbolRefExpr::VK_None) {
2124       Error(S, "unqualified, assembler-local label name expected");
2125       return MatchOperand_ParseFail;
2126     }
2127   }
2128
2129   SMLoc E = SMLoc::getFromPointer(getLoc().getPointer() - 1);
2130   Operands.push_back(ARM64Operand::CreateImm(Expr, S, E, getContext()));
2131
2132   return MatchOperand_Success;
2133 }
2134
2135 /// tryParseFPImm - A floating point immediate expression operand.
2136 ARM64AsmParser::OperandMatchResultTy
2137 ARM64AsmParser::tryParseFPImm(OperandVector &Operands) {
2138   SMLoc S = getLoc();
2139
2140   if (Parser.getTok().isNot(AsmToken::Hash))
2141     return MatchOperand_NoMatch;
2142   Parser.Lex(); // Eat the '#'.
2143
2144   // Handle negation, as that still comes through as a separate token.
2145   bool isNegative = false;
2146   if (Parser.getTok().is(AsmToken::Minus)) {
2147     isNegative = true;
2148     Parser.Lex();
2149   }
2150   const AsmToken &Tok = Parser.getTok();
2151   if (Tok.is(AsmToken::Real)) {
2152     APFloat RealVal(APFloat::IEEEdouble, Tok.getString());
2153     uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
2154     // If we had a '-' in front, toggle the sign bit.
2155     IntVal ^= (uint64_t)isNegative << 63;
2156     int Val = ARM64_AM::getFP64Imm(APInt(64, IntVal));
2157     Parser.Lex(); // Eat the token.
2158     // Check for out of range values. As an exception, we let Zero through,
2159     // as we handle that special case in post-processing before matching in
2160     // order to use the zero register for it.
2161     if (Val == -1 && !RealVal.isZero()) {
2162       TokError("floating point value out of range");
2163       return MatchOperand_ParseFail;
2164     }
2165     Operands.push_back(ARM64Operand::CreateFPImm(Val, S, getContext()));
2166     return MatchOperand_Success;
2167   }
2168   if (Tok.is(AsmToken::Integer)) {
2169     int64_t Val;
2170     if (!isNegative && Tok.getString().startswith("0x")) {
2171       Val = Tok.getIntVal();
2172       if (Val > 255 || Val < 0) {
2173         TokError("encoded floating point value out of range");
2174         return MatchOperand_ParseFail;
2175       }
2176     } else {
2177       APFloat RealVal(APFloat::IEEEdouble, Tok.getString());
2178       uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
2179       // If we had a '-' in front, toggle the sign bit.
2180       IntVal ^= (uint64_t)isNegative << 63;
2181       Val = ARM64_AM::getFP64Imm(APInt(64, IntVal));
2182     }
2183     Parser.Lex(); // Eat the token.
2184     Operands.push_back(ARM64Operand::CreateFPImm(Val, S, getContext()));
2185     return MatchOperand_Success;
2186   }
2187
2188   TokError("invalid floating point immediate");
2189   return MatchOperand_ParseFail;
2190 }
2191
2192 /// parseCondCodeString - Parse a Condition Code string.
2193 unsigned ARM64AsmParser::parseCondCodeString(StringRef Cond) {
2194   unsigned CC = StringSwitch<unsigned>(Cond.lower())
2195                     .Case("eq", ARM64CC::EQ)
2196                     .Case("ne", ARM64CC::NE)
2197                     .Case("cs", ARM64CC::CS)
2198                     .Case("hs", ARM64CC::CS)
2199                     .Case("cc", ARM64CC::CC)
2200                     .Case("lo", ARM64CC::CC)
2201                     .Case("mi", ARM64CC::MI)
2202                     .Case("pl", ARM64CC::PL)
2203                     .Case("vs", ARM64CC::VS)
2204                     .Case("vc", ARM64CC::VC)
2205                     .Case("hi", ARM64CC::HI)
2206                     .Case("ls", ARM64CC::LS)
2207                     .Case("ge", ARM64CC::GE)
2208                     .Case("lt", ARM64CC::LT)
2209                     .Case("gt", ARM64CC::GT)
2210                     .Case("le", ARM64CC::LE)
2211                     .Case("al", ARM64CC::AL)
2212                     .Case("nv", ARM64CC::NV)
2213                     .Default(ARM64CC::Invalid);
2214   return CC;
2215 }
2216
2217 /// parseCondCode - Parse a Condition Code operand.
2218 bool ARM64AsmParser::parseCondCode(OperandVector &Operands,
2219                                    bool invertCondCode) {
2220   SMLoc S = getLoc();
2221   const AsmToken &Tok = Parser.getTok();
2222   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
2223
2224   StringRef Cond = Tok.getString();
2225   unsigned CC = parseCondCodeString(Cond);
2226   if (CC == ARM64CC::Invalid)
2227     return TokError("invalid condition code");
2228   Parser.Lex(); // Eat identifier token.
2229
2230   if (invertCondCode)
2231     CC = ARM64CC::getInvertedCondCode(ARM64CC::CondCode(CC));
2232
2233   const MCExpr *CCExpr = MCConstantExpr::Create(CC, getContext());
2234   Operands.push_back(
2235       ARM64Operand::CreateImm(CCExpr, S, getLoc(), getContext()));
2236   return false;
2237 }
2238
2239 /// ParseOptionalShift - Some operands take an optional shift argument. Parse
2240 /// them if present.
2241 bool ARM64AsmParser::parseOptionalShift(OperandVector &Operands) {
2242   const AsmToken &Tok = Parser.getTok();
2243   ARM64_AM::ShiftType ShOp = StringSwitch<ARM64_AM::ShiftType>(Tok.getString())
2244                                  .Case("lsl", ARM64_AM::LSL)
2245                                  .Case("lsr", ARM64_AM::LSR)
2246                                  .Case("asr", ARM64_AM::ASR)
2247                                  .Case("ror", ARM64_AM::ROR)
2248                                  .Case("msl", ARM64_AM::MSL)
2249                                  .Case("LSL", ARM64_AM::LSL)
2250                                  .Case("LSR", ARM64_AM::LSR)
2251                                  .Case("ASR", ARM64_AM::ASR)
2252                                  .Case("ROR", ARM64_AM::ROR)
2253                                  .Case("MSL", ARM64_AM::MSL)
2254                                  .Default(ARM64_AM::InvalidShift);
2255   if (ShOp == ARM64_AM::InvalidShift)
2256     return true;
2257
2258   SMLoc S = Tok.getLoc();
2259   Parser.Lex();
2260
2261   // We expect a number here.
2262   if (getLexer().isNot(AsmToken::Hash))
2263     return TokError("immediate value expected for shifter operand");
2264   Parser.Lex(); // Eat the '#'.
2265
2266   SMLoc ExprLoc = getLoc();
2267   const MCExpr *ImmVal;
2268   if (getParser().parseExpression(ImmVal))
2269     return true;
2270
2271   const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(ImmVal);
2272   if (!MCE)
2273     return TokError("immediate value expected for shifter operand");
2274
2275   if ((MCE->getValue() & 0x3f) != MCE->getValue())
2276     return Error(ExprLoc, "immediate value too large for shifter operand");
2277
2278   SMLoc E = SMLoc::getFromPointer(getLoc().getPointer() - 1);
2279   Operands.push_back(
2280       ARM64Operand::CreateShifter(ShOp, MCE->getValue(), S, E, getContext()));
2281   return false;
2282 }
2283
2284 /// parseOptionalExtend - Some operands take an optional extend argument. Parse
2285 /// them if present.
2286 bool ARM64AsmParser::parseOptionalExtend(OperandVector &Operands) {
2287   const AsmToken &Tok = Parser.getTok();
2288   ARM64_AM::ExtendType ExtOp =
2289       StringSwitch<ARM64_AM::ExtendType>(Tok.getString())
2290           .Case("uxtb", ARM64_AM::UXTB)
2291           .Case("uxth", ARM64_AM::UXTH)
2292           .Case("uxtw", ARM64_AM::UXTW)
2293           .Case("uxtx", ARM64_AM::UXTX)
2294           .Case("lsl", ARM64_AM::UXTX) // Alias for UXTX
2295           .Case("sxtb", ARM64_AM::SXTB)
2296           .Case("sxth", ARM64_AM::SXTH)
2297           .Case("sxtw", ARM64_AM::SXTW)
2298           .Case("sxtx", ARM64_AM::SXTX)
2299           .Case("UXTB", ARM64_AM::UXTB)
2300           .Case("UXTH", ARM64_AM::UXTH)
2301           .Case("UXTW", ARM64_AM::UXTW)
2302           .Case("UXTX", ARM64_AM::UXTX)
2303           .Case("LSL", ARM64_AM::UXTX) // Alias for UXTX
2304           .Case("SXTB", ARM64_AM::SXTB)
2305           .Case("SXTH", ARM64_AM::SXTH)
2306           .Case("SXTW", ARM64_AM::SXTW)
2307           .Case("SXTX", ARM64_AM::SXTX)
2308           .Default(ARM64_AM::InvalidExtend);
2309   if (ExtOp == ARM64_AM::InvalidExtend)
2310     return true;
2311
2312   SMLoc S = Tok.getLoc();
2313   Parser.Lex();
2314
2315   if (getLexer().is(AsmToken::EndOfStatement) ||
2316       getLexer().is(AsmToken::Comma)) {
2317     SMLoc E = SMLoc::getFromPointer(getLoc().getPointer() - 1);
2318     Operands.push_back(
2319         ARM64Operand::CreateExtend(ExtOp, 0, S, E, getContext()));
2320     return false;
2321   }
2322
2323   if (getLexer().isNot(AsmToken::Hash)) {
2324     SMLoc E = SMLoc::getFromPointer(getLoc().getPointer() - 1);
2325     Operands.push_back(
2326         ARM64Operand::CreateExtend(ExtOp, 0, S, E, getContext()));
2327     return false;
2328   }
2329
2330   Parser.Lex(); // Eat the '#'.
2331
2332   const MCExpr *ImmVal;
2333   if (getParser().parseExpression(ImmVal))
2334     return true;
2335
2336   const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(ImmVal);
2337   if (!MCE)
2338     return TokError("immediate value expected for extend operand");
2339
2340   SMLoc E = SMLoc::getFromPointer(getLoc().getPointer() - 1);
2341   Operands.push_back(
2342       ARM64Operand::CreateExtend(ExtOp, MCE->getValue(), S, E, getContext()));
2343   return false;
2344 }
2345
2346 /// parseSysAlias - The IC, DC, AT, and TLBI instructions are simple aliases for
2347 /// the SYS instruction. Parse them specially so that we create a SYS MCInst.
2348 bool ARM64AsmParser::parseSysAlias(StringRef Name, SMLoc NameLoc,
2349                                    OperandVector &Operands) {
2350   if (Name.find('.') != StringRef::npos)
2351     return TokError("invalid operand");
2352
2353   Mnemonic = Name;
2354   Operands.push_back(
2355       ARM64Operand::CreateToken("sys", false, NameLoc, getContext()));
2356
2357   const AsmToken &Tok = Parser.getTok();
2358   StringRef Op = Tok.getString();
2359   SMLoc S = Tok.getLoc();
2360
2361   const MCExpr *Expr = 0;
2362
2363 #define SYS_ALIAS(op1, Cn, Cm, op2)                                            \
2364   do {                                                                         \
2365     Expr = MCConstantExpr::Create(op1, getContext());                          \
2366     Operands.push_back(                                                        \
2367         ARM64Operand::CreateImm(Expr, S, getLoc(), getContext()));             \
2368     Operands.push_back(                                                        \
2369         ARM64Operand::CreateSysCR(Cn, S, getLoc(), getContext()));             \
2370     Operands.push_back(                                                        \
2371         ARM64Operand::CreateSysCR(Cm, S, getLoc(), getContext()));             \
2372     Expr = MCConstantExpr::Create(op2, getContext());                          \
2373     Operands.push_back(                                                        \
2374         ARM64Operand::CreateImm(Expr, S, getLoc(), getContext()));             \
2375   } while (0)
2376
2377   if (Mnemonic == "ic") {
2378     if (!Op.compare_lower("ialluis")) {
2379       // SYS #0, C7, C1, #0
2380       SYS_ALIAS(0, 7, 1, 0);
2381     } else if (!Op.compare_lower("iallu")) {
2382       // SYS #0, C7, C5, #0
2383       SYS_ALIAS(0, 7, 5, 0);
2384     } else if (!Op.compare_lower("ivau")) {
2385       // SYS #3, C7, C5, #1
2386       SYS_ALIAS(3, 7, 5, 1);
2387     } else {
2388       return TokError("invalid operand for IC instruction");
2389     }
2390   } else if (Mnemonic == "dc") {
2391     if (!Op.compare_lower("zva")) {
2392       // SYS #3, C7, C4, #1
2393       SYS_ALIAS(3, 7, 4, 1);
2394     } else if (!Op.compare_lower("ivac")) {
2395       // SYS #3, C7, C6, #1
2396       SYS_ALIAS(0, 7, 6, 1);
2397     } else if (!Op.compare_lower("isw")) {
2398       // SYS #0, C7, C6, #2
2399       SYS_ALIAS(0, 7, 6, 2);
2400     } else if (!Op.compare_lower("cvac")) {
2401       // SYS #3, C7, C10, #1
2402       SYS_ALIAS(3, 7, 10, 1);
2403     } else if (!Op.compare_lower("csw")) {
2404       // SYS #0, C7, C10, #2
2405       SYS_ALIAS(0, 7, 10, 2);
2406     } else if (!Op.compare_lower("cvau")) {
2407       // SYS #3, C7, C11, #1
2408       SYS_ALIAS(3, 7, 11, 1);
2409     } else if (!Op.compare_lower("civac")) {
2410       // SYS #3, C7, C14, #1
2411       SYS_ALIAS(3, 7, 14, 1);
2412     } else if (!Op.compare_lower("cisw")) {
2413       // SYS #0, C7, C14, #2
2414       SYS_ALIAS(0, 7, 14, 2);
2415     } else {
2416       return TokError("invalid operand for DC instruction");
2417     }
2418   } else if (Mnemonic == "at") {
2419     if (!Op.compare_lower("s1e1r")) {
2420       // SYS #0, C7, C8, #0
2421       SYS_ALIAS(0, 7, 8, 0);
2422     } else if (!Op.compare_lower("s1e2r")) {
2423       // SYS #4, C7, C8, #0
2424       SYS_ALIAS(4, 7, 8, 0);
2425     } else if (!Op.compare_lower("s1e3r")) {
2426       // SYS #6, C7, C8, #0
2427       SYS_ALIAS(6, 7, 8, 0);
2428     } else if (!Op.compare_lower("s1e1w")) {
2429       // SYS #0, C7, C8, #1
2430       SYS_ALIAS(0, 7, 8, 1);
2431     } else if (!Op.compare_lower("s1e2w")) {
2432       // SYS #4, C7, C8, #1
2433       SYS_ALIAS(4, 7, 8, 1);
2434     } else if (!Op.compare_lower("s1e3w")) {
2435       // SYS #6, C7, C8, #1
2436       SYS_ALIAS(6, 7, 8, 1);
2437     } else if (!Op.compare_lower("s1e0r")) {
2438       // SYS #0, C7, C8, #3
2439       SYS_ALIAS(0, 7, 8, 2);
2440     } else if (!Op.compare_lower("s1e0w")) {
2441       // SYS #0, C7, C8, #3
2442       SYS_ALIAS(0, 7, 8, 3);
2443     } else if (!Op.compare_lower("s12e1r")) {
2444       // SYS #4, C7, C8, #4
2445       SYS_ALIAS(4, 7, 8, 4);
2446     } else if (!Op.compare_lower("s12e1w")) {
2447       // SYS #4, C7, C8, #5
2448       SYS_ALIAS(4, 7, 8, 5);
2449     } else if (!Op.compare_lower("s12e0r")) {
2450       // SYS #4, C7, C8, #6
2451       SYS_ALIAS(4, 7, 8, 6);
2452     } else if (!Op.compare_lower("s12e0w")) {
2453       // SYS #4, C7, C8, #7
2454       SYS_ALIAS(4, 7, 8, 7);
2455     } else {
2456       return TokError("invalid operand for AT instruction");
2457     }
2458   } else if (Mnemonic == "tlbi") {
2459     if (!Op.compare_lower("vmalle1is")) {
2460       // SYS #0, C8, C3, #0
2461       SYS_ALIAS(0, 8, 3, 0);
2462     } else if (!Op.compare_lower("alle2is")) {
2463       // SYS #4, C8, C3, #0
2464       SYS_ALIAS(4, 8, 3, 0);
2465     } else if (!Op.compare_lower("alle3is")) {
2466       // SYS #6, C8, C3, #0
2467       SYS_ALIAS(6, 8, 3, 0);
2468     } else if (!Op.compare_lower("vae1is")) {
2469       // SYS #0, C8, C3, #1
2470       SYS_ALIAS(0, 8, 3, 1);
2471     } else if (!Op.compare_lower("vae2is")) {
2472       // SYS #4, C8, C3, #1
2473       SYS_ALIAS(4, 8, 3, 1);
2474     } else if (!Op.compare_lower("vae3is")) {
2475       // SYS #6, C8, C3, #1
2476       SYS_ALIAS(6, 8, 3, 1);
2477     } else if (!Op.compare_lower("aside1is")) {
2478       // SYS #0, C8, C3, #2
2479       SYS_ALIAS(0, 8, 3, 2);
2480     } else if (!Op.compare_lower("vaae1is")) {
2481       // SYS #0, C8, C3, #3
2482       SYS_ALIAS(0, 8, 3, 3);
2483     } else if (!Op.compare_lower("alle1is")) {
2484       // SYS #4, C8, C3, #4
2485       SYS_ALIAS(4, 8, 3, 4);
2486     } else if (!Op.compare_lower("vale1is")) {
2487       // SYS #0, C8, C3, #5
2488       SYS_ALIAS(0, 8, 3, 5);
2489     } else if (!Op.compare_lower("vaale1is")) {
2490       // SYS #0, C8, C3, #7
2491       SYS_ALIAS(0, 8, 3, 7);
2492     } else if (!Op.compare_lower("vmalle1")) {
2493       // SYS #0, C8, C7, #0
2494       SYS_ALIAS(0, 8, 7, 0);
2495     } else if (!Op.compare_lower("alle2")) {
2496       // SYS #4, C8, C7, #0
2497       SYS_ALIAS(4, 8, 7, 0);
2498     } else if (!Op.compare_lower("vale2is")) {
2499       // SYS #4, C8, C3, #5
2500       SYS_ALIAS(4, 8, 3, 5);
2501     } else if (!Op.compare_lower("vale3is")) {
2502       // SYS #6, C8, C3, #5
2503       SYS_ALIAS(6, 8, 3, 5);
2504     } else if (!Op.compare_lower("alle3")) {
2505       // SYS #6, C8, C7, #0
2506       SYS_ALIAS(6, 8, 7, 0);
2507     } else if (!Op.compare_lower("vae1")) {
2508       // SYS #0, C8, C7, #1
2509       SYS_ALIAS(0, 8, 7, 1);
2510     } else if (!Op.compare_lower("vae2")) {
2511       // SYS #4, C8, C7, #1
2512       SYS_ALIAS(4, 8, 7, 1);
2513     } else if (!Op.compare_lower("vae3")) {
2514       // SYS #6, C8, C7, #1
2515       SYS_ALIAS(6, 8, 7, 1);
2516     } else if (!Op.compare_lower("aside1")) {
2517       // SYS #0, C8, C7, #2
2518       SYS_ALIAS(0, 8, 7, 2);
2519     } else if (!Op.compare_lower("vaae1")) {
2520       // SYS #0, C8, C7, #3
2521       SYS_ALIAS(0, 8, 7, 3);
2522     } else if (!Op.compare_lower("alle1")) {
2523       // SYS #4, C8, C7, #4
2524       SYS_ALIAS(4, 8, 7, 4);
2525     } else if (!Op.compare_lower("vale1")) {
2526       // SYS #0, C8, C7, #5
2527       SYS_ALIAS(0, 8, 7, 5);
2528     } else if (!Op.compare_lower("vale2")) {
2529       // SYS #4, C8, C7, #5
2530       SYS_ALIAS(4, 8, 7, 5);
2531     } else if (!Op.compare_lower("vale3")) {
2532       // SYS #6, C8, C7, #5
2533       SYS_ALIAS(6, 8, 7, 5);
2534     } else if (!Op.compare_lower("vaale1")) {
2535       // SYS #0, C8, C7, #7
2536       SYS_ALIAS(0, 8, 7, 7);
2537     } else if (!Op.compare_lower("ipas2e1")) {
2538       // SYS #4, C8, C4, #1
2539       SYS_ALIAS(4, 8, 4, 1);
2540     } else if (!Op.compare_lower("ipas2le1")) {
2541       // SYS #4, C8, C4, #5
2542       SYS_ALIAS(4, 8, 4, 5);
2543     } else if (!Op.compare_lower("vmalls12e1")) {
2544       // SYS #4, C8, C7, #6
2545       SYS_ALIAS(4, 8, 7, 6);
2546     } else if (!Op.compare_lower("vmalls12e1is")) {
2547       // SYS #4, C8, C3, #6
2548       SYS_ALIAS(4, 8, 3, 6);
2549     } else {
2550       return TokError("invalid operand for TLBI instruction");
2551     }
2552   }
2553
2554 #undef SYS_ALIAS
2555
2556   Parser.Lex(); // Eat operand.
2557
2558   // Check for the optional register operand.
2559   if (getLexer().is(AsmToken::Comma)) {
2560     Parser.Lex(); // Eat comma.
2561
2562     if (Tok.isNot(AsmToken::Identifier) || parseRegister(Operands))
2563       return TokError("expected register operand");
2564   }
2565
2566   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2567     Parser.eatToEndOfStatement();
2568     return TokError("unexpected token in argument list");
2569   }
2570
2571   Parser.Lex(); // Consume the EndOfStatement
2572   return false;
2573 }
2574
2575 ARM64AsmParser::OperandMatchResultTy
2576 ARM64AsmParser::tryParseBarrierOperand(OperandVector &Operands) {
2577   const AsmToken &Tok = Parser.getTok();
2578
2579   // Can be either a #imm style literal or an option name
2580   if (Tok.is(AsmToken::Hash)) {
2581     // Immediate operand.
2582     Parser.Lex(); // Eat the '#'
2583     const MCExpr *ImmVal;
2584     SMLoc ExprLoc = getLoc();
2585     if (getParser().parseExpression(ImmVal))
2586       return MatchOperand_ParseFail;
2587     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(ImmVal);
2588     if (!MCE) {
2589       Error(ExprLoc, "immediate value expected for barrier operand");
2590       return MatchOperand_ParseFail;
2591     }
2592     if (MCE->getValue() < 0 || MCE->getValue() > 15) {
2593       Error(ExprLoc, "barrier operand out of range");
2594       return MatchOperand_ParseFail;
2595     }
2596     Operands.push_back(
2597         ARM64Operand::CreateBarrier(MCE->getValue(), ExprLoc, getContext()));
2598     return MatchOperand_Success;
2599   }
2600
2601   if (Tok.isNot(AsmToken::Identifier)) {
2602     TokError("invalid operand for instruction");
2603     return MatchOperand_ParseFail;
2604   }
2605
2606   bool Valid;
2607   unsigned Opt = ARM64DB::DBarrierMapper().fromString(Tok.getString(), Valid);
2608   if (!Valid) {
2609     TokError("invalid barrier option name");
2610     return MatchOperand_ParseFail;
2611   }
2612
2613   // The only valid named option for ISB is 'sy'
2614   if (Mnemonic == "isb" && Opt != ARM64DB::SY) {
2615     TokError("'sy' or #imm operand expected");
2616     return MatchOperand_ParseFail;
2617   }
2618
2619   Operands.push_back(ARM64Operand::CreateBarrier(Opt, getLoc(), getContext()));
2620   Parser.Lex(); // Consume the option
2621
2622   return MatchOperand_Success;
2623 }
2624
2625 ARM64AsmParser::OperandMatchResultTy
2626 ARM64AsmParser::tryParseMRSSystemRegister(OperandVector &Operands) {
2627   const AsmToken &Tok = Parser.getTok();
2628
2629   if (Tok.isNot(AsmToken::Identifier))
2630     return MatchOperand_NoMatch;
2631
2632   bool Valid;
2633   auto Mapper = ARM64SysReg::MRSMapper();
2634   uint32_t Reg = Mapper.fromString(Tok.getString(), Valid);
2635   
2636   if (Valid) {
2637     Operands.push_back(
2638       ARM64Operand::CreateSystemRegister((uint16_t)Reg, getLoc(),
2639                                          getContext()));
2640     Parser.Lex(); // Consume the register name.
2641     return MatchOperand_Success;
2642   }
2643
2644   return MatchOperand_NoMatch;
2645 }
2646
2647 ARM64AsmParser::OperandMatchResultTy
2648 ARM64AsmParser::tryParseMSRSystemRegister(OperandVector &Operands) {
2649   const AsmToken &Tok = Parser.getTok();
2650
2651   if (Tok.isNot(AsmToken::Identifier))
2652     return MatchOperand_NoMatch;
2653
2654   bool Valid;
2655   auto Mapper = ARM64SysReg::MSRMapper();
2656   uint32_t Reg = Mapper.fromString(Tok.getString(), Valid);
2657   
2658   if (Valid) {
2659     Operands.push_back(
2660       ARM64Operand::CreateSystemRegister((uint16_t)Reg, getLoc(),
2661                                          getContext()));
2662     Parser.Lex(); // Consume the register name.
2663     return MatchOperand_Success;
2664   }
2665
2666   return MatchOperand_NoMatch;
2667 }
2668
2669 ARM64AsmParser::OperandMatchResultTy
2670 ARM64AsmParser::tryParseCPSRField(OperandVector &Operands) {
2671   const AsmToken &Tok = Parser.getTok();
2672
2673   if (Tok.isNot(AsmToken::Identifier))
2674     return MatchOperand_NoMatch;
2675
2676   bool Valid;
2677   ARM64PState::PStateValues Field = (ARM64PState::PStateValues)
2678     ARM64PState::PStateMapper().fromString(Tok.getString(), Valid);
2679
2680   if (!Valid)
2681     return MatchOperand_NoMatch;
2682   Operands.push_back(
2683       ARM64Operand::CreateCPSRField(Field, getLoc(), getContext()));
2684   Parser.Lex(); // Consume the register name.
2685
2686   return MatchOperand_Success;
2687 }
2688
2689 /// tryParseVectorRegister - Parse a vector register operand.
2690 bool ARM64AsmParser::tryParseVectorRegister(OperandVector &Operands) {
2691   if (Parser.getTok().isNot(AsmToken::Identifier))
2692     return true;
2693
2694   SMLoc S = getLoc();
2695   // Check for a vector register specifier first.
2696   StringRef Kind;
2697   int64_t Reg = tryMatchVectorRegister(Kind, false);
2698   if (Reg == -1)
2699     return true;
2700   Operands.push_back(
2701       ARM64Operand::CreateReg(Reg, true, S, getLoc(), getContext()));
2702   // If there was an explicit qualifier, that goes on as a literal text
2703   // operand.
2704   if (!Kind.empty())
2705     Operands.push_back(ARM64Operand::CreateToken(Kind, false, S, getContext()));
2706
2707   // If there is an index specifier following the register, parse that too.
2708   if (Parser.getTok().is(AsmToken::LBrac)) {
2709     SMLoc SIdx = getLoc();
2710     Parser.Lex(); // Eat left bracket token.
2711
2712     const MCExpr *ImmVal;
2713     if (getParser().parseExpression(ImmVal))
2714       return false;
2715     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(ImmVal);
2716     if (!MCE) {
2717       TokError("immediate value expected for vector index");
2718       return false;
2719     }
2720
2721     SMLoc E = getLoc();
2722     if (Parser.getTok().isNot(AsmToken::RBrac)) {
2723       Error(E, "']' expected");
2724       return false;
2725     }
2726
2727     Parser.Lex(); // Eat right bracket token.
2728
2729     Operands.push_back(ARM64Operand::CreateVectorIndex(MCE->getValue(), SIdx, E,
2730                                                        getContext()));
2731   }
2732
2733   return false;
2734 }
2735
2736 /// parseRegister - Parse a non-vector register operand.
2737 bool ARM64AsmParser::parseRegister(OperandVector &Operands) {
2738   SMLoc S = getLoc();
2739   // Try for a vector register.
2740   if (!tryParseVectorRegister(Operands))
2741     return false;
2742
2743   // Try for a scalar register.
2744   int64_t Reg = tryParseRegister();
2745   if (Reg == -1)
2746     return true;
2747   Operands.push_back(
2748       ARM64Operand::CreateReg(Reg, false, S, getLoc(), getContext()));
2749
2750   // A small number of instructions (FMOVXDhighr, for example) have "[1]"
2751   // as a string token in the instruction itself.
2752   if (getLexer().getKind() == AsmToken::LBrac) {
2753     SMLoc LBracS = getLoc();
2754     Parser.Lex();
2755     const AsmToken &Tok = Parser.getTok();
2756     if (Tok.is(AsmToken::Integer)) {
2757       SMLoc IntS = getLoc();
2758       int64_t Val = Tok.getIntVal();
2759       if (Val == 1) {
2760         Parser.Lex();
2761         if (getLexer().getKind() == AsmToken::RBrac) {
2762           SMLoc RBracS = getLoc();
2763           Parser.Lex();
2764           Operands.push_back(
2765               ARM64Operand::CreateToken("[", false, LBracS, getContext()));
2766           Operands.push_back(
2767               ARM64Operand::CreateToken("1", false, IntS, getContext()));
2768           Operands.push_back(
2769               ARM64Operand::CreateToken("]", false, RBracS, getContext()));
2770           return false;
2771         }
2772       }
2773     }
2774   }
2775
2776   return false;
2777 }
2778
2779 /// tryParseNoIndexMemory - Custom parser method for memory operands that
2780 ///                         do not allow base regisrer writeback modes,
2781 ///                         or those that handle writeback separately from
2782 ///                         the memory operand (like the AdvSIMD ldX/stX
2783 ///                         instructions.
2784 ARM64AsmParser::OperandMatchResultTy
2785 ARM64AsmParser::tryParseNoIndexMemory(OperandVector &Operands) {
2786   if (Parser.getTok().isNot(AsmToken::LBrac))
2787     return MatchOperand_NoMatch;
2788   SMLoc S = getLoc();
2789   Parser.Lex(); // Eat left bracket token.
2790
2791   const AsmToken &BaseRegTok = Parser.getTok();
2792   if (BaseRegTok.isNot(AsmToken::Identifier)) {
2793     Error(BaseRegTok.getLoc(), "register expected");
2794     return MatchOperand_ParseFail;
2795   }
2796
2797   int64_t Reg = tryParseRegister();
2798   if (Reg == -1) {
2799     Error(BaseRegTok.getLoc(), "register expected");
2800     return MatchOperand_ParseFail;
2801   }
2802
2803   SMLoc E = getLoc();
2804   if (Parser.getTok().isNot(AsmToken::RBrac)) {
2805     Error(E, "']' expected");
2806     return MatchOperand_ParseFail;
2807   }
2808
2809   Parser.Lex(); // Eat right bracket token.
2810
2811   Operands.push_back(ARM64Operand::CreateMem(Reg, 0, S, E, E, getContext()));
2812   return MatchOperand_Success;
2813 }
2814
2815 /// parseMemory - Parse a memory operand for a basic load/store instruction.
2816 bool ARM64AsmParser::parseMemory(OperandVector &Operands) {
2817   assert(Parser.getTok().is(AsmToken::LBrac) && "Token is not a Left Bracket");
2818   SMLoc S = getLoc();
2819   Parser.Lex(); // Eat left bracket token.
2820
2821   const AsmToken &BaseRegTok = Parser.getTok();
2822   if (BaseRegTok.isNot(AsmToken::Identifier))
2823     return Error(BaseRegTok.getLoc(), "register expected");
2824
2825   int64_t Reg = tryParseRegister();
2826   if (Reg == -1)
2827     return Error(BaseRegTok.getLoc(), "register expected");
2828
2829   // If there is an offset expression, parse it.
2830   const MCExpr *OffsetExpr = 0;
2831   SMLoc OffsetLoc;
2832   if (Parser.getTok().is(AsmToken::Comma)) {
2833     Parser.Lex(); // Eat the comma.
2834     OffsetLoc = getLoc();
2835
2836     // Register offset
2837     const AsmToken &OffsetRegTok = Parser.getTok();
2838     int Reg2 = OffsetRegTok.is(AsmToken::Identifier) ? tryParseRegister() : -1;
2839     if (Reg2 != -1) {
2840       // Default shift is LSL, with an omitted shift.  We use the third bit of
2841       // the extend value to indicate presence/omission of the immediate offset.
2842       ARM64_AM::ExtendType ExtOp = ARM64_AM::UXTX;
2843       int64_t ShiftVal = 0;
2844       bool ExplicitShift = false;
2845
2846       if (Parser.getTok().is(AsmToken::Comma)) {
2847         // Embedded extend operand.
2848         Parser.Lex(); // Eat the comma
2849
2850         SMLoc ExtLoc = getLoc();
2851         const AsmToken &Tok = Parser.getTok();
2852         ExtOp = StringSwitch<ARM64_AM::ExtendType>(Tok.getString())
2853                     .Case("uxtw", ARM64_AM::UXTW)
2854                     .Case("lsl", ARM64_AM::UXTX) // Alias for UXTX
2855                     .Case("sxtw", ARM64_AM::SXTW)
2856                     .Case("sxtx", ARM64_AM::SXTX)
2857                     .Case("UXTW", ARM64_AM::UXTW)
2858                     .Case("LSL", ARM64_AM::UXTX) // Alias for UXTX
2859                     .Case("SXTW", ARM64_AM::SXTW)
2860                     .Case("SXTX", ARM64_AM::SXTX)
2861                     .Default(ARM64_AM::InvalidExtend);
2862         if (ExtOp == ARM64_AM::InvalidExtend)
2863           return Error(ExtLoc, "expected valid extend operation");
2864
2865         Parser.Lex(); // Eat the extend op.
2866
2867         if (getLexer().is(AsmToken::RBrac)) {
2868           // No immediate operand.
2869           if (ExtOp == ARM64_AM::UXTX)
2870             return Error(ExtLoc, "LSL extend requires immediate operand");
2871         } else if (getLexer().is(AsmToken::Hash)) {
2872           // Immediate operand.
2873           Parser.Lex(); // Eat the '#'
2874           const MCExpr *ImmVal;
2875           SMLoc ExprLoc = getLoc();
2876           if (getParser().parseExpression(ImmVal))
2877             return true;
2878           const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(ImmVal);
2879           if (!MCE)
2880             return TokError("immediate value expected for extend operand");
2881
2882           ExplicitShift = true;
2883           ShiftVal = MCE->getValue();
2884           if (ShiftVal < 0 || ShiftVal > 4)
2885             return Error(ExprLoc, "immediate operand out of range");
2886         } else
2887           return Error(getLoc(), "expected immediate operand");
2888       }
2889
2890       if (Parser.getTok().isNot(AsmToken::RBrac))
2891         return Error(getLoc(), "']' expected");
2892
2893       Parser.Lex(); // Eat right bracket token.
2894
2895       SMLoc E = getLoc();
2896       Operands.push_back(ARM64Operand::CreateRegOffsetMem(
2897           Reg, Reg2, ExtOp, ShiftVal, ExplicitShift, S, E, getContext()));
2898       return false;
2899
2900       // Immediate expressions.
2901     } else if (Parser.getTok().is(AsmToken::Hash)) {
2902       Parser.Lex(); // Eat hash token.
2903
2904       if (parseSymbolicImmVal(OffsetExpr))
2905         return true;
2906     } else {
2907       // FIXME: We really should make sure that we're dealing with a LDR/STR
2908       // instruction that can legally have a symbolic expression here.
2909       // Symbol reference.
2910       if (Parser.getTok().isNot(AsmToken::Identifier) &&
2911           Parser.getTok().isNot(AsmToken::String))
2912         return Error(getLoc(), "identifier or immediate expression expected");
2913       if (getParser().parseExpression(OffsetExpr))
2914         return true;
2915       // If this is a plain ref, Make sure a legal variant kind was specified.
2916       // Otherwise, it's a more complicated expression and we have to just
2917       // assume it's OK and let the relocation stuff puke if it's not.
2918       ARM64MCExpr::VariantKind ELFRefKind;
2919       MCSymbolRefExpr::VariantKind DarwinRefKind;
2920       const MCConstantExpr *Addend;
2921       if (classifySymbolRef(OffsetExpr, ELFRefKind, DarwinRefKind, Addend) &&
2922           Addend == 0) {
2923         assert(ELFRefKind == ARM64MCExpr::VK_INVALID &&
2924                "ELF symbol modifiers not supported here yet");
2925
2926         switch (DarwinRefKind) {
2927         default:
2928           return Error(getLoc(), "expected @pageoff or @gotpageoff modifier");
2929         case MCSymbolRefExpr::VK_GOTPAGEOFF:
2930         case MCSymbolRefExpr::VK_PAGEOFF:
2931         case MCSymbolRefExpr::VK_TLVPPAGEOFF:
2932           // These are what we're expecting.
2933           break;
2934         }
2935       }
2936     }
2937   }
2938
2939   SMLoc E = getLoc();
2940   if (Parser.getTok().isNot(AsmToken::RBrac))
2941     return Error(E, "']' expected");
2942
2943   Parser.Lex(); // Eat right bracket token.
2944
2945   // Create the memory operand.
2946   Operands.push_back(
2947       ARM64Operand::CreateMem(Reg, OffsetExpr, S, E, OffsetLoc, getContext()));
2948
2949   // Check for a '!', indicating pre-indexed addressing with writeback.
2950   if (Parser.getTok().is(AsmToken::Exclaim)) {
2951     // There needs to have been an immediate or wback doesn't make sense.
2952     if (!OffsetExpr)
2953       return Error(E, "missing offset for pre-indexed addressing");
2954     // Pre-indexed with writeback must have a constant expression for the
2955     // offset. FIXME: Theoretically, we'd like to allow fixups so long
2956     // as they don't require a relocation.
2957     if (!isa<MCConstantExpr>(OffsetExpr))
2958       return Error(OffsetLoc, "constant immediate expression expected");
2959
2960     // Create the Token operand for the '!'.
2961     Operands.push_back(ARM64Operand::CreateToken(
2962         "!", false, Parser.getTok().getLoc(), getContext()));
2963     Parser.Lex(); // Eat the '!' token.
2964   }
2965
2966   return false;
2967 }
2968
2969 bool ARM64AsmParser::parseSymbolicImmVal(const MCExpr *&ImmVal) {
2970   bool HasELFModifier = false;
2971   ARM64MCExpr::VariantKind RefKind;
2972
2973   if (Parser.getTok().is(AsmToken::Colon)) {
2974     Parser.Lex(); // Eat ':"
2975     HasELFModifier = true;
2976
2977     if (Parser.getTok().isNot(AsmToken::Identifier)) {
2978       Error(Parser.getTok().getLoc(),
2979             "expect relocation specifier in operand after ':'");
2980       return true;
2981     }
2982
2983     std::string LowerCase = Parser.getTok().getIdentifier().lower();
2984     RefKind = StringSwitch<ARM64MCExpr::VariantKind>(LowerCase)
2985                   .Case("lo12", ARM64MCExpr::VK_LO12)
2986                   .Case("abs_g3", ARM64MCExpr::VK_ABS_G3)
2987                   .Case("abs_g2", ARM64MCExpr::VK_ABS_G2)
2988                   .Case("abs_g2_nc", ARM64MCExpr::VK_ABS_G2_NC)
2989                   .Case("abs_g1", ARM64MCExpr::VK_ABS_G1)
2990                   .Case("abs_g1_nc", ARM64MCExpr::VK_ABS_G1_NC)
2991                   .Case("abs_g0", ARM64MCExpr::VK_ABS_G0)
2992                   .Case("abs_g0_nc", ARM64MCExpr::VK_ABS_G0_NC)
2993                   .Case("dtprel_g2", ARM64MCExpr::VK_DTPREL_G2)
2994                   .Case("dtprel_g1", ARM64MCExpr::VK_DTPREL_G1)
2995                   .Case("dtprel_g1_nc", ARM64MCExpr::VK_DTPREL_G1_NC)
2996                   .Case("dtprel_g0", ARM64MCExpr::VK_DTPREL_G0)
2997                   .Case("dtprel_g0_nc", ARM64MCExpr::VK_DTPREL_G0_NC)
2998                   .Case("dtprel_lo12", ARM64MCExpr::VK_DTPREL_LO12)
2999                   .Case("dtprel_lo12_nc", ARM64MCExpr::VK_DTPREL_LO12_NC)
3000                   .Case("tprel_g2", ARM64MCExpr::VK_TPREL_G2)
3001                   .Case("tprel_g1", ARM64MCExpr::VK_TPREL_G1)
3002                   .Case("tprel_g1_nc", ARM64MCExpr::VK_TPREL_G1_NC)
3003                   .Case("tprel_g0", ARM64MCExpr::VK_TPREL_G0)
3004                   .Case("tprel_g0_nc", ARM64MCExpr::VK_TPREL_G0_NC)
3005                   .Case("tprel_lo12", ARM64MCExpr::VK_TPREL_LO12)
3006                   .Case("tprel_lo12_nc", ARM64MCExpr::VK_TPREL_LO12_NC)
3007                   .Case("tlsdesc_lo12", ARM64MCExpr::VK_TLSDESC_LO12)
3008                   .Case("got", ARM64MCExpr::VK_GOT_PAGE)
3009                   .Case("got_lo12", ARM64MCExpr::VK_GOT_LO12)
3010                   .Case("gottprel", ARM64MCExpr::VK_GOTTPREL_PAGE)
3011                   .Case("gottprel_lo12", ARM64MCExpr::VK_GOTTPREL_LO12_NC)
3012                   .Case("gottprel_g1", ARM64MCExpr::VK_GOTTPREL_G1)
3013                   .Case("gottprel_g0_nc", ARM64MCExpr::VK_GOTTPREL_G0_NC)
3014                   .Case("tlsdesc", ARM64MCExpr::VK_TLSDESC_PAGE)
3015                   .Default(ARM64MCExpr::VK_INVALID);
3016
3017     if (RefKind == ARM64MCExpr::VK_INVALID) {
3018       Error(Parser.getTok().getLoc(),
3019             "expect relocation specifier in operand after ':'");
3020       return true;
3021     }
3022
3023     Parser.Lex(); // Eat identifier
3024
3025     if (Parser.getTok().isNot(AsmToken::Colon)) {
3026       Error(Parser.getTok().getLoc(), "expect ':' after relocation specifier");
3027       return true;
3028     }
3029     Parser.Lex(); // Eat ':'
3030   }
3031
3032   if (getParser().parseExpression(ImmVal))
3033     return true;
3034
3035   if (HasELFModifier)
3036     ImmVal = ARM64MCExpr::Create(ImmVal, RefKind, getContext());
3037
3038   return false;
3039 }
3040
3041 /// parseVectorList - Parse a vector list operand for AdvSIMD instructions.
3042 bool ARM64AsmParser::parseVectorList(OperandVector &Operands) {
3043   assert(Parser.getTok().is(AsmToken::LCurly) && "Token is not a Left Bracket");
3044   SMLoc S = getLoc();
3045   Parser.Lex(); // Eat left bracket token.
3046   StringRef Kind;
3047   int64_t FirstReg = tryMatchVectorRegister(Kind, true);
3048   if (FirstReg == -1)
3049     return true;
3050   int64_t PrevReg = FirstReg;
3051   unsigned Count = 1;
3052
3053   if (Parser.getTok().is(AsmToken::Minus)) {
3054     Parser.Lex(); // Eat the minus.
3055
3056     SMLoc Loc = getLoc();
3057     StringRef NextKind;
3058     int64_t Reg = tryMatchVectorRegister(NextKind, true);
3059     if (Reg == -1)
3060       return true;
3061     // Any Kind suffices must match on all regs in the list.
3062     if (Kind != NextKind)
3063       return Error(Loc, "mismatched register size suffix");
3064
3065     unsigned Space = (PrevReg < Reg) ? (Reg - PrevReg) : (Reg + 32 - PrevReg);
3066
3067     if (Space == 0 || Space > 3) {
3068       return Error(Loc, "invalid number of vectors");
3069     }
3070
3071     Count += Space;
3072   }
3073   else {
3074     while (Parser.getTok().is(AsmToken::Comma)) {
3075       Parser.Lex(); // Eat the comma token.
3076
3077       SMLoc Loc = getLoc();
3078       StringRef NextKind;
3079       int64_t Reg = tryMatchVectorRegister(NextKind, true);
3080       if (Reg == -1)
3081         return true;
3082       // Any Kind suffices must match on all regs in the list.
3083       if (Kind != NextKind)
3084         return Error(Loc, "mismatched register size suffix");
3085
3086       // Registers must be incremental (with wraparound at 31)
3087       if (getContext().getRegisterInfo()->getEncodingValue(Reg) !=
3088           (getContext().getRegisterInfo()->getEncodingValue(PrevReg) + 1) % 32)
3089        return Error(Loc, "registers must be sequential");
3090
3091       PrevReg = Reg;
3092       ++Count;
3093     }
3094   }
3095
3096   if (Parser.getTok().is(AsmToken::EndOfStatement))
3097     Error(getLoc(), "'}' expected");
3098   Parser.Lex(); // Eat the '}' token.
3099
3100   unsigned NumElements = 0;
3101   char ElementKind = 0;
3102   if (!Kind.empty())
3103     parseValidVectorKind(Kind, NumElements, ElementKind);
3104
3105   Operands.push_back(ARM64Operand::CreateVectorList(
3106       FirstReg, Count, NumElements, ElementKind, S, getLoc(), getContext()));
3107
3108   // If there is an index specifier following the list, parse that too.
3109   if (Parser.getTok().is(AsmToken::LBrac)) {
3110     SMLoc SIdx = getLoc();
3111     Parser.Lex(); // Eat left bracket token.
3112
3113     const MCExpr *ImmVal;
3114     if (getParser().parseExpression(ImmVal))
3115       return false;
3116     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(ImmVal);
3117     if (!MCE) {
3118       TokError("immediate value expected for vector index");
3119       return false;
3120     }
3121
3122     SMLoc E = getLoc();
3123     if (Parser.getTok().isNot(AsmToken::RBrac)) {
3124       Error(E, "']' expected");
3125       return false;
3126     }
3127
3128     Parser.Lex(); // Eat right bracket token.
3129
3130     Operands.push_back(ARM64Operand::CreateVectorIndex(MCE->getValue(), SIdx, E,
3131                                                        getContext()));
3132   }
3133   return false;
3134 }
3135
3136 /// parseOperand - Parse a arm instruction operand.  For now this parses the
3137 /// operand regardless of the mnemonic.
3138 bool ARM64AsmParser::parseOperand(OperandVector &Operands, bool isCondCode,
3139                                   bool invertCondCode) {
3140   // Check if the current operand has a custom associated parser, if so, try to
3141   // custom parse the operand, or fallback to the general approach.
3142   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
3143   if (ResTy == MatchOperand_Success)
3144     return false;
3145   // If there wasn't a custom match, try the generic matcher below. Otherwise,
3146   // there was a match, but an error occurred, in which case, just return that
3147   // the operand parsing failed.
3148   if (ResTy == MatchOperand_ParseFail)
3149     return true;
3150
3151   // Nothing custom, so do general case parsing.
3152   SMLoc S, E;
3153   switch (getLexer().getKind()) {
3154   default: {
3155     SMLoc S = getLoc();
3156     const MCExpr *Expr;
3157     if (parseSymbolicImmVal(Expr))
3158       return Error(S, "invalid operand");
3159
3160     SMLoc E = SMLoc::getFromPointer(getLoc().getPointer() - 1);
3161     Operands.push_back(ARM64Operand::CreateImm(Expr, S, E, getContext()));
3162     return false;
3163   }
3164   case AsmToken::LBrac:
3165     return parseMemory(Operands);
3166   case AsmToken::LCurly:
3167     return parseVectorList(Operands);
3168   case AsmToken::Identifier: {
3169     // If we're expecting a Condition Code operand, then just parse that.
3170     if (isCondCode)
3171       return parseCondCode(Operands, invertCondCode);
3172
3173     // If it's a register name, parse it.
3174     if (!parseRegister(Operands))
3175       return false;
3176
3177     // This could be an optional "shift" operand.
3178     if (!parseOptionalShift(Operands))
3179       return false;
3180
3181     // Or maybe it could be an optional "extend" operand.
3182     if (!parseOptionalExtend(Operands))
3183       return false;
3184
3185     // This was not a register so parse other operands that start with an
3186     // identifier (like labels) as expressions and create them as immediates.
3187     const MCExpr *IdVal;
3188     S = getLoc();
3189     if (getParser().parseExpression(IdVal))
3190       return true;
3191
3192     E = SMLoc::getFromPointer(getLoc().getPointer() - 1);
3193     Operands.push_back(ARM64Operand::CreateImm(IdVal, S, E, getContext()));
3194     return false;
3195   }
3196   case AsmToken::Hash: {
3197     // #42 -> immediate.
3198     S = getLoc();
3199     Parser.Lex();
3200
3201     // The only Real that should come through here is a literal #0.0 for
3202     // the fcmp[e] r, #0.0 instructions. They expect raw token operands,
3203     // so convert the value.
3204     const AsmToken &Tok = Parser.getTok();
3205     if (Tok.is(AsmToken::Real)) {
3206       APFloat RealVal(APFloat::IEEEdouble, Tok.getString());
3207       uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
3208       if (IntVal != 0 || (Mnemonic != "fcmp" && Mnemonic != "fcmpe"))
3209         return TokError("unexpected floating point literal");
3210       Parser.Lex(); // Eat the token.
3211
3212       Operands.push_back(
3213           ARM64Operand::CreateToken("#0", false, S, getContext()));
3214       Operands.push_back(
3215           ARM64Operand::CreateToken(".0", false, S, getContext()));
3216       return false;
3217     }
3218
3219     const MCExpr *ImmVal;
3220     if (parseSymbolicImmVal(ImmVal))
3221       return true;
3222
3223     E = SMLoc::getFromPointer(getLoc().getPointer() - 1);
3224     Operands.push_back(ARM64Operand::CreateImm(ImmVal, S, E, getContext()));
3225     return false;
3226   }
3227   }
3228 }
3229
3230 /// ParseInstruction - Parse an ARM64 instruction mnemonic followed by its
3231 /// operands.
3232 bool ARM64AsmParser::ParseInstruction(ParseInstructionInfo &Info,
3233                                       StringRef Name, SMLoc NameLoc,
3234                                       OperandVector &Operands) {
3235   // Create the leading tokens for the mnemonic, split by '.' characters.
3236   size_t Start = 0, Next = Name.find('.');
3237   StringRef Head = Name.slice(Start, Next);
3238
3239   // IC, DC, AT, and TLBI instructions are aliases for the SYS instruction.
3240   if (Head == "ic" || Head == "dc" || Head == "at" || Head == "tlbi")
3241     return parseSysAlias(Head, NameLoc, Operands);
3242
3243   Operands.push_back(
3244       ARM64Operand::CreateToken(Head, false, NameLoc, getContext()));
3245   Mnemonic = Head;
3246
3247   // Handle condition codes for a branch mnemonic
3248   if (Head == "b" && Next != StringRef::npos) {
3249     Start = Next;
3250     Next = Name.find('.', Start + 1);
3251     Head = Name.slice(Start + 1, Next);
3252
3253     SMLoc SuffixLoc = SMLoc::getFromPointer(NameLoc.getPointer() +
3254                                             (Head.data() - Name.data()));
3255     unsigned CC = parseCondCodeString(Head);
3256     if (CC == ARM64CC::Invalid)
3257       return Error(SuffixLoc, "invalid condition code");
3258     const MCExpr *CCExpr = MCConstantExpr::Create(CC, getContext());
3259     Operands.push_back(
3260         ARM64Operand::CreateImm(CCExpr, NameLoc, NameLoc, getContext()));
3261   }
3262
3263   // Add the remaining tokens in the mnemonic.
3264   while (Next != StringRef::npos) {
3265     Start = Next;
3266     Next = Name.find('.', Start + 1);
3267     Head = Name.slice(Start, Next);
3268     SMLoc SuffixLoc = SMLoc::getFromPointer(NameLoc.getPointer() +
3269                                             (Head.data() - Name.data()) + 1);
3270     Operands.push_back(
3271         ARM64Operand::CreateToken(Head, true, SuffixLoc, getContext()));
3272   }
3273
3274   // Conditional compare instructions have a Condition Code operand, which needs
3275   // to be parsed and an immediate operand created.
3276   bool condCodeFourthOperand =
3277       (Head == "ccmp" || Head == "ccmn" || Head == "fccmp" ||
3278        Head == "fccmpe" || Head == "fcsel" || Head == "csel" ||
3279        Head == "csinc" || Head == "csinv" || Head == "csneg");
3280
3281   // These instructions are aliases to some of the conditional select
3282   // instructions. However, the condition code is inverted in the aliased
3283   // instruction.
3284   //
3285   // FIXME: Is this the correct way to handle these? Or should the parser
3286   //        generate the aliased instructions directly?
3287   bool condCodeSecondOperand = (Head == "cset" || Head == "csetm");
3288   bool condCodeThirdOperand =
3289       (Head == "cinc" || Head == "cinv" || Head == "cneg");
3290
3291   // Read the remaining operands.
3292   if (getLexer().isNot(AsmToken::EndOfStatement)) {
3293     // Read the first operand.
3294     if (parseOperand(Operands, false, false)) {
3295       Parser.eatToEndOfStatement();
3296       return true;
3297     }
3298
3299     unsigned N = 2;
3300     while (getLexer().is(AsmToken::Comma)) {
3301       Parser.Lex(); // Eat the comma.
3302
3303       // Parse and remember the operand.
3304       if (parseOperand(Operands, (N == 4 && condCodeFourthOperand) ||
3305                                      (N == 3 && condCodeThirdOperand) ||
3306                                      (N == 2 && condCodeSecondOperand),
3307                        condCodeSecondOperand || condCodeThirdOperand)) {
3308         Parser.eatToEndOfStatement();
3309         return true;
3310       }
3311
3312       ++N;
3313     }
3314   }
3315
3316   if (getLexer().isNot(AsmToken::EndOfStatement)) {
3317     SMLoc Loc = Parser.getTok().getLoc();
3318     Parser.eatToEndOfStatement();
3319     return Error(Loc, "unexpected token in argument list");
3320   }
3321
3322   Parser.Lex(); // Consume the EndOfStatement
3323   return false;
3324 }
3325
3326 /// isFPR32Register - Check if a register is in the FPR32 register class.
3327 /// (The parser does not have the target register info to check the register
3328 /// class directly.)
3329 static bool isFPR32Register(unsigned Reg) {
3330   using namespace ARM64;
3331   switch (Reg) {
3332   default:
3333     break;
3334   case S0:  case S1:  case S2:  case S3:  case S4:  case S5:  case S6:
3335   case S7:  case S8:  case S9:  case S10:  case S11:  case S12:  case S13:
3336   case S14:  case S15:  case S16:  case S17:  case S18:  case S19:  case S20:
3337   case S21:  case S22:  case S23:  case S24:  case S25:  case S26:  case S27:
3338   case S28:  case S29:  case S30:  case S31:
3339     return true;
3340   }
3341   return false;
3342 }
3343
3344 /// isGPR32Register - Check if a register is in the GPR32sp register class.
3345 /// (The parser does not have the target register info to check the register
3346 /// class directly.)
3347 static bool isGPR32Register(unsigned Reg) {
3348   using namespace ARM64;
3349   switch (Reg) {
3350   default:
3351     break;
3352   case W0:  case W1:  case W2:  case W3:  case W4:  case W5:  case W6:
3353   case W7:  case W8:  case W9:  case W10:  case W11:  case W12:  case W13:
3354   case W14:  case W15:  case W16:  case W17:  case W18:  case W19:  case W20:
3355   case W21:  case W22:  case W23:  case W24:  case W25:  case W26:  case W27:
3356   case W28:  case W29:  case W30:  case WSP:  case WZR:
3357     return true;
3358   }
3359   return false;
3360 }
3361
3362 static bool isGPR64Reg(unsigned Reg) {
3363   using namespace ARM64;
3364   switch (Reg) {
3365   case X0:  case X1:  case X2:  case X3:  case X4:  case X5:  case X6:
3366   case X7:  case X8:  case X9:  case X10:  case X11:  case X12:  case X13:
3367   case X14:  case X15:  case X16:  case X17:  case X18:  case X19:  case X20:
3368   case X21:  case X22:  case X23:  case X24:  case X25:  case X26:  case X27:
3369   case X28:  case FP:  case LR:  case SP:  case XZR:
3370     return true;
3371   default:
3372     return false;
3373   }
3374 }
3375
3376
3377 // FIXME: This entire function is a giant hack to provide us with decent
3378 // operand range validation/diagnostics until TableGen/MC can be extended
3379 // to support autogeneration of this kind of validation.
3380 bool ARM64AsmParser::validateInstruction(MCInst &Inst,
3381                                          SmallVectorImpl<SMLoc> &Loc) {
3382   const MCRegisterInfo *RI = getContext().getRegisterInfo();
3383   // Check for indexed addressing modes w/ the base register being the
3384   // same as a destination/source register or pair load where
3385   // the Rt == Rt2. All of those are undefined behaviour.
3386   switch (Inst.getOpcode()) {
3387   case ARM64::LDPSWpre:
3388   case ARM64::LDPWpost:
3389   case ARM64::LDPWpre:
3390   case ARM64::LDPXpost:
3391   case ARM64::LDPXpre: {
3392     unsigned Rt = Inst.getOperand(0).getReg();
3393     unsigned Rt2 = Inst.getOperand(1).getReg();
3394     unsigned Rn = Inst.getOperand(2).getReg();
3395     if (RI->isSubRegisterEq(Rn, Rt))
3396       return Error(Loc[0], "unpredictable LDP instruction, writeback base "
3397                            "is also a destination");
3398     if (RI->isSubRegisterEq(Rn, Rt2))
3399       return Error(Loc[1], "unpredictable LDP instruction, writeback base "
3400                            "is also a destination");
3401     // FALLTHROUGH
3402   }
3403   case ARM64::LDPDpost:
3404   case ARM64::LDPDpre:
3405   case ARM64::LDPQpost:
3406   case ARM64::LDPQpre:
3407   case ARM64::LDPSpost:
3408   case ARM64::LDPSpre:
3409   case ARM64::LDPSWpost:
3410   case ARM64::LDPDi:
3411   case ARM64::LDPQi:
3412   case ARM64::LDPSi:
3413   case ARM64::LDPSWi:
3414   case ARM64::LDPWi:
3415   case ARM64::LDPXi: {
3416     unsigned Rt = Inst.getOperand(0).getReg();
3417     unsigned Rt2 = Inst.getOperand(1).getReg();
3418     if (Rt == Rt2)
3419       return Error(Loc[1], "unpredictable LDP instruction, Rt2==Rt");
3420     break;
3421   }
3422   case ARM64::STPDpost:
3423   case ARM64::STPDpre:
3424   case ARM64::STPQpost:
3425   case ARM64::STPQpre:
3426   case ARM64::STPSpost:
3427   case ARM64::STPSpre:
3428   case ARM64::STPWpost:
3429   case ARM64::STPWpre:
3430   case ARM64::STPXpost:
3431   case ARM64::STPXpre: {
3432     unsigned Rt = Inst.getOperand(0).getReg();
3433     unsigned Rt2 = Inst.getOperand(1).getReg();
3434     unsigned Rn = Inst.getOperand(2).getReg();
3435     if (RI->isSubRegisterEq(Rn, Rt))
3436       return Error(Loc[0], "unpredictable STP instruction, writeback base "
3437                            "is also a source");
3438     if (RI->isSubRegisterEq(Rn, Rt2))
3439       return Error(Loc[1], "unpredictable STP instruction, writeback base "
3440                            "is also a source");
3441     break;
3442   }
3443   case ARM64::LDRBBpre:
3444   case ARM64::LDRBpre:
3445   case ARM64::LDRHHpre:
3446   case ARM64::LDRHpre:
3447   case ARM64::LDRSBWpre:
3448   case ARM64::LDRSBXpre:
3449   case ARM64::LDRSHWpre:
3450   case ARM64::LDRSHXpre:
3451   case ARM64::LDRSWpre:
3452   case ARM64::LDRWpre:
3453   case ARM64::LDRXpre:
3454   case ARM64::LDRBBpost:
3455   case ARM64::LDRBpost:
3456   case ARM64::LDRHHpost:
3457   case ARM64::LDRHpost:
3458   case ARM64::LDRSBWpost:
3459   case ARM64::LDRSBXpost:
3460   case ARM64::LDRSHWpost:
3461   case ARM64::LDRSHXpost:
3462   case ARM64::LDRSWpost:
3463   case ARM64::LDRWpost:
3464   case ARM64::LDRXpost: {
3465     unsigned Rt = Inst.getOperand(0).getReg();
3466     unsigned Rn = Inst.getOperand(1).getReg();
3467     if (RI->isSubRegisterEq(Rn, Rt))
3468       return Error(Loc[0], "unpredictable LDR instruction, writeback base "
3469                            "is also a source");
3470     break;
3471   }
3472   case ARM64::STRBBpost:
3473   case ARM64::STRBpost:
3474   case ARM64::STRHHpost:
3475   case ARM64::STRHpost:
3476   case ARM64::STRWpost:
3477   case ARM64::STRXpost:
3478   case ARM64::STRBBpre:
3479   case ARM64::STRBpre:
3480   case ARM64::STRHHpre:
3481   case ARM64::STRHpre:
3482   case ARM64::STRWpre:
3483   case ARM64::STRXpre: {
3484     unsigned Rt = Inst.getOperand(0).getReg();
3485     unsigned Rn = Inst.getOperand(1).getReg();
3486     if (RI->isSubRegisterEq(Rn, Rt))
3487       return Error(Loc[0], "unpredictable STR instruction, writeback base "
3488                            "is also a source");
3489     break;
3490   }
3491   }
3492
3493   // Now check immediate ranges. Separate from the above as there is overlap
3494   // in the instructions being checked and this keeps the nested conditionals
3495   // to a minimum.
3496   switch (Inst.getOpcode()) {
3497   case ARM64::ANDWrs:
3498   case ARM64::ANDSWrs:
3499   case ARM64::EORWrs:
3500   case ARM64::ORRWrs: {
3501     if (!Inst.getOperand(3).isImm())
3502       return Error(Loc[3], "immediate value expected");
3503     int64_t shifter = Inst.getOperand(3).getImm();
3504     ARM64_AM::ShiftType ST = ARM64_AM::getShiftType(shifter);
3505     if (ST == ARM64_AM::LSL && shifter > 31)
3506       return Error(Loc[3], "shift value out of range");
3507     return false;
3508   }
3509   case ARM64::ADDSWri:
3510   case ARM64::ADDSXri:
3511   case ARM64::ADDWri:
3512   case ARM64::ADDXri:
3513   case ARM64::SUBSWri:
3514   case ARM64::SUBSXri:
3515   case ARM64::SUBWri:
3516   case ARM64::SUBXri: {
3517     if (!Inst.getOperand(3).isImm())
3518       return Error(Loc[3], "immediate value expected");
3519     int64_t shifter = Inst.getOperand(3).getImm();
3520     if (shifter != 0 && shifter != 12)
3521       return Error(Loc[3], "shift value out of range");
3522     // The imm12 operand can be an expression. Validate that it's legit.
3523     // FIXME: We really, really want to allow arbitrary expressions here
3524     // and resolve the value and validate the result at fixup time, but
3525     // that's hard as we have long since lost any source information we
3526     // need to generate good diagnostics by that point.
3527     if (Inst.getOpcode() == ARM64::ADDXri && Inst.getOperand(2).isExpr()) {
3528       const MCExpr *Expr = Inst.getOperand(2).getExpr();
3529       ARM64MCExpr::VariantKind ELFRefKind;
3530       MCSymbolRefExpr::VariantKind DarwinRefKind;
3531       const MCConstantExpr *Addend;
3532       if (!classifySymbolRef(Expr, ELFRefKind, DarwinRefKind, Addend)) {
3533         return Error(Loc[2], "invalid immediate expression");
3534       }
3535
3536       if (DarwinRefKind == MCSymbolRefExpr::VK_PAGEOFF ||
3537           DarwinRefKind == MCSymbolRefExpr::VK_TLVPPAGEOFF ||
3538           ELFRefKind == ARM64MCExpr::VK_LO12 ||
3539           ELFRefKind == ARM64MCExpr::VK_DTPREL_LO12 ||
3540           ELFRefKind == ARM64MCExpr::VK_DTPREL_LO12_NC ||
3541           ELFRefKind == ARM64MCExpr::VK_TPREL_LO12 ||
3542           ELFRefKind == ARM64MCExpr::VK_TPREL_LO12_NC ||
3543           ELFRefKind == ARM64MCExpr::VK_TLSDESC_LO12) {
3544         // Note that we don't range-check the addend. It's adjusted
3545         // modulo page size when converted, so there is no "out of range"
3546         // condition when using @pageoff. Any validity checking for the value
3547         // was done in the is*() predicate function.
3548         return false;
3549       } else if (DarwinRefKind == MCSymbolRefExpr::VK_GOTPAGEOFF) {
3550         // @gotpageoff can only be used directly, not with an addend.
3551         return Addend != 0;
3552       }
3553
3554       // Otherwise, we're not sure, so don't allow it for now.
3555       return Error(Loc[2], "invalid immediate expression");
3556     }
3557
3558     // If it's anything but an immediate, it's not legit.
3559     if (!Inst.getOperand(2).isImm())
3560       return Error(Loc[2], "invalid immediate expression");
3561     int64_t imm = Inst.getOperand(2).getImm();
3562     if (imm > 4095 || imm < 0)
3563       return Error(Loc[2], "immediate value out of range");
3564     return false;
3565   }
3566   case ARM64::LDRBpre:
3567   case ARM64::LDRHpre:
3568   case ARM64::LDRSBWpre:
3569   case ARM64::LDRSBXpre:
3570   case ARM64::LDRSHWpre:
3571   case ARM64::LDRSHXpre:
3572   case ARM64::LDRWpre:
3573   case ARM64::LDRXpre:
3574   case ARM64::LDRSpre:
3575   case ARM64::LDRDpre:
3576   case ARM64::LDRQpre:
3577   case ARM64::STRBpre:
3578   case ARM64::STRHpre:
3579   case ARM64::STRWpre:
3580   case ARM64::STRXpre:
3581   case ARM64::STRSpre:
3582   case ARM64::STRDpre:
3583   case ARM64::STRQpre:
3584   case ARM64::LDRBpost:
3585   case ARM64::LDRHpost:
3586   case ARM64::LDRSBWpost:
3587   case ARM64::LDRSBXpost:
3588   case ARM64::LDRSHWpost:
3589   case ARM64::LDRSHXpost:
3590   case ARM64::LDRWpost:
3591   case ARM64::LDRXpost:
3592   case ARM64::LDRSpost:
3593   case ARM64::LDRDpost:
3594   case ARM64::LDRQpost:
3595   case ARM64::STRBpost:
3596   case ARM64::STRHpost:
3597   case ARM64::STRWpost:
3598   case ARM64::STRXpost:
3599   case ARM64::STRSpost:
3600   case ARM64::STRDpost:
3601   case ARM64::STRQpost:
3602   case ARM64::LDTRXi:
3603   case ARM64::LDTRWi:
3604   case ARM64::LDTRHi:
3605   case ARM64::LDTRBi:
3606   case ARM64::LDTRSHWi:
3607   case ARM64::LDTRSHXi:
3608   case ARM64::LDTRSBWi:
3609   case ARM64::LDTRSBXi:
3610   case ARM64::LDTRSWi:
3611   case ARM64::STTRWi:
3612   case ARM64::STTRXi:
3613   case ARM64::STTRHi:
3614   case ARM64::STTRBi:
3615   case ARM64::LDURWi:
3616   case ARM64::LDURXi:
3617   case ARM64::LDURSi:
3618   case ARM64::LDURDi:
3619   case ARM64::LDURQi:
3620   case ARM64::LDURHi:
3621   case ARM64::LDURBi:
3622   case ARM64::LDURSHWi:
3623   case ARM64::LDURSHXi:
3624   case ARM64::LDURSBWi:
3625   case ARM64::LDURSBXi:
3626   case ARM64::LDURSWi:
3627   case ARM64::PRFUMi:
3628   case ARM64::STURWi:
3629   case ARM64::STURXi:
3630   case ARM64::STURSi:
3631   case ARM64::STURDi:
3632   case ARM64::STURQi:
3633   case ARM64::STURHi:
3634   case ARM64::STURBi: {
3635     // FIXME: Should accept expressions and error in fixup evaluation
3636     // if out of range.
3637     if (!Inst.getOperand(2).isImm())
3638       return Error(Loc[1], "immediate value expected");
3639     int64_t offset = Inst.getOperand(2).getImm();
3640     if (offset > 255 || offset < -256)
3641       return Error(Loc[1], "offset value out of range");
3642     return false;
3643   }
3644   case ARM64::LDRSro:
3645   case ARM64::LDRWro:
3646   case ARM64::LDRSWro:
3647   case ARM64::STRWro:
3648   case ARM64::STRSro: {
3649     // FIXME: Should accept expressions and error in fixup evaluation
3650     // if out of range.
3651     if (!Inst.getOperand(3).isImm())
3652       return Error(Loc[1], "immediate value expected");
3653     int64_t shift = Inst.getOperand(3).getImm();
3654     ARM64_AM::ExtendType type = ARM64_AM::getMemExtendType(shift);
3655     if (type != ARM64_AM::UXTW && type != ARM64_AM::UXTX &&
3656         type != ARM64_AM::SXTW && type != ARM64_AM::SXTX)
3657       return Error(Loc[1], "shift type invalid");
3658     return false;
3659   }
3660   case ARM64::LDRDro:
3661   case ARM64::LDRQro:
3662   case ARM64::LDRXro:
3663   case ARM64::PRFMro:
3664   case ARM64::STRXro:
3665   case ARM64::STRDro:
3666   case ARM64::STRQro: {
3667     // FIXME: Should accept expressions and error in fixup evaluation
3668     // if out of range.
3669     if (!Inst.getOperand(3).isImm())
3670       return Error(Loc[1], "immediate value expected");
3671     int64_t shift = Inst.getOperand(3).getImm();
3672     ARM64_AM::ExtendType type = ARM64_AM::getMemExtendType(shift);
3673     if (type != ARM64_AM::UXTW && type != ARM64_AM::UXTX &&
3674         type != ARM64_AM::SXTW && type != ARM64_AM::SXTX)
3675       return Error(Loc[1], "shift type invalid");
3676     return false;
3677   }
3678   case ARM64::LDRHro:
3679   case ARM64::LDRHHro:
3680   case ARM64::LDRSHWro:
3681   case ARM64::LDRSHXro:
3682   case ARM64::STRHro:
3683   case ARM64::STRHHro: {
3684     // FIXME: Should accept expressions and error in fixup evaluation
3685     // if out of range.
3686     if (!Inst.getOperand(3).isImm())
3687       return Error(Loc[1], "immediate value expected");
3688     int64_t shift = Inst.getOperand(3).getImm();
3689     ARM64_AM::ExtendType type = ARM64_AM::getMemExtendType(shift);
3690     if (type != ARM64_AM::UXTW && type != ARM64_AM::UXTX &&
3691         type != ARM64_AM::SXTW && type != ARM64_AM::SXTX)
3692       return Error(Loc[1], "shift type invalid");
3693     return false;
3694   }
3695   case ARM64::LDRBro:
3696   case ARM64::LDRBBro:
3697   case ARM64::LDRSBWro:
3698   case ARM64::LDRSBXro:
3699   case ARM64::STRBro:
3700   case ARM64::STRBBro: {
3701     // FIXME: Should accept expressions and error in fixup evaluation
3702     // if out of range.
3703     if (!Inst.getOperand(3).isImm())
3704       return Error(Loc[1], "immediate value expected");
3705     int64_t shift = Inst.getOperand(3).getImm();
3706     ARM64_AM::ExtendType type = ARM64_AM::getMemExtendType(shift);
3707     if (type != ARM64_AM::UXTW && type != ARM64_AM::UXTX &&
3708         type != ARM64_AM::SXTW && type != ARM64_AM::SXTX)
3709       return Error(Loc[1], "shift type invalid");
3710     return false;
3711   }
3712   case ARM64::LDPWi:
3713   case ARM64::LDPXi:
3714   case ARM64::LDPSi:
3715   case ARM64::LDPDi:
3716   case ARM64::LDPQi:
3717   case ARM64::LDPSWi:
3718   case ARM64::STPWi:
3719   case ARM64::STPXi:
3720   case ARM64::STPSi:
3721   case ARM64::STPDi:
3722   case ARM64::STPQi:
3723   case ARM64::LDPWpre:
3724   case ARM64::LDPXpre:
3725   case ARM64::LDPSpre:
3726   case ARM64::LDPDpre:
3727   case ARM64::LDPQpre:
3728   case ARM64::LDPSWpre:
3729   case ARM64::STPWpre:
3730   case ARM64::STPXpre:
3731   case ARM64::STPSpre:
3732   case ARM64::STPDpre:
3733   case ARM64::STPQpre:
3734   case ARM64::LDPWpost:
3735   case ARM64::LDPXpost:
3736   case ARM64::LDPSpost:
3737   case ARM64::LDPDpost:
3738   case ARM64::LDPQpost:
3739   case ARM64::LDPSWpost:
3740   case ARM64::STPWpost:
3741   case ARM64::STPXpost:
3742   case ARM64::STPSpost:
3743   case ARM64::STPDpost:
3744   case ARM64::STPQpost:
3745   case ARM64::LDNPWi:
3746   case ARM64::LDNPXi:
3747   case ARM64::LDNPSi:
3748   case ARM64::LDNPDi:
3749   case ARM64::LDNPQi:
3750   case ARM64::STNPWi:
3751   case ARM64::STNPXi:
3752   case ARM64::STNPSi:
3753   case ARM64::STNPDi:
3754   case ARM64::STNPQi: {
3755     // FIXME: Should accept expressions and error in fixup evaluation
3756     // if out of range.
3757     if (!Inst.getOperand(3).isImm())
3758       return Error(Loc[2], "immediate value expected");
3759     int64_t offset = Inst.getOperand(3).getImm();
3760     if (offset > 63 || offset < -64)
3761       return Error(Loc[2], "offset value out of range");
3762     return false;
3763   }
3764   default:
3765     return false;
3766   }
3767 }
3768
3769 static void rewriteMOV(ARM64AsmParser::OperandVector &Operands,
3770                        StringRef mnemonic, uint64_t imm, unsigned shift,
3771                        MCContext &Context) {
3772   ARM64Operand *Op = static_cast<ARM64Operand *>(Operands[0]);
3773   ARM64Operand *Op2 = static_cast<ARM64Operand *>(Operands[2]);
3774   Operands[0] =
3775       ARM64Operand::CreateToken(mnemonic, false, Op->getStartLoc(), Context);
3776
3777   const MCExpr *NewImm = MCConstantExpr::Create(imm >> shift, Context);
3778   Operands[2] = ARM64Operand::CreateImm(NewImm, Op2->getStartLoc(),
3779                                         Op2->getEndLoc(), Context);
3780
3781   Operands.push_back(ARM64Operand::CreateShifter(
3782       ARM64_AM::LSL, shift, Op2->getStartLoc(), Op2->getEndLoc(), Context));
3783   delete Op2;
3784   delete Op;
3785 }
3786
3787 bool ARM64AsmParser::showMatchError(SMLoc Loc, unsigned ErrCode) {
3788   switch (ErrCode) {
3789   case Match_MissingFeature:
3790     return Error(Loc,
3791                  "instruction requires a CPU feature not currently enabled");
3792   case Match_InvalidOperand:
3793     return Error(Loc, "invalid operand for instruction");
3794   case Match_InvalidSuffix:
3795     return Error(Loc, "invalid type suffix for instruction");
3796   case Match_InvalidMemoryIndexedSImm9:
3797     return Error(Loc, "index must be an integer in range [-256,255].");
3798   case Match_InvalidMemoryIndexed32SImm7:
3799     return Error(Loc, "index must be a multiple of 4 in range [-256,252].");
3800   case Match_InvalidMemoryIndexed64SImm7:
3801     return Error(Loc, "index must be a multiple of 8 in range [-512,504].");
3802   case Match_InvalidMemoryIndexed128SImm7:
3803     return Error(Loc, "index must be a multiple of 16 in range [-1024,1008].");
3804   case Match_InvalidMemoryIndexed8:
3805     return Error(Loc, "index must be an integer in range [0,4095].");
3806   case Match_InvalidMemoryIndexed16:
3807     return Error(Loc, "index must be a multiple of 2 in range [0,8190].");
3808   case Match_InvalidMemoryIndexed32:
3809     return Error(Loc, "index must be a multiple of 4 in range [0,16380].");
3810   case Match_InvalidMemoryIndexed64:
3811     return Error(Loc, "index must be a multiple of 8 in range [0,32760].");
3812   case Match_InvalidMemoryIndexed128:
3813     return Error(Loc, "index must be a multiple of 16 in range [0,65520].");
3814   case Match_InvalidImm1_8:
3815     return Error(Loc, "immediate must be an integer in range [1,8].");
3816   case Match_InvalidImm1_16:
3817     return Error(Loc, "immediate must be an integer in range [1,16].");
3818   case Match_InvalidImm1_32:
3819     return Error(Loc, "immediate must be an integer in range [1,32].");
3820   case Match_InvalidImm1_64:
3821     return Error(Loc, "immediate must be an integer in range [1,64].");
3822   case Match_MnemonicFail:
3823     return Error(Loc, "unrecognized instruction mnemonic");
3824   default:
3825     assert(0 && "unexpected error code!");
3826     return Error(Loc, "invalid instruction format");
3827   }
3828 }
3829
3830 bool ARM64AsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
3831                                              OperandVector &Operands,
3832                                              MCStreamer &Out,
3833                                              unsigned &ErrorInfo,
3834                                              bool MatchingInlineAsm) {
3835   assert(!Operands.empty() && "Unexpect empty operand list!");
3836   ARM64Operand *Op = static_cast<ARM64Operand *>(Operands[0]);
3837   assert(Op->isToken() && "Leading operand should always be a mnemonic!");
3838
3839   StringRef Tok = Op->getToken();
3840   // Translate CMN/CMP pseudos to ADDS/SUBS with zero register destination.
3841   // This needs to be done before the special handling of ADD/SUB immediates.
3842   if (Tok == "cmp" || Tok == "cmn") {
3843     // Replace the opcode with either ADDS or SUBS.
3844     const char *Repl = StringSwitch<const char *>(Tok)
3845                            .Case("cmp", "subs")
3846                            .Case("cmn", "adds")
3847                            .Default(0);
3848     assert(Repl && "Unknown compare instruction");
3849     delete Operands[0];
3850     Operands[0] = ARM64Operand::CreateToken(Repl, false, IDLoc, getContext());
3851
3852     // Insert WZR or XZR as destination operand.
3853     ARM64Operand *RegOp = static_cast<ARM64Operand *>(Operands[1]);
3854     unsigned ZeroReg;
3855     if (RegOp->isReg() && isGPR32Register(RegOp->getReg()))
3856       ZeroReg = ARM64::WZR;
3857     else
3858       ZeroReg = ARM64::XZR;
3859     Operands.insert(
3860         Operands.begin() + 1,
3861         ARM64Operand::CreateReg(ZeroReg, false, IDLoc, IDLoc, getContext()));
3862     // Update since we modified it above.
3863     ARM64Operand *Op = static_cast<ARM64Operand *>(Operands[0]);
3864     Tok = Op->getToken();
3865   }
3866
3867   unsigned NumOperands = Operands.size();
3868
3869   if (Tok == "mov" && NumOperands == 3) {
3870     // The MOV mnemomic is aliased to movn/movz, depending on the value of
3871     // the immediate being instantiated.
3872     // FIXME: Catching this here is a total hack, and we should use tblgen
3873     // support to implement this instead as soon as it is available.
3874
3875     ARM64Operand *Op2 = static_cast<ARM64Operand *>(Operands[2]);
3876     if (Op2->isImm()) {
3877       if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op2->getImm())) {
3878         uint64_t Val = CE->getValue();
3879         uint64_t NVal = ~Val;
3880
3881         // If this is a 32-bit register and the value has none of the upper
3882         // set, clear the complemented upper 32-bits so the logic below works
3883         // for 32-bit registers too.
3884         ARM64Operand *Op1 = static_cast<ARM64Operand *>(Operands[1]);
3885         if (Op1->isReg() && isGPR32Register(Op1->getReg()) &&
3886             (Val & 0xFFFFFFFFULL) == Val)
3887           NVal &= 0x00000000FFFFFFFFULL;
3888
3889         // MOVK Rd, imm << 0
3890         if ((Val & 0xFFFF) == Val)
3891           rewriteMOV(Operands, "movz", Val, 0, getContext());
3892
3893         // MOVK Rd, imm << 16
3894         else if ((Val & 0xFFFF0000ULL) == Val)
3895           rewriteMOV(Operands, "movz", Val, 16, getContext());
3896
3897         // MOVK Rd, imm << 32
3898         else if ((Val & 0xFFFF00000000ULL) == Val)
3899           rewriteMOV(Operands, "movz", Val, 32, getContext());
3900
3901         // MOVK Rd, imm << 48
3902         else if ((Val & 0xFFFF000000000000ULL) == Val)
3903           rewriteMOV(Operands, "movz", Val, 48, getContext());
3904
3905         // MOVN Rd, (~imm << 0)
3906         else if ((NVal & 0xFFFFULL) == NVal)
3907           rewriteMOV(Operands, "movn", NVal, 0, getContext());
3908
3909         // MOVN Rd, ~(imm << 16)
3910         else if ((NVal & 0xFFFF0000ULL) == NVal)
3911           rewriteMOV(Operands, "movn", NVal, 16, getContext());
3912
3913         // MOVN Rd, ~(imm << 32)
3914         else if ((NVal & 0xFFFF00000000ULL) == NVal)
3915           rewriteMOV(Operands, "movn", NVal, 32, getContext());
3916
3917         // MOVN Rd, ~(imm << 48)
3918         else if ((NVal & 0xFFFF000000000000ULL) == NVal)
3919           rewriteMOV(Operands, "movn", NVal, 48, getContext());
3920       }
3921     }
3922   } else if (NumOperands == 4) {
3923     if (Tok == "add" || Tok == "adds" || Tok == "sub" || Tok == "subs") {
3924       // Handle the uimm24 immediate form, where the shift is not specified.
3925       ARM64Operand *Op3 = static_cast<ARM64Operand *>(Operands[3]);
3926       if (Op3->isImm()) {
3927         if (const MCConstantExpr *CE =
3928                 dyn_cast<MCConstantExpr>(Op3->getImm())) {
3929           uint64_t Val = CE->getValue();
3930           if (Val >= (1 << 24)) {
3931             Error(IDLoc, "immediate value is too large");
3932             return true;
3933           }
3934           if (Val < (1 << 12)) {
3935             Operands.push_back(ARM64Operand::CreateShifter(
3936                 ARM64_AM::LSL, 0, IDLoc, IDLoc, getContext()));
3937           } else if ((Val & 0xfff) == 0) {
3938             delete Operands[3];
3939             CE = MCConstantExpr::Create(Val >> 12, getContext());
3940             Operands[3] =
3941                 ARM64Operand::CreateImm(CE, IDLoc, IDLoc, getContext());
3942             Operands.push_back(ARM64Operand::CreateShifter(
3943                 ARM64_AM::LSL, 12, IDLoc, IDLoc, getContext()));
3944           } else {
3945             Error(IDLoc, "immediate value is too large");
3946             return true;
3947           }
3948         } else {
3949           Operands.push_back(ARM64Operand::CreateShifter(
3950               ARM64_AM::LSL, 0, IDLoc, IDLoc, getContext()));
3951         }
3952       }
3953
3954       // FIXME: Horible hack to handle the LSL -> UBFM alias.
3955     } else if (NumOperands == 4 && Tok == "lsl") {
3956       ARM64Operand *Op2 = static_cast<ARM64Operand *>(Operands[2]);
3957       ARM64Operand *Op3 = static_cast<ARM64Operand *>(Operands[3]);
3958       if (Op2->isReg() && Op3->isImm()) {
3959         const MCConstantExpr *Op3CE = dyn_cast<MCConstantExpr>(Op3->getImm());
3960         if (Op3CE) {
3961           uint64_t Op3Val = Op3CE->getValue();
3962           uint64_t NewOp3Val = 0;
3963           uint64_t NewOp4Val = 0;
3964           if (isGPR32Register(Op2->getReg())) {
3965             NewOp3Val = (32 - Op3Val) & 0x1f;
3966             NewOp4Val = 31 - Op3Val;
3967           } else {
3968             NewOp3Val = (64 - Op3Val) & 0x3f;
3969             NewOp4Val = 63 - Op3Val;
3970           }
3971
3972           const MCExpr *NewOp3 =
3973               MCConstantExpr::Create(NewOp3Val, getContext());
3974           const MCExpr *NewOp4 =
3975               MCConstantExpr::Create(NewOp4Val, getContext());
3976
3977           Operands[0] = ARM64Operand::CreateToken(
3978               "ubfm", false, Op->getStartLoc(), getContext());
3979           Operands[3] = ARM64Operand::CreateImm(NewOp3, Op3->getStartLoc(),
3980                                                 Op3->getEndLoc(), getContext());
3981           Operands.push_back(ARM64Operand::CreateImm(
3982               NewOp4, Op3->getStartLoc(), Op3->getEndLoc(), getContext()));
3983           delete Op3;
3984           delete Op;
3985         }
3986       }
3987
3988       // FIXME: Horrible hack to handle the optional LSL shift for vector
3989       //        instructions.
3990     } else if (NumOperands == 4 && (Tok == "bic" || Tok == "orr")) {
3991       ARM64Operand *Op1 = static_cast<ARM64Operand *>(Operands[1]);
3992       ARM64Operand *Op2 = static_cast<ARM64Operand *>(Operands[2]);
3993       ARM64Operand *Op3 = static_cast<ARM64Operand *>(Operands[3]);
3994       if ((Op1->isToken() && Op2->isVectorReg() && Op3->isImm()) ||
3995           (Op1->isVectorReg() && Op2->isToken() && Op3->isImm()))
3996         Operands.push_back(ARM64Operand::CreateShifter(ARM64_AM::LSL, 0, IDLoc,
3997                                                        IDLoc, getContext()));
3998     } else if (NumOperands == 4 && (Tok == "movi" || Tok == "mvni")) {
3999       ARM64Operand *Op1 = static_cast<ARM64Operand *>(Operands[1]);
4000       ARM64Operand *Op2 = static_cast<ARM64Operand *>(Operands[2]);
4001       ARM64Operand *Op3 = static_cast<ARM64Operand *>(Operands[3]);
4002       if ((Op1->isToken() && Op2->isVectorReg() && Op3->isImm()) ||
4003           (Op1->isVectorReg() && Op2->isToken() && Op3->isImm())) {
4004         StringRef Suffix = Op1->isToken() ? Op1->getToken() : Op2->getToken();
4005         // Canonicalize on lower-case for ease of comparison.
4006         std::string CanonicalSuffix = Suffix.lower();
4007         if (Tok != "movi" ||
4008             (CanonicalSuffix != ".1d" && CanonicalSuffix != ".2d" &&
4009              CanonicalSuffix != ".8b" && CanonicalSuffix != ".16b"))
4010           Operands.push_back(ARM64Operand::CreateShifter(
4011               ARM64_AM::LSL, 0, IDLoc, IDLoc, getContext()));
4012       }
4013     }
4014   } else if (NumOperands == 5) {
4015     // FIXME: Horrible hack to handle the BFI -> BFM, SBFIZ->SBFM, and
4016     // UBFIZ -> UBFM aliases.
4017     if (Tok == "bfi" || Tok == "sbfiz" || Tok == "ubfiz") {
4018       ARM64Operand *Op1 = static_cast<ARM64Operand *>(Operands[1]);
4019       ARM64Operand *Op3 = static_cast<ARM64Operand *>(Operands[3]);
4020       ARM64Operand *Op4 = static_cast<ARM64Operand *>(Operands[4]);
4021
4022       if (Op1->isReg() && Op3->isImm() && Op4->isImm()) {
4023         const MCConstantExpr *Op3CE = dyn_cast<MCConstantExpr>(Op3->getImm());
4024         const MCConstantExpr *Op4CE = dyn_cast<MCConstantExpr>(Op4->getImm());
4025
4026         if (Op3CE && Op4CE) {
4027           uint64_t Op3Val = Op3CE->getValue();
4028           uint64_t Op4Val = Op4CE->getValue();
4029
4030           uint64_t NewOp3Val = 0;
4031           if (isGPR32Register(Op1->getReg()))
4032             NewOp3Val = (32 - Op3Val) & 0x1f;
4033           else
4034             NewOp3Val = (64 - Op3Val) & 0x3f;
4035
4036           uint64_t NewOp4Val = Op4Val - 1;
4037
4038           const MCExpr *NewOp3 =
4039               MCConstantExpr::Create(NewOp3Val, getContext());
4040           const MCExpr *NewOp4 =
4041               MCConstantExpr::Create(NewOp4Val, getContext());
4042           Operands[3] = ARM64Operand::CreateImm(NewOp3, Op3->getStartLoc(),
4043                                                 Op3->getEndLoc(), getContext());
4044           Operands[4] = ARM64Operand::CreateImm(NewOp4, Op4->getStartLoc(),
4045                                                 Op4->getEndLoc(), getContext());
4046           if (Tok == "bfi")
4047             Operands[0] = ARM64Operand::CreateToken(
4048                 "bfm", false, Op->getStartLoc(), getContext());
4049           else if (Tok == "sbfiz")
4050             Operands[0] = ARM64Operand::CreateToken(
4051                 "sbfm", false, Op->getStartLoc(), getContext());
4052           else if (Tok == "ubfiz")
4053             Operands[0] = ARM64Operand::CreateToken(
4054                 "ubfm", false, Op->getStartLoc(), getContext());
4055           else
4056             llvm_unreachable("No valid mnemonic for alias?");
4057
4058           delete Op;
4059           delete Op3;
4060           delete Op4;
4061         }
4062       }
4063
4064       // FIXME: Horrible hack to handle the BFXIL->BFM, SBFX->SBFM, and
4065       // UBFX -> UBFM aliases.
4066     } else if (NumOperands == 5 &&
4067                (Tok == "bfxil" || Tok == "sbfx" || Tok == "ubfx")) {
4068       ARM64Operand *Op1 = static_cast<ARM64Operand *>(Operands[1]);
4069       ARM64Operand *Op3 = static_cast<ARM64Operand *>(Operands[3]);
4070       ARM64Operand *Op4 = static_cast<ARM64Operand *>(Operands[4]);
4071
4072       if (Op1->isReg() && Op3->isImm() && Op4->isImm()) {
4073         const MCConstantExpr *Op3CE = dyn_cast<MCConstantExpr>(Op3->getImm());
4074         const MCConstantExpr *Op4CE = dyn_cast<MCConstantExpr>(Op4->getImm());
4075
4076         if (Op3CE && Op4CE) {
4077           uint64_t Op3Val = Op3CE->getValue();
4078           uint64_t Op4Val = Op4CE->getValue();
4079           uint64_t NewOp4Val = Op3Val + Op4Val - 1;
4080
4081           if (NewOp4Val >= Op3Val) {
4082             const MCExpr *NewOp4 =
4083                 MCConstantExpr::Create(NewOp4Val, getContext());
4084             Operands[4] = ARM64Operand::CreateImm(
4085                 NewOp4, Op4->getStartLoc(), Op4->getEndLoc(), getContext());
4086             if (Tok == "bfxil")
4087               Operands[0] = ARM64Operand::CreateToken(
4088                   "bfm", false, Op->getStartLoc(), getContext());
4089             else if (Tok == "sbfx")
4090               Operands[0] = ARM64Operand::CreateToken(
4091                   "sbfm", false, Op->getStartLoc(), getContext());
4092             else if (Tok == "ubfx")
4093               Operands[0] = ARM64Operand::CreateToken(
4094                   "ubfm", false, Op->getStartLoc(), getContext());
4095             else
4096               llvm_unreachable("No valid mnemonic for alias?");
4097
4098             delete Op;
4099             delete Op4;
4100           }
4101         }
4102       }
4103     }
4104   }
4105   // FIXME: Horrible hack for tbz and tbnz with Wn register operand.
4106   //        InstAlias can't quite handle this since the reg classes aren't
4107   //        subclasses.
4108   if (NumOperands == 4 && (Tok == "tbz" || Tok == "tbnz")) {
4109     ARM64Operand *Op = static_cast<ARM64Operand *>(Operands[2]);
4110     if (Op->isImm()) {
4111       if (const MCConstantExpr *OpCE = dyn_cast<MCConstantExpr>(Op->getImm())) {
4112         if (OpCE->getValue() < 32) {
4113           // The source register can be Wn here, but the matcher expects a
4114           // GPR64. Twiddle it here if necessary.
4115           ARM64Operand *Op = static_cast<ARM64Operand *>(Operands[1]);
4116           if (Op->isReg()) {
4117             unsigned Reg = getXRegFromWReg(Op->getReg());
4118             Operands[1] = ARM64Operand::CreateReg(
4119                 Reg, false, Op->getStartLoc(), Op->getEndLoc(), getContext());
4120             delete Op;
4121           }
4122         }
4123       }
4124     }
4125   }
4126   // FIXME: Horrible hack for sxtw and uxtw with Wn src and Xd dst operands.
4127   //        InstAlias can't quite handle this since the reg classes aren't
4128   //        subclasses.
4129   if (NumOperands == 3 && (Tok == "sxtw" || Tok == "uxtw")) {
4130     // The source register can be Wn here, but the matcher expects a
4131     // GPR64. Twiddle it here if necessary.
4132     ARM64Operand *Op = static_cast<ARM64Operand *>(Operands[2]);
4133     if (Op->isReg()) {
4134       unsigned Reg = getXRegFromWReg(Op->getReg());
4135       Operands[2] = ARM64Operand::CreateReg(Reg, false, Op->getStartLoc(),
4136                                             Op->getEndLoc(), getContext());
4137       delete Op;
4138     }
4139   }
4140   // FIXME: Likewise for [su]xt[bh] with a Xd dst operand
4141   else if (NumOperands == 3 &&
4142            (Tok == "sxtb" || Tok == "uxtb" || Tok == "sxth" || Tok == "uxth")) {
4143     ARM64Operand *Op = static_cast<ARM64Operand *>(Operands[1]);
4144     if (Op->isReg() && isGPR64Reg(Op->getReg())) {
4145       // The source register can be Wn here, but the matcher expects a
4146       // GPR64. Twiddle it here if necessary.
4147       ARM64Operand *Op = static_cast<ARM64Operand *>(Operands[2]);
4148       if (Op->isReg()) {
4149         unsigned Reg = getXRegFromWReg(Op->getReg());
4150         Operands[2] = ARM64Operand::CreateReg(Reg, false, Op->getStartLoc(),
4151                                               Op->getEndLoc(), getContext());
4152         delete Op;
4153       }
4154     }
4155   }
4156
4157   // Yet another horrible hack to handle FMOV Rd, #0.0 using [WX]ZR.
4158   if (NumOperands == 3 && Tok == "fmov") {
4159     ARM64Operand *RegOp = static_cast<ARM64Operand *>(Operands[1]);
4160     ARM64Operand *ImmOp = static_cast<ARM64Operand *>(Operands[2]);
4161     if (RegOp->isReg() && ImmOp->isFPImm() &&
4162         ImmOp->getFPImm() == (unsigned)-1) {
4163       unsigned zreg =
4164           isFPR32Register(RegOp->getReg()) ? ARM64::WZR : ARM64::XZR;
4165       Operands[2] = ARM64Operand::CreateReg(zreg, false, Op->getStartLoc(),
4166                                             Op->getEndLoc(), getContext());
4167       delete ImmOp;
4168     }
4169   }
4170
4171   // FIXME: Horrible hack to handle the literal .d[1] vector index on
4172   // FMOV instructions. The index isn't an actual instruction operand
4173   // but rather syntactic sugar. It really should be part of the mnemonic,
4174   // not the operand, but whatever.
4175   if ((NumOperands == 5) && Tok == "fmov") {
4176     // If the last operand is a vectorindex of '1', then replace it with
4177     // a '[' '1' ']' token sequence, which is what the matcher
4178     // (annoyingly) expects for a literal vector index operand.
4179     ARM64Operand *Op = static_cast<ARM64Operand *>(Operands[NumOperands - 1]);
4180     if (Op->isVectorIndexD() && Op->getVectorIndex() == 1) {
4181       SMLoc Loc = Op->getStartLoc();
4182       Operands.pop_back();
4183       Operands.push_back(
4184           ARM64Operand::CreateToken("[", false, Loc, getContext()));
4185       Operands.push_back(
4186           ARM64Operand::CreateToken("1", false, Loc, getContext()));
4187       Operands.push_back(
4188           ARM64Operand::CreateToken("]", false, Loc, getContext()));
4189     } else if (Op->isReg()) {
4190       // Similarly, check the destination operand for the GPR->High-lane
4191       // variant.
4192       unsigned OpNo = NumOperands - 2;
4193       ARM64Operand *Op = static_cast<ARM64Operand *>(Operands[OpNo]);
4194       if (Op->isVectorIndexD() && Op->getVectorIndex() == 1) {
4195         SMLoc Loc = Op->getStartLoc();
4196         Operands[OpNo] =
4197             ARM64Operand::CreateToken("[", false, Loc, getContext());
4198         Operands.insert(
4199             Operands.begin() + OpNo + 1,
4200             ARM64Operand::CreateToken("1", false, Loc, getContext()));
4201         Operands.insert(
4202             Operands.begin() + OpNo + 2,
4203             ARM64Operand::CreateToken("]", false, Loc, getContext()));
4204       }
4205     }
4206   }
4207
4208   MCInst Inst;
4209   // First try to match against the secondary set of tables containing the
4210   // short-form NEON instructions (e.g. "fadd.2s v0, v1, v2").
4211   unsigned MatchResult =
4212       MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm, 1);
4213
4214   // If that fails, try against the alternate table containing long-form NEON:
4215   // "fadd v0.2s, v1.2s, v2.2s"
4216   if (MatchResult != Match_Success)
4217     MatchResult =
4218         MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm, 0);
4219
4220   switch (MatchResult) {
4221   case Match_Success: {
4222     // Perform range checking and other semantic validations
4223     SmallVector<SMLoc, 8> OperandLocs;
4224     NumOperands = Operands.size();
4225     for (unsigned i = 1; i < NumOperands; ++i)
4226       OperandLocs.push_back(Operands[i]->getStartLoc());
4227     if (validateInstruction(Inst, OperandLocs))
4228       return true;
4229
4230     Inst.setLoc(IDLoc);
4231     Out.EmitInstruction(Inst, STI);
4232     return false;
4233   }
4234   case Match_MissingFeature:
4235   case Match_MnemonicFail:
4236     return showMatchError(IDLoc, MatchResult);
4237   case Match_InvalidOperand: {
4238     SMLoc ErrorLoc = IDLoc;
4239     if (ErrorInfo != ~0U) {
4240       if (ErrorInfo >= Operands.size())
4241         return Error(IDLoc, "too few operands for instruction");
4242
4243       ErrorLoc = ((ARM64Operand *)Operands[ErrorInfo])->getStartLoc();
4244       if (ErrorLoc == SMLoc())
4245         ErrorLoc = IDLoc;
4246     }
4247     // If the match failed on a suffix token operand, tweak the diagnostic
4248     // accordingly.
4249     if (((ARM64Operand *)Operands[ErrorInfo])->isToken() &&
4250         ((ARM64Operand *)Operands[ErrorInfo])->isTokenSuffix())
4251       MatchResult = Match_InvalidSuffix;
4252
4253     return showMatchError(ErrorLoc, MatchResult);
4254   }
4255   case Match_InvalidMemoryIndexedSImm9: {
4256     // If there is not a '!' after the memory operand that failed, we really
4257     // want the diagnostic for the non-pre-indexed instruction variant instead.
4258     // Be careful to check for the post-indexed variant as well, which also
4259     // uses this match diagnostic. Also exclude the explicitly unscaled
4260     // mnemonics, as they want the unscaled diagnostic as well.
4261     if (Operands.size() == ErrorInfo + 1 &&
4262         !((ARM64Operand *)Operands[ErrorInfo])->isImm() &&
4263         !Tok.startswith("stur") && !Tok.startswith("ldur")) {
4264       // whether we want an Indexed64 or Indexed32 diagnostic depends on
4265       // the register class of the previous operand. Default to 64 in case
4266       // we see something unexpected.
4267       MatchResult = Match_InvalidMemoryIndexed64;
4268       if (ErrorInfo) {
4269         ARM64Operand *PrevOp = (ARM64Operand *)Operands[ErrorInfo - 1];
4270         if (PrevOp->isReg() && ARM64MCRegisterClasses[ARM64::GPR32RegClassID]
4271                                    .contains(PrevOp->getReg()))
4272           MatchResult = Match_InvalidMemoryIndexed32;
4273       }
4274     }
4275     SMLoc ErrorLoc = ((ARM64Operand *)Operands[ErrorInfo])->getStartLoc();
4276     if (ErrorLoc == SMLoc())
4277       ErrorLoc = IDLoc;
4278     return showMatchError(ErrorLoc, MatchResult);
4279   }
4280   case Match_InvalidMemoryIndexed32:
4281   case Match_InvalidMemoryIndexed64:
4282   case Match_InvalidMemoryIndexed128:
4283     // If there is a '!' after the memory operand that failed, we really
4284     // want the diagnostic for the pre-indexed instruction variant instead.
4285     if (Operands.size() > ErrorInfo + 1 &&
4286         ((ARM64Operand *)Operands[ErrorInfo + 1])->isTokenEqual("!"))
4287       MatchResult = Match_InvalidMemoryIndexedSImm9;
4288   // FALL THROUGH
4289   case Match_InvalidMemoryIndexed8:
4290   case Match_InvalidMemoryIndexed16:
4291   case Match_InvalidMemoryIndexed32SImm7:
4292   case Match_InvalidMemoryIndexed64SImm7:
4293   case Match_InvalidMemoryIndexed128SImm7:
4294   case Match_InvalidImm1_8:
4295   case Match_InvalidImm1_16:
4296   case Match_InvalidImm1_32:
4297   case Match_InvalidImm1_64: {
4298     // Any time we get here, there's nothing fancy to do. Just get the
4299     // operand SMLoc and display the diagnostic.
4300     SMLoc ErrorLoc = ((ARM64Operand *)Operands[ErrorInfo])->getStartLoc();
4301     // If it's a memory operand, the error is with the offset immediate,
4302     // so get that location instead.
4303     if (((ARM64Operand *)Operands[ErrorInfo])->isMem())
4304       ErrorLoc = ((ARM64Operand *)Operands[ErrorInfo])->getOffsetLoc();
4305     if (ErrorLoc == SMLoc())
4306       ErrorLoc = IDLoc;
4307     return showMatchError(ErrorLoc, MatchResult);
4308   }
4309   }
4310
4311   llvm_unreachable("Implement any new match types added!");
4312   return true;
4313 }
4314
4315 /// ParseDirective parses the arm specific directives
4316 bool ARM64AsmParser::ParseDirective(AsmToken DirectiveID) {
4317   StringRef IDVal = DirectiveID.getIdentifier();
4318   SMLoc Loc = DirectiveID.getLoc();
4319   if (IDVal == ".hword")
4320     return parseDirectiveWord(2, Loc);
4321   if (IDVal == ".word")
4322     return parseDirectiveWord(4, Loc);
4323   if (IDVal == ".xword")
4324     return parseDirectiveWord(8, Loc);
4325   if (IDVal == ".tlsdesccall")
4326     return parseDirectiveTLSDescCall(Loc);
4327
4328   return parseDirectiveLOH(IDVal, Loc);
4329 }
4330
4331 /// parseDirectiveWord
4332 ///  ::= .word [ expression (, expression)* ]
4333 bool ARM64AsmParser::parseDirectiveWord(unsigned Size, SMLoc L) {
4334   if (getLexer().isNot(AsmToken::EndOfStatement)) {
4335     for (;;) {
4336       const MCExpr *Value;
4337       if (getParser().parseExpression(Value))
4338         return true;
4339
4340       getParser().getStreamer().EmitValue(Value, Size);
4341
4342       if (getLexer().is(AsmToken::EndOfStatement))
4343         break;
4344
4345       // FIXME: Improve diagnostic.
4346       if (getLexer().isNot(AsmToken::Comma))
4347         return Error(L, "unexpected token in directive");
4348       Parser.Lex();
4349     }
4350   }
4351
4352   Parser.Lex();
4353   return false;
4354 }
4355
4356 // parseDirectiveTLSDescCall:
4357 //   ::= .tlsdesccall symbol
4358 bool ARM64AsmParser::parseDirectiveTLSDescCall(SMLoc L) {
4359   StringRef Name;
4360   if (getParser().parseIdentifier(Name))
4361     return Error(L, "expected symbol after directive");
4362
4363   MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
4364   const MCExpr *Expr = MCSymbolRefExpr::Create(Sym, getContext());
4365   Expr = ARM64MCExpr::Create(Expr, ARM64MCExpr::VK_TLSDESC, getContext());
4366
4367   MCInst Inst;
4368   Inst.setOpcode(ARM64::TLSDESCCALL);
4369   Inst.addOperand(MCOperand::CreateExpr(Expr));
4370
4371   getParser().getStreamer().EmitInstruction(Inst, STI);
4372   return false;
4373 }
4374
4375 /// ::= .loh <lohName | lohId> label1, ..., labelN
4376 /// The number of arguments depends on the loh identifier.
4377 bool ARM64AsmParser::parseDirectiveLOH(StringRef IDVal, SMLoc Loc) {
4378   if (IDVal != MCLOHDirectiveName())
4379     return true;
4380   MCLOHType Kind;
4381   if (getParser().getTok().isNot(AsmToken::Identifier)) {
4382     if (getParser().getTok().isNot(AsmToken::Integer))
4383       return TokError("expected an identifier or a number in directive");
4384     // We successfully get a numeric value for the identifier.
4385     // Check if it is valid.
4386     int64_t Id = getParser().getTok().getIntVal();
4387     Kind = (MCLOHType)Id;
4388     // Check that Id does not overflow MCLOHType.
4389     if (!isValidMCLOHType(Kind) || Id != Kind)
4390       return TokError("invalid numeric identifier in directive");
4391   } else {
4392     StringRef Name = getTok().getIdentifier();
4393     // We successfully parse an identifier.
4394     // Check if it is a recognized one.
4395     int Id = MCLOHNameToId(Name);
4396
4397     if (Id == -1)
4398       return TokError("invalid identifier in directive");
4399     Kind = (MCLOHType)Id;
4400   }
4401   // Consume the identifier.
4402   Lex();
4403   // Get the number of arguments of this LOH.
4404   int NbArgs = MCLOHIdToNbArgs(Kind);
4405
4406   assert(NbArgs != -1 && "Invalid number of arguments");
4407
4408   SmallVector<MCSymbol *, 3> Args;
4409   for (int Idx = 0; Idx < NbArgs; ++Idx) {
4410     StringRef Name;
4411     if (getParser().parseIdentifier(Name))
4412       return TokError("expected identifier in directive");
4413     Args.push_back(getContext().GetOrCreateSymbol(Name));
4414
4415     if (Idx + 1 == NbArgs)
4416       break;
4417     if (getLexer().isNot(AsmToken::Comma))
4418       return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
4419     Lex();
4420   }
4421   if (getLexer().isNot(AsmToken::EndOfStatement))
4422     return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
4423
4424   getStreamer().EmitLOHDirective((MCLOHType)Kind, Args);
4425   return false;
4426 }
4427
4428 bool
4429 ARM64AsmParser::classifySymbolRef(const MCExpr *Expr,
4430                                   ARM64MCExpr::VariantKind &ELFRefKind,
4431                                   MCSymbolRefExpr::VariantKind &DarwinRefKind,
4432                                   const MCConstantExpr *&Addend) {
4433   ELFRefKind = ARM64MCExpr::VK_INVALID;
4434   DarwinRefKind = MCSymbolRefExpr::VK_None;
4435
4436   if (const ARM64MCExpr *AE = dyn_cast<ARM64MCExpr>(Expr)) {
4437     ELFRefKind = AE->getKind();
4438     Expr = AE->getSubExpr();
4439   }
4440
4441   const MCSymbolRefExpr *SE = dyn_cast<MCSymbolRefExpr>(Expr);
4442   if (SE) {
4443     // It's a simple symbol reference with no addend.
4444     DarwinRefKind = SE->getKind();
4445     Addend = 0;
4446     return true;
4447   }
4448
4449   const MCBinaryExpr *BE = dyn_cast<MCBinaryExpr>(Expr);
4450   if (!BE)
4451     return false;
4452
4453   SE = dyn_cast<MCSymbolRefExpr>(BE->getLHS());
4454   if (!SE)
4455     return false;
4456   DarwinRefKind = SE->getKind();
4457
4458   if (BE->getOpcode() != MCBinaryExpr::Add)
4459     return false;
4460
4461   // See if the addend is is a constant, otherwise there's more going
4462   // on here than we can deal with.
4463   Addend = dyn_cast<MCConstantExpr>(BE->getRHS());
4464   if (!Addend)
4465     return false;
4466
4467   // It's some symbol reference + a constant addend, but really
4468   // shouldn't use both Darwin and ELF syntax.
4469   return ELFRefKind == ARM64MCExpr::VK_INVALID ||
4470          DarwinRefKind == MCSymbolRefExpr::VK_None;
4471 }
4472
4473 /// Force static initialization.
4474 extern "C" void LLVMInitializeARM64AsmParser() {
4475   RegisterMCAsmParser<ARM64AsmParser> X(TheARM64Target);
4476 }
4477
4478 #define GET_REGISTER_MATCHER
4479 #define GET_MATCHER_IMPLEMENTATION
4480 #include "ARM64GenAsmMatcher.inc"
4481
4482 // Define this matcher function after the auto-generated include so we
4483 // have the match class enum definitions.
4484 unsigned ARM64AsmParser::validateTargetOperandClass(MCParsedAsmOperand *AsmOp,
4485                                                     unsigned Kind) {
4486   ARM64Operand *Op = static_cast<ARM64Operand *>(AsmOp);
4487   // If the kind is a token for a literal immediate, check if our asm
4488   // operand matches. This is for InstAliases which have a fixed-value
4489   // immediate in the syntax.
4490   int64_t ExpectedVal;
4491   switch (Kind) {
4492   default:
4493     return Match_InvalidOperand;
4494   case MCK__35_0:
4495     ExpectedVal = 0;
4496     break;
4497   case MCK__35_1:
4498     ExpectedVal = 1;
4499     break;
4500   case MCK__35_12:
4501     ExpectedVal = 12;
4502     break;
4503   case MCK__35_16:
4504     ExpectedVal = 16;
4505     break;
4506   case MCK__35_2:
4507     ExpectedVal = 2;
4508     break;
4509   case MCK__35_24:
4510     ExpectedVal = 24;
4511     break;
4512   case MCK__35_3:
4513     ExpectedVal = 3;
4514     break;
4515   case MCK__35_32:
4516     ExpectedVal = 32;
4517     break;
4518   case MCK__35_4:
4519     ExpectedVal = 4;
4520     break;
4521   case MCK__35_48:
4522     ExpectedVal = 48;
4523     break;
4524   case MCK__35_6:
4525     ExpectedVal = 6;
4526     break;
4527   case MCK__35_64:
4528     ExpectedVal = 64;
4529     break;
4530   case MCK__35_8:
4531     ExpectedVal = 8;
4532     break;
4533   }
4534   if (!Op->isImm())
4535     return Match_InvalidOperand;
4536   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op->getImm());
4537   if (!CE)
4538     return Match_InvalidOperand;
4539   if (CE->getValue() == ExpectedVal)
4540     return Match_Success;
4541   return Match_InvalidOperand;
4542 }