OSDN Git Service

[AArch64] Add support for NEON scalar shift immediate instructions.
[android-x86/external-llvm.git] / lib / Target / AArch64 / AsmParser / AArch64AsmParser.cpp
1 //==- AArch64AsmParser.cpp - Parse AArch64 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 // This file contains the (GNU-style) assembly parser for the AArch64
11 // architecture.
12 //
13 //===----------------------------------------------------------------------===//
14
15
16 #include "MCTargetDesc/AArch64MCTargetDesc.h"
17 #include "MCTargetDesc/AArch64MCExpr.h"
18 #include "Utils/AArch64BaseInfo.h"
19 #include "llvm/ADT/APFloat.h"
20 #include "llvm/ADT/APInt.h"
21 #include "llvm/ADT/StringSwitch.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/MC/MCContext.h"
24 #include "llvm/MC/MCInst.h"
25 #include "llvm/MC/MCSubtargetInfo.h"
26 #include "llvm/MC/MCTargetAsmParser.h"
27 #include "llvm/MC/MCExpr.h"
28 #include "llvm/MC/MCRegisterInfo.h"
29 #include "llvm/MC/MCStreamer.h"
30 #include "llvm/MC/MCParser/MCAsmLexer.h"
31 #include "llvm/MC/MCParser/MCAsmParser.h"
32 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Support/TargetRegistry.h"
36
37 using namespace llvm;
38
39 namespace {
40
41 class AArch64Operand;
42
43 class AArch64AsmParser : public MCTargetAsmParser {
44   MCSubtargetInfo &STI;
45   MCAsmParser &Parser;
46
47 #define GET_ASSEMBLER_HEADER
48 #include "AArch64GenAsmMatcher.inc"
49
50 public:
51   enum AArch64MatchResultTy {
52     Match_FirstAArch64 = FIRST_TARGET_MATCH_RESULT_TY,
53 #define GET_OPERAND_DIAGNOSTIC_TYPES
54 #include "AArch64GenAsmMatcher.inc"
55   };
56
57   AArch64AsmParser(MCSubtargetInfo &_STI, MCAsmParser &_Parser,
58                    const MCInstrInfo &MII)
59       : MCTargetAsmParser(), STI(_STI), Parser(_Parser) {
60     MCAsmParserExtension::Initialize(_Parser);
61
62     // Initialize the set of available features.
63     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
64   }
65
66   // These are the public interface of the MCTargetAsmParser
67   bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
68   bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
69                         SMLoc NameLoc,
70                         SmallVectorImpl<MCParsedAsmOperand*> &Operands);
71
72   bool ParseDirective(AsmToken DirectiveID);
73   bool ParseDirectiveTLSDescCall(SMLoc L);
74   bool ParseDirectiveWord(unsigned Size, SMLoc L);
75
76   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
77                                SmallVectorImpl<MCParsedAsmOperand*> &Operands,
78                                MCStreamer&Out, unsigned &ErrorInfo,
79                                bool MatchingInlineAsm);
80
81   // The rest of the sub-parsers have more freedom over interface: they return
82   // an OperandMatchResultTy because it's less ambiguous than true/false or
83   // -1/0/1 even if it is more verbose
84   OperandMatchResultTy
85   ParseOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands,
86                StringRef Mnemonic);
87
88   OperandMatchResultTy ParseImmediate(const MCExpr *&ExprVal);
89
90   OperandMatchResultTy ParseRelocPrefix(AArch64MCExpr::VariantKind &RefKind);
91
92   OperandMatchResultTy
93   ParseNEONLane(SmallVectorImpl<MCParsedAsmOperand*> &Operands,
94                 uint32_t NumLanes);
95
96   OperandMatchResultTy
97   ParseRegister(SmallVectorImpl<MCParsedAsmOperand*> &Operands,
98                 uint32_t &NumLanes);
99
100   OperandMatchResultTy
101   ParseImmWithLSLOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands);
102
103   OperandMatchResultTy
104   ParseCondCodeOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands);
105
106   OperandMatchResultTy
107   ParseCRxOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands);
108
109   OperandMatchResultTy
110   ParseFPImmOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands);
111
112   template<typename SomeNamedImmMapper> OperandMatchResultTy
113   ParseNamedImmOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
114     return ParseNamedImmOperand(SomeNamedImmMapper(), Operands);
115   }
116
117   OperandMatchResultTy
118   ParseNamedImmOperand(const NamedImmMapper &Mapper,
119                        SmallVectorImpl<MCParsedAsmOperand*> &Operands);
120
121   OperandMatchResultTy
122   ParseLSXAddressOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands);
123
124   OperandMatchResultTy
125   ParseShiftExtend(SmallVectorImpl<MCParsedAsmOperand*> &Operands);
126
127   OperandMatchResultTy
128   ParseSysRegOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands);
129
130   bool TryParseVector(uint32_t &RegNum, SMLoc &RegEndLoc, StringRef &Layout,
131                       SMLoc &LayoutLoc);
132
133   OperandMatchResultTy ParseVectorList(SmallVectorImpl<MCParsedAsmOperand *> &);
134
135   bool validateInstruction(MCInst &Inst,
136                           const SmallVectorImpl<MCParsedAsmOperand*> &Operands);
137
138   /// Scan the next token (which had better be an identifier) and determine
139   /// whether it represents a general-purpose or vector register. It returns
140   /// true if an identifier was found and populates its reference arguments. It
141   /// does not consume the token.
142   bool
143   IdentifyRegister(unsigned &RegNum, SMLoc &RegEndLoc, StringRef &LayoutSpec,
144                    SMLoc &LayoutLoc) const;
145
146 };
147
148 }
149
150 namespace {
151
152 /// Instances of this class represent a parsed AArch64 machine instruction.
153 class AArch64Operand : public MCParsedAsmOperand {
154 private:
155   enum KindTy {
156     k_ImmWithLSL,     // #uimm {, LSL #amt }
157     k_CondCode,       // eq/ne/...
158     k_FPImmediate,    // Limited-precision floating-point imm
159     k_Immediate,      // Including expressions referencing symbols
160     k_Register,
161     k_ShiftExtend,
162     k_VectorList,     // A sequential list of 1 to 4 registers.
163     k_SysReg,         // The register operand of MRS and MSR instructions
164     k_Token,          // The mnemonic; other raw tokens the auto-generated
165     k_WrappedRegister // Load/store exclusive permit a wrapped register.
166   } Kind;
167
168   SMLoc StartLoc, EndLoc;
169
170   struct ImmWithLSLOp {
171     const MCExpr *Val;
172     unsigned ShiftAmount;
173     bool ImplicitAmount;
174   };
175
176   struct CondCodeOp {
177     A64CC::CondCodes Code;
178   };
179
180   struct FPImmOp {
181     double Val;
182   };
183
184   struct ImmOp {
185     const MCExpr *Val;
186   };
187
188   struct RegOp {
189     unsigned RegNum;
190   };
191
192   struct ShiftExtendOp {
193     A64SE::ShiftExtSpecifiers ShiftType;
194     unsigned Amount;
195     bool ImplicitAmount;
196   };
197
198   // A vector register list is a sequential list of 1 to 4 registers.
199   struct VectorListOp {
200     unsigned RegNum;
201     unsigned Count;
202     A64Layout::VectorLayout Layout;
203   };
204
205   struct SysRegOp {
206     const char *Data;
207     unsigned Length;
208   };
209
210   struct TokOp {
211     const char *Data;
212     unsigned Length;
213   };
214
215   union {
216     struct ImmWithLSLOp ImmWithLSL;
217     struct CondCodeOp CondCode;
218     struct FPImmOp FPImm;
219     struct ImmOp Imm;
220     struct RegOp Reg;
221     struct ShiftExtendOp ShiftExtend;
222     struct VectorListOp VectorList;
223     struct SysRegOp SysReg;
224     struct TokOp Tok;
225   };
226
227   AArch64Operand(KindTy K, SMLoc S, SMLoc E)
228     : MCParsedAsmOperand(), Kind(K), StartLoc(S), EndLoc(E) {}
229
230 public:
231   AArch64Operand(const AArch64Operand &o) : MCParsedAsmOperand() {
232   }
233
234   SMLoc getStartLoc() const { return StartLoc; }
235   SMLoc getEndLoc() const { return EndLoc; }
236   void print(raw_ostream&) const;
237   void dump() const;
238
239   StringRef getToken() const {
240     assert(Kind == k_Token && "Invalid access!");
241     return StringRef(Tok.Data, Tok.Length);
242   }
243
244   unsigned getReg() const {
245     assert((Kind == k_Register || Kind == k_WrappedRegister)
246            && "Invalid access!");
247     return Reg.RegNum;
248   }
249
250   const MCExpr *getImm() const {
251     assert(Kind == k_Immediate && "Invalid access!");
252     return Imm.Val;
253   }
254
255   A64CC::CondCodes getCondCode() const {
256     assert(Kind == k_CondCode && "Invalid access!");
257     return CondCode.Code;
258   }
259
260   static bool isNonConstantExpr(const MCExpr *E,
261                                 AArch64MCExpr::VariantKind &Variant) {
262     if (const AArch64MCExpr *A64E = dyn_cast<AArch64MCExpr>(E)) {
263       Variant = A64E->getKind();
264       return true;
265     } else if (!isa<MCConstantExpr>(E)) {
266       Variant = AArch64MCExpr::VK_AARCH64_None;
267       return true;
268     }
269
270     return false;
271   }
272
273   bool isCondCode() const { return Kind == k_CondCode; }
274   bool isToken() const { return Kind == k_Token; }
275   bool isReg() const { return Kind == k_Register; }
276   bool isImm() const { return Kind == k_Immediate; }
277   bool isMem() const { return false; }
278   bool isFPImm() const { return Kind == k_FPImmediate; }
279   bool isShiftOrExtend() const { return Kind == k_ShiftExtend; }
280   bool isSysReg() const { return Kind == k_SysReg; }
281   bool isImmWithLSL() const { return Kind == k_ImmWithLSL; }
282   bool isWrappedReg() const { return Kind == k_WrappedRegister; }
283
284   bool isAddSubImmLSL0() const {
285     if (!isImmWithLSL()) return false;
286     if (ImmWithLSL.ShiftAmount != 0) return false;
287
288     AArch64MCExpr::VariantKind Variant;
289     if (isNonConstantExpr(ImmWithLSL.Val, Variant)) {
290       return Variant == AArch64MCExpr::VK_AARCH64_LO12
291           || Variant == AArch64MCExpr::VK_AARCH64_DTPREL_LO12
292           || Variant == AArch64MCExpr::VK_AARCH64_DTPREL_LO12_NC
293           || Variant == AArch64MCExpr::VK_AARCH64_TPREL_LO12
294           || Variant == AArch64MCExpr::VK_AARCH64_TPREL_LO12_NC
295           || Variant == AArch64MCExpr::VK_AARCH64_TLSDESC_LO12;
296     }
297
298     // Otherwise it should be a real immediate in range:
299     const MCConstantExpr *CE = cast<MCConstantExpr>(ImmWithLSL.Val);
300     return CE->getValue() >= 0 && CE->getValue() <= 0xfff;
301   }
302
303   bool isAddSubImmLSL12() const {
304     if (!isImmWithLSL()) return false;
305     if (ImmWithLSL.ShiftAmount != 12) return false;
306
307     AArch64MCExpr::VariantKind Variant;
308     if (isNonConstantExpr(ImmWithLSL.Val, Variant)) {
309       return Variant == AArch64MCExpr::VK_AARCH64_DTPREL_HI12
310           || Variant == AArch64MCExpr::VK_AARCH64_TPREL_HI12;
311     }
312
313     // Otherwise it should be a real immediate in range:
314     const MCConstantExpr *CE = cast<MCConstantExpr>(ImmWithLSL.Val);
315     return CE->getValue() >= 0 && CE->getValue() <= 0xfff;
316   }
317
318   template<unsigned MemSize, unsigned RmSize> bool isAddrRegExtend() const {
319     if (!isShiftOrExtend()) return false;
320
321     A64SE::ShiftExtSpecifiers Ext = ShiftExtend.ShiftType;
322     if (RmSize == 32 && !(Ext == A64SE::UXTW || Ext == A64SE::SXTW))
323       return false;
324
325     if (RmSize == 64 && !(Ext == A64SE::LSL || Ext == A64SE::SXTX))
326       return false;
327
328     return ShiftExtend.Amount == Log2_32(MemSize) || ShiftExtend.Amount == 0;
329   }
330
331   bool isAdrpLabel() const {
332     if (!isImm()) return false;
333
334     AArch64MCExpr::VariantKind Variant;
335     if (isNonConstantExpr(getImm(), Variant)) {
336       return Variant == AArch64MCExpr::VK_AARCH64_None
337         || Variant == AArch64MCExpr::VK_AARCH64_GOT
338         || Variant == AArch64MCExpr::VK_AARCH64_GOTTPREL
339         || Variant == AArch64MCExpr::VK_AARCH64_TLSDESC;
340     }
341
342     return isLabel<21, 4096>();
343   }
344
345   template<unsigned RegWidth>  bool isBitfieldWidth() const {
346     if (!isImm()) return false;
347
348     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
349     if (!CE) return false;
350
351     return CE->getValue() >= 1 && CE->getValue() <= RegWidth;
352   }
353
354   template<int RegWidth>
355   bool isCVTFixedPos() const {
356     if (!isImm()) return false;
357
358     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
359     if (!CE) return false;
360
361     return CE->getValue() >= 1 && CE->getValue() <= RegWidth;
362   }
363
364   bool isFMOVImm() const {
365     if (!isFPImm()) return false;
366
367     APFloat RealVal(FPImm.Val);
368     uint32_t ImmVal;
369     return A64Imms::isFPImm(RealVal, ImmVal);
370   }
371
372   bool isFPZero() const {
373     if (!isFPImm()) return false;
374
375     APFloat RealVal(FPImm.Val);
376     return RealVal.isPosZero();
377   }
378
379   template<unsigned field_width, unsigned scale>
380   bool isLabel() const {
381     if (!isImm()) return false;
382
383     if (dyn_cast<MCSymbolRefExpr>(Imm.Val)) {
384       return true;
385     } else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
386       int64_t Val = CE->getValue();
387       int64_t Min = - (scale * (1LL << (field_width - 1)));
388       int64_t Max = scale * ((1LL << (field_width - 1)) - 1);
389       return (Val % scale) == 0 && Val >= Min && Val <= Max;
390     }
391
392     // N.b. this disallows explicit relocation specifications via an
393     // AArch64MCExpr. Users needing that behaviour
394     return false;
395   }
396
397   bool isLane1() const {
398     if (!isImm()) return false;
399
400     // Because it's come through custom assembly parsing, it must always be a
401     // constant expression.
402     return cast<MCConstantExpr>(getImm())->getValue() == 1;
403   }
404
405   bool isLoadLitLabel() const {
406     if (!isImm()) return false;
407
408     AArch64MCExpr::VariantKind Variant;
409     if (isNonConstantExpr(getImm(), Variant)) {
410       return Variant == AArch64MCExpr::VK_AARCH64_None
411           || Variant == AArch64MCExpr::VK_AARCH64_GOTTPREL;
412     }
413
414     return isLabel<19, 4>();
415   }
416
417   template<unsigned RegWidth> bool isLogicalImm() const {
418     if (!isImm()) return false;
419
420     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val);
421     if (!CE) return false;
422
423     uint32_t Bits;
424     return A64Imms::isLogicalImm(RegWidth, CE->getValue(), Bits);
425   }
426
427   template<unsigned RegWidth> bool isLogicalImmMOV() const {
428     if (!isLogicalImm<RegWidth>()) return false;
429
430     const MCConstantExpr *CE = cast<MCConstantExpr>(Imm.Val);
431
432     // The move alias for ORR is only valid if the immediate cannot be
433     // represented with a move (immediate) instruction; they take priority.
434     int UImm16, Shift;
435     return !A64Imms::isMOVZImm(RegWidth, CE->getValue(), UImm16, Shift)
436       && !A64Imms::isMOVNImm(RegWidth, CE->getValue(), UImm16, Shift);
437   }
438
439   template<int MemSize>
440   bool isOffsetUImm12() const {
441     if (!isImm()) return false;
442
443     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
444
445     // Assume they know what they're doing for now if they've given us a
446     // non-constant expression. In principle we could check for ridiculous
447     // things that can't possibly work or relocations that would almost
448     // certainly break resulting code.
449     if (!CE)
450       return true;
451
452     int64_t Val = CE->getValue();
453
454     // Must be a multiple of the access size in bytes.
455     if ((Val & (MemSize - 1)) != 0) return false;
456
457     // Must be 12-bit unsigned
458     return Val >= 0 && Val <= 0xfff * MemSize;
459   }
460
461   template<A64SE::ShiftExtSpecifiers SHKind, bool is64Bit>
462   bool isShift() const {
463     if (!isShiftOrExtend()) return false;
464
465     if (ShiftExtend.ShiftType != SHKind)
466       return false;
467
468     return is64Bit ? ShiftExtend.Amount <= 63 : ShiftExtend.Amount <= 31;
469   }
470
471   bool isMOVN32Imm() const {
472     static const AArch64MCExpr::VariantKind PermittedModifiers[] = {
473       AArch64MCExpr::VK_AARCH64_SABS_G0,
474       AArch64MCExpr::VK_AARCH64_SABS_G1,
475       AArch64MCExpr::VK_AARCH64_DTPREL_G1,
476       AArch64MCExpr::VK_AARCH64_DTPREL_G0,
477       AArch64MCExpr::VK_AARCH64_GOTTPREL_G1,
478       AArch64MCExpr::VK_AARCH64_TPREL_G1,
479       AArch64MCExpr::VK_AARCH64_TPREL_G0,
480     };
481     const unsigned NumModifiers = llvm::array_lengthof(PermittedModifiers);
482
483     return isMoveWideImm(32, PermittedModifiers, NumModifiers);
484   }
485
486   bool isMOVN64Imm() const {
487     static const AArch64MCExpr::VariantKind PermittedModifiers[] = {
488       AArch64MCExpr::VK_AARCH64_SABS_G0,
489       AArch64MCExpr::VK_AARCH64_SABS_G1,
490       AArch64MCExpr::VK_AARCH64_SABS_G2,
491       AArch64MCExpr::VK_AARCH64_DTPREL_G2,
492       AArch64MCExpr::VK_AARCH64_DTPREL_G1,
493       AArch64MCExpr::VK_AARCH64_DTPREL_G0,
494       AArch64MCExpr::VK_AARCH64_GOTTPREL_G1,
495       AArch64MCExpr::VK_AARCH64_TPREL_G2,
496       AArch64MCExpr::VK_AARCH64_TPREL_G1,
497       AArch64MCExpr::VK_AARCH64_TPREL_G0,
498     };
499     const unsigned NumModifiers = llvm::array_lengthof(PermittedModifiers);
500
501     return isMoveWideImm(64, PermittedModifiers, NumModifiers);
502   }
503
504
505   bool isMOVZ32Imm() const {
506     static const AArch64MCExpr::VariantKind PermittedModifiers[] = {
507       AArch64MCExpr::VK_AARCH64_ABS_G0,
508       AArch64MCExpr::VK_AARCH64_ABS_G1,
509       AArch64MCExpr::VK_AARCH64_SABS_G0,
510       AArch64MCExpr::VK_AARCH64_SABS_G1,
511       AArch64MCExpr::VK_AARCH64_DTPREL_G1,
512       AArch64MCExpr::VK_AARCH64_DTPREL_G0,
513       AArch64MCExpr::VK_AARCH64_GOTTPREL_G1,
514       AArch64MCExpr::VK_AARCH64_TPREL_G1,
515       AArch64MCExpr::VK_AARCH64_TPREL_G0,
516     };
517     const unsigned NumModifiers = llvm::array_lengthof(PermittedModifiers);
518
519     return isMoveWideImm(32, PermittedModifiers, NumModifiers);
520   }
521
522   bool isMOVZ64Imm() const {
523     static const AArch64MCExpr::VariantKind PermittedModifiers[] = {
524       AArch64MCExpr::VK_AARCH64_ABS_G0,
525       AArch64MCExpr::VK_AARCH64_ABS_G1,
526       AArch64MCExpr::VK_AARCH64_ABS_G2,
527       AArch64MCExpr::VK_AARCH64_ABS_G3,
528       AArch64MCExpr::VK_AARCH64_SABS_G0,
529       AArch64MCExpr::VK_AARCH64_SABS_G1,
530       AArch64MCExpr::VK_AARCH64_SABS_G2,
531       AArch64MCExpr::VK_AARCH64_DTPREL_G2,
532       AArch64MCExpr::VK_AARCH64_DTPREL_G1,
533       AArch64MCExpr::VK_AARCH64_DTPREL_G0,
534       AArch64MCExpr::VK_AARCH64_GOTTPREL_G1,
535       AArch64MCExpr::VK_AARCH64_TPREL_G2,
536       AArch64MCExpr::VK_AARCH64_TPREL_G1,
537       AArch64MCExpr::VK_AARCH64_TPREL_G0,
538     };
539     const unsigned NumModifiers = llvm::array_lengthof(PermittedModifiers);
540
541     return isMoveWideImm(64, PermittedModifiers, NumModifiers);
542   }
543
544   bool isMOVK32Imm() const {
545     static const AArch64MCExpr::VariantKind PermittedModifiers[] = {
546       AArch64MCExpr::VK_AARCH64_ABS_G0_NC,
547       AArch64MCExpr::VK_AARCH64_ABS_G1_NC,
548       AArch64MCExpr::VK_AARCH64_DTPREL_G1_NC,
549       AArch64MCExpr::VK_AARCH64_DTPREL_G0_NC,
550       AArch64MCExpr::VK_AARCH64_GOTTPREL_G0_NC,
551       AArch64MCExpr::VK_AARCH64_TPREL_G1_NC,
552       AArch64MCExpr::VK_AARCH64_TPREL_G0_NC,
553     };
554     const unsigned NumModifiers = llvm::array_lengthof(PermittedModifiers);
555
556     return isMoveWideImm(32, PermittedModifiers, NumModifiers);
557   }
558
559   bool isMOVK64Imm() const {
560     static const AArch64MCExpr::VariantKind PermittedModifiers[] = {
561       AArch64MCExpr::VK_AARCH64_ABS_G0_NC,
562       AArch64MCExpr::VK_AARCH64_ABS_G1_NC,
563       AArch64MCExpr::VK_AARCH64_ABS_G2_NC,
564       AArch64MCExpr::VK_AARCH64_ABS_G3,
565       AArch64MCExpr::VK_AARCH64_DTPREL_G1_NC,
566       AArch64MCExpr::VK_AARCH64_DTPREL_G0_NC,
567       AArch64MCExpr::VK_AARCH64_GOTTPREL_G0_NC,
568       AArch64MCExpr::VK_AARCH64_TPREL_G1_NC,
569       AArch64MCExpr::VK_AARCH64_TPREL_G0_NC,
570     };
571     const unsigned NumModifiers = llvm::array_lengthof(PermittedModifiers);
572
573     return isMoveWideImm(64, PermittedModifiers, NumModifiers);
574   }
575
576   bool isMoveWideImm(unsigned RegWidth,
577                      const AArch64MCExpr::VariantKind *PermittedModifiers,
578                      unsigned NumModifiers) const {
579     if (!isImmWithLSL()) return false;
580
581     if (ImmWithLSL.ShiftAmount % 16 != 0) return false;
582     if (ImmWithLSL.ShiftAmount >= RegWidth) return false;
583
584     AArch64MCExpr::VariantKind Modifier;
585     if (isNonConstantExpr(ImmWithLSL.Val, Modifier)) {
586       // E.g. "#:abs_g0:sym, lsl #16" makes no sense.
587       if (!ImmWithLSL.ImplicitAmount) return false;
588
589       for (unsigned i = 0; i < NumModifiers; ++i)
590         if (PermittedModifiers[i] == Modifier) return true;
591
592       return false;
593     }
594
595     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ImmWithLSL.Val);
596     return CE && CE->getValue() >= 0  && CE->getValue() <= 0xffff;
597   }
598
599   template<int RegWidth, bool (*isValidImm)(int, uint64_t, int&, int&)>
600   bool isMoveWideMovAlias() const {
601     if (!isImm()) return false;
602
603     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
604     if (!CE) return false;
605
606     int UImm16, Shift;
607     uint64_t Value = CE->getValue();
608
609     // If this is a 32-bit instruction then all bits above 32 should be the
610     // same: either of these is fine because signed/unsigned values should be
611     // permitted.
612     if (RegWidth == 32) {
613       if ((Value >> 32) != 0 && (Value >> 32) != 0xffffffff)
614         return false;
615
616       Value &= 0xffffffffULL;
617     }
618
619     return isValidImm(RegWidth, Value, UImm16, Shift);
620   }
621
622   bool isMSRWithReg() const {
623     if (!isSysReg()) return false;
624
625     bool IsKnownRegister;
626     StringRef Name(SysReg.Data, SysReg.Length);
627     A64SysReg::MSRMapper().fromString(Name, IsKnownRegister);
628
629     return IsKnownRegister;
630   }
631
632   bool isMSRPState() const {
633     if (!isSysReg()) return false;
634
635     bool IsKnownRegister;
636     StringRef Name(SysReg.Data, SysReg.Length);
637     A64PState::PStateMapper().fromString(Name, IsKnownRegister);
638
639     return IsKnownRegister;
640   }
641
642   bool isMRS() const {
643     if (!isSysReg()) return false;
644
645     // First check against specific MSR-only (write-only) registers
646     bool IsKnownRegister;
647     StringRef Name(SysReg.Data, SysReg.Length);
648     A64SysReg::MRSMapper().fromString(Name, IsKnownRegister);
649
650     return IsKnownRegister;
651   }
652
653   bool isPRFM() const {
654     if (!isImm()) return false;
655
656     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
657
658     if (!CE)
659       return false;
660
661     return CE->getValue() >= 0 && CE->getValue() <= 31;
662   }
663
664   template<A64SE::ShiftExtSpecifiers SHKind> bool isRegExtend() const {
665     if (!isShiftOrExtend()) return false;
666
667     if (ShiftExtend.ShiftType != SHKind)
668       return false;
669
670     return ShiftExtend.Amount <= 4;
671   }
672
673   bool isRegExtendLSL() const {
674     if (!isShiftOrExtend()) return false;
675
676     if (ShiftExtend.ShiftType != A64SE::LSL)
677       return false;
678
679     return !ShiftExtend.ImplicitAmount && ShiftExtend.Amount <= 4;
680   }
681
682   // if 0 < value <= w, return true
683   bool isShrFixedWidth(int w) const {
684     if (!isImm())
685       return false;
686     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
687     if (!CE)
688       return false;
689     int64_t Value = CE->getValue();
690     return Value > 0 && Value <= w;
691   }
692
693   bool isShrImm8() const { return isShrFixedWidth(8); }
694
695   bool isShrImm16() const { return isShrFixedWidth(16); }
696
697   bool isShrImm32() const { return isShrFixedWidth(32); }
698
699   bool isShrImm64() const { return isShrFixedWidth(64); }
700
701   // if 0 <= value < w, return true
702   bool isShlFixedWidth(int w) const {
703     if (!isImm())
704       return false;
705     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
706     if (!CE)
707       return false;
708     int64_t Value = CE->getValue();
709     return Value >= 0 && Value < w;
710   }
711
712   bool isShlImm8() const { return isShlFixedWidth(8); }
713
714   bool isShlImm16() const { return isShlFixedWidth(16); }
715
716   bool isShlImm32() const { return isShlFixedWidth(32); }
717
718   bool isShlImm64() const { return isShlFixedWidth(64); }
719
720   bool isNeonMovImmShiftLSL() const {
721     if (!isShiftOrExtend())
722       return false;
723
724     if (ShiftExtend.ShiftType != A64SE::LSL)
725       return false;
726
727     // Valid shift amount is 0, 8, 16 and 24.
728     return ShiftExtend.Amount % 8 == 0 && ShiftExtend.Amount <= 24;
729   }
730
731   bool isNeonMovImmShiftLSLH() const {
732     if (!isShiftOrExtend())
733       return false;
734
735     if (ShiftExtend.ShiftType != A64SE::LSL)
736       return false;
737
738     // Valid shift amount is 0 and 8.
739     return ShiftExtend.Amount == 0 || ShiftExtend.Amount == 8;
740   }
741
742   bool isNeonMovImmShiftMSL() const {
743     if (!isShiftOrExtend())
744       return false;
745
746     if (ShiftExtend.ShiftType != A64SE::MSL)
747       return false;
748
749     // Valid shift amount is 8 and 16.
750     return ShiftExtend.Amount == 8 || ShiftExtend.Amount == 16;
751   }
752
753   template <A64Layout::VectorLayout Layout, unsigned Count>
754   bool isVectorList() const {
755     return Kind == k_VectorList && VectorList.Layout == Layout &&
756            VectorList.Count == Count;
757   }
758
759   template <int MemSize> bool isSImm7Scaled() const {
760     if (!isImm())
761       return false;
762
763     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
764     if (!CE) return false;
765
766     int64_t Val = CE->getValue();
767     if (Val % MemSize != 0) return false;
768
769     Val /= MemSize;
770
771     return Val >= -64 && Val < 64;
772   }
773
774   template<int BitWidth>
775   bool isSImm() const {
776     if (!isImm()) return false;
777
778     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
779     if (!CE) return false;
780
781     return CE->getValue() >= -(1LL << (BitWidth - 1))
782       && CE->getValue() < (1LL << (BitWidth - 1));
783   }
784
785   template<int bitWidth>
786   bool isUImm() const {
787     if (!isImm()) return false;
788
789     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
790     if (!CE) return false;
791
792     return CE->getValue() >= 0 && CE->getValue() < (1LL << bitWidth);
793   }
794
795   bool isUImm() const {
796     if (!isImm()) return false;
797
798     return isa<MCConstantExpr>(getImm());
799   }
800
801   bool isNeonUImm64Mask() const {
802     if (!isImm())
803       return false;
804
805     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
806     if (!CE)
807       return false;
808
809     uint64_t Value = CE->getValue();
810
811     // i64 value with each byte being either 0x00 or 0xff.
812     for (unsigned i = 0; i < 8; ++i, Value >>= 8)
813       if ((Value & 0xff) != 0 && (Value & 0xff) != 0xff)
814         return false;
815     return true;
816   }
817
818   static AArch64Operand *CreateImmWithLSL(const MCExpr *Val,
819                                           unsigned ShiftAmount,
820                                           bool ImplicitAmount,
821                                                                                   SMLoc S,SMLoc E) {
822     AArch64Operand *Op = new AArch64Operand(k_ImmWithLSL, S, E);
823     Op->ImmWithLSL.Val = Val;
824     Op->ImmWithLSL.ShiftAmount = ShiftAmount;
825     Op->ImmWithLSL.ImplicitAmount = ImplicitAmount;
826     return Op;
827   }
828
829   static AArch64Operand *CreateCondCode(A64CC::CondCodes Code,
830                                         SMLoc S, SMLoc E) {
831     AArch64Operand *Op = new AArch64Operand(k_CondCode, S, E);
832     Op->CondCode.Code = Code;
833     return Op;
834   }
835
836   static AArch64Operand *CreateFPImm(double Val,
837                                      SMLoc S, SMLoc E) {
838     AArch64Operand *Op = new AArch64Operand(k_FPImmediate, S, E);
839     Op->FPImm.Val = Val;
840     return Op;
841   }
842
843   static AArch64Operand *CreateImm(const MCExpr *Val, SMLoc S, SMLoc E) {
844     AArch64Operand *Op = new AArch64Operand(k_Immediate, S, E);
845     Op->Imm.Val = Val;
846     return Op;
847   }
848
849   static AArch64Operand *CreateReg(unsigned RegNum, SMLoc S, SMLoc E) {
850     AArch64Operand *Op = new AArch64Operand(k_Register, S, E);
851     Op->Reg.RegNum = RegNum;
852     return Op;
853   }
854
855   static AArch64Operand *CreateWrappedReg(unsigned RegNum, SMLoc S, SMLoc E) {
856     AArch64Operand *Op = new AArch64Operand(k_WrappedRegister, S, E);
857     Op->Reg.RegNum = RegNum;
858     return Op;
859   }
860
861   static AArch64Operand *CreateShiftExtend(A64SE::ShiftExtSpecifiers ShiftTyp,
862                                            unsigned Amount,
863                                            bool ImplicitAmount,
864                                            SMLoc S, SMLoc E) {
865     AArch64Operand *Op = new AArch64Operand(k_ShiftExtend, S, E);
866     Op->ShiftExtend.ShiftType = ShiftTyp;
867     Op->ShiftExtend.Amount = Amount;
868     Op->ShiftExtend.ImplicitAmount = ImplicitAmount;
869     return Op;
870   }
871
872   static AArch64Operand *CreateSysReg(StringRef Str, SMLoc S) {
873     AArch64Operand *Op = new AArch64Operand(k_SysReg, S, S);
874     Op->Tok.Data = Str.data();
875     Op->Tok.Length = Str.size();
876     return Op;
877   }
878
879   static AArch64Operand *CreateVectorList(unsigned RegNum, unsigned Count,
880                                           A64Layout::VectorLayout Layout,
881                                           SMLoc S, SMLoc E) {
882     AArch64Operand *Op = new AArch64Operand(k_VectorList, S, E);
883     Op->VectorList.RegNum = RegNum;
884     Op->VectorList.Count = Count;
885     Op->VectorList.Layout = Layout;
886     Op->StartLoc = S;
887     Op->EndLoc = E;
888     return Op;
889   }
890
891   static AArch64Operand *CreateToken(StringRef Str, SMLoc S) {
892     AArch64Operand *Op = new AArch64Operand(k_Token, S, S);
893     Op->Tok.Data = Str.data();
894     Op->Tok.Length = Str.size();
895     return Op;
896   }
897
898
899   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
900     // Add as immediates when possible.
901     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
902       Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
903     else
904       Inst.addOperand(MCOperand::CreateExpr(Expr));
905   }
906
907   template<unsigned RegWidth>
908   void addBFILSBOperands(MCInst &Inst, unsigned N) const {
909     assert(N == 1 && "Invalid number of operands!");
910     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
911     unsigned EncodedVal = (RegWidth - CE->getValue()) % RegWidth;
912     Inst.addOperand(MCOperand::CreateImm(EncodedVal));
913   }
914
915   void addBFIWidthOperands(MCInst &Inst, unsigned N) const {
916     assert(N == 1 && "Invalid number of operands!");
917     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
918     Inst.addOperand(MCOperand::CreateImm(CE->getValue() - 1));
919   }
920
921   void addBFXWidthOperands(MCInst &Inst, unsigned N) const {
922     assert(N == 1 && "Invalid number of operands!");
923
924     uint64_t LSB = Inst.getOperand(Inst.getNumOperands()-1).getImm();
925     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
926
927     Inst.addOperand(MCOperand::CreateImm(LSB + CE->getValue() - 1));
928   }
929
930   void addCondCodeOperands(MCInst &Inst, unsigned N) const {
931     assert(N == 1 && "Invalid number of operands!");
932     Inst.addOperand(MCOperand::CreateImm(getCondCode()));
933   }
934
935   void addCVTFixedPosOperands(MCInst &Inst, unsigned N) const {
936     assert(N == 1 && "Invalid number of operands!");
937
938     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
939     Inst.addOperand(MCOperand::CreateImm(64 - CE->getValue()));
940   }
941
942   void addFMOVImmOperands(MCInst &Inst, unsigned N) const {
943     assert(N == 1 && "Invalid number of operands!");
944
945     APFloat RealVal(FPImm.Val);
946     uint32_t ImmVal;
947     A64Imms::isFPImm(RealVal, ImmVal);
948
949     Inst.addOperand(MCOperand::CreateImm(ImmVal));
950   }
951
952   void addFPZeroOperands(MCInst &Inst, unsigned N) const {
953     assert(N == 1 && "Invalid number of operands");
954     Inst.addOperand(MCOperand::CreateImm(0));
955   }
956
957   void addInvCondCodeOperands(MCInst &Inst, unsigned N) const {
958     assert(N == 1 && "Invalid number of operands!");
959     unsigned Encoded = A64InvertCondCode(getCondCode());
960     Inst.addOperand(MCOperand::CreateImm(Encoded));
961   }
962
963   void addRegOperands(MCInst &Inst, unsigned N) const {
964     assert(N == 1 && "Invalid number of operands!");
965     Inst.addOperand(MCOperand::CreateReg(getReg()));
966   }
967
968   void addImmOperands(MCInst &Inst, unsigned N) const {
969     assert(N == 1 && "Invalid number of operands!");
970     addExpr(Inst, getImm());
971   }
972
973   template<int MemSize>
974   void addSImm7ScaledOperands(MCInst &Inst, unsigned N) const {
975     assert(N == 1 && "Invalid number of operands!");
976
977     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
978     uint64_t Val = CE->getValue() / MemSize;
979     Inst.addOperand(MCOperand::CreateImm(Val  & 0x7f));
980   }
981
982   template<int BitWidth>
983   void addSImmOperands(MCInst &Inst, unsigned N) const {
984     assert(N == 1 && "Invalid number of operands!");
985
986     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
987     uint64_t Val = CE->getValue();
988     Inst.addOperand(MCOperand::CreateImm(Val  & ((1ULL << BitWidth) - 1)));
989   }
990
991   void addImmWithLSLOperands(MCInst &Inst, unsigned N) const {
992     assert (N == 1 && "Invalid number of operands!");
993
994     addExpr(Inst, ImmWithLSL.Val);
995   }
996
997   template<unsigned field_width, unsigned scale>
998   void addLabelOperands(MCInst &Inst, unsigned N) const {
999     assert(N == 1 && "Invalid number of operands!");
1000
1001     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val);
1002
1003     if (!CE) {
1004       addExpr(Inst, Imm.Val);
1005       return;
1006     }
1007
1008     int64_t Val = CE->getValue();
1009     assert(Val % scale == 0 && "Unaligned immediate in instruction");
1010     Val /= scale;
1011
1012     Inst.addOperand(MCOperand::CreateImm(Val & ((1LL << field_width) - 1)));
1013   }
1014
1015   template<int MemSize>
1016   void addOffsetUImm12Operands(MCInst &Inst, unsigned N) const {
1017     assert(N == 1 && "Invalid number of operands!");
1018
1019     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm())) {
1020       Inst.addOperand(MCOperand::CreateImm(CE->getValue() / MemSize));
1021     } else {
1022       Inst.addOperand(MCOperand::CreateExpr(getImm()));
1023     }
1024   }
1025
1026   template<unsigned RegWidth>
1027   void addLogicalImmOperands(MCInst &Inst, unsigned N) const {
1028     assert(N == 1 && "Invalid number of operands");
1029     const MCConstantExpr *CE = cast<MCConstantExpr>(Imm.Val);
1030
1031     uint32_t Bits;
1032     A64Imms::isLogicalImm(RegWidth, CE->getValue(), Bits);
1033
1034     Inst.addOperand(MCOperand::CreateImm(Bits));
1035   }
1036
1037   void addMRSOperands(MCInst &Inst, unsigned N) const {
1038     assert(N == 1 && "Invalid number of operands!");
1039
1040     bool Valid;
1041     StringRef Name(SysReg.Data, SysReg.Length);
1042     uint32_t Bits = A64SysReg::MRSMapper().fromString(Name, Valid);
1043
1044     Inst.addOperand(MCOperand::CreateImm(Bits));
1045   }
1046
1047   void addMSRWithRegOperands(MCInst &Inst, unsigned N) const {
1048     assert(N == 1 && "Invalid number of operands!");
1049
1050     bool Valid;
1051     StringRef Name(SysReg.Data, SysReg.Length);
1052     uint32_t Bits = A64SysReg::MSRMapper().fromString(Name, Valid);
1053
1054     Inst.addOperand(MCOperand::CreateImm(Bits));
1055   }
1056
1057   void addMSRPStateOperands(MCInst &Inst, unsigned N) const {
1058     assert(N == 1 && "Invalid number of operands!");
1059
1060     bool Valid;
1061     StringRef Name(SysReg.Data, SysReg.Length);
1062     uint32_t Bits = A64PState::PStateMapper().fromString(Name, Valid);
1063
1064     Inst.addOperand(MCOperand::CreateImm(Bits));
1065   }
1066
1067   void addMoveWideImmOperands(MCInst &Inst, unsigned N) const {
1068     assert(N == 2 && "Invalid number of operands!");
1069
1070     addExpr(Inst, ImmWithLSL.Val);
1071
1072     AArch64MCExpr::VariantKind Variant;
1073     if (!isNonConstantExpr(ImmWithLSL.Val, Variant)) {
1074       Inst.addOperand(MCOperand::CreateImm(ImmWithLSL.ShiftAmount / 16));
1075       return;
1076     }
1077
1078     // We know it's relocated
1079     switch (Variant) {
1080     case AArch64MCExpr::VK_AARCH64_ABS_G0:
1081     case AArch64MCExpr::VK_AARCH64_ABS_G0_NC:
1082     case AArch64MCExpr::VK_AARCH64_SABS_G0:
1083     case AArch64MCExpr::VK_AARCH64_DTPREL_G0:
1084     case AArch64MCExpr::VK_AARCH64_DTPREL_G0_NC:
1085     case AArch64MCExpr::VK_AARCH64_GOTTPREL_G0_NC:
1086     case AArch64MCExpr::VK_AARCH64_TPREL_G0:
1087     case AArch64MCExpr::VK_AARCH64_TPREL_G0_NC:
1088       Inst.addOperand(MCOperand::CreateImm(0));
1089       break;
1090     case AArch64MCExpr::VK_AARCH64_ABS_G1:
1091     case AArch64MCExpr::VK_AARCH64_ABS_G1_NC:
1092     case AArch64MCExpr::VK_AARCH64_SABS_G1:
1093     case AArch64MCExpr::VK_AARCH64_DTPREL_G1:
1094     case AArch64MCExpr::VK_AARCH64_DTPREL_G1_NC:
1095     case AArch64MCExpr::VK_AARCH64_GOTTPREL_G1:
1096     case AArch64MCExpr::VK_AARCH64_TPREL_G1:
1097     case AArch64MCExpr::VK_AARCH64_TPREL_G1_NC:
1098       Inst.addOperand(MCOperand::CreateImm(1));
1099       break;
1100     case AArch64MCExpr::VK_AARCH64_ABS_G2:
1101     case AArch64MCExpr::VK_AARCH64_ABS_G2_NC:
1102     case AArch64MCExpr::VK_AARCH64_SABS_G2:
1103     case AArch64MCExpr::VK_AARCH64_DTPREL_G2:
1104     case AArch64MCExpr::VK_AARCH64_TPREL_G2:
1105       Inst.addOperand(MCOperand::CreateImm(2));
1106       break;
1107     case AArch64MCExpr::VK_AARCH64_ABS_G3:
1108       Inst.addOperand(MCOperand::CreateImm(3));
1109       break;
1110     default: llvm_unreachable("Inappropriate move wide relocation");
1111     }
1112   }
1113
1114   template<int RegWidth, bool isValidImm(int, uint64_t, int&, int&)>
1115   void addMoveWideMovAliasOperands(MCInst &Inst, unsigned N) const {
1116     assert(N == 2 && "Invalid number of operands!");
1117     int UImm16, Shift;
1118
1119     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
1120     uint64_t Value = CE->getValue();
1121
1122     if (RegWidth == 32) {
1123       Value &= 0xffffffffULL;
1124     }
1125
1126     bool Valid = isValidImm(RegWidth, Value, UImm16, Shift);
1127     (void)Valid;
1128     assert(Valid && "Invalid immediates should have been weeded out by now");
1129
1130     Inst.addOperand(MCOperand::CreateImm(UImm16));
1131     Inst.addOperand(MCOperand::CreateImm(Shift));
1132   }
1133
1134   void addPRFMOperands(MCInst &Inst, unsigned N) const {
1135     assert(N == 1 && "Invalid number of operands!");
1136
1137     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
1138     assert(CE->getValue() >= 0 && CE->getValue() <= 31
1139            && "PRFM operand should be 5-bits");
1140
1141     Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
1142   }
1143
1144   // For Add-sub (extended register) operands.
1145   void addRegExtendOperands(MCInst &Inst, unsigned N) const {
1146     assert(N == 1 && "Invalid number of operands!");
1147
1148     Inst.addOperand(MCOperand::CreateImm(ShiftExtend.Amount));
1149   }
1150
1151   // For Vector Immediates shifted imm operands.
1152   void addNeonMovImmShiftLSLOperands(MCInst &Inst, unsigned N) const {
1153     assert(N == 1 && "Invalid number of operands!");
1154
1155     if (ShiftExtend.Amount % 8 != 0 || ShiftExtend.Amount > 24)
1156       llvm_unreachable("Invalid shift amount for vector immediate inst.");
1157
1158     // Encode LSL shift amount 0, 8, 16, 24 as 0, 1, 2, 3.
1159     int64_t Imm = ShiftExtend.Amount / 8;
1160     Inst.addOperand(MCOperand::CreateImm(Imm));
1161   }
1162
1163   void addNeonMovImmShiftLSLHOperands(MCInst &Inst, unsigned N) const {
1164     assert(N == 1 && "Invalid number of operands!");
1165
1166     if (ShiftExtend.Amount != 0 && ShiftExtend.Amount != 8)
1167       llvm_unreachable("Invalid shift amount for vector immediate inst.");
1168
1169     // Encode LSLH shift amount 0, 8  as 0, 1.
1170     int64_t Imm = ShiftExtend.Amount / 8;
1171     Inst.addOperand(MCOperand::CreateImm(Imm));
1172   }
1173
1174   void addNeonMovImmShiftMSLOperands(MCInst &Inst, unsigned N) const {
1175     assert(N == 1 && "Invalid number of operands!");
1176
1177     if (ShiftExtend.Amount != 8 && ShiftExtend.Amount != 16)
1178       llvm_unreachable("Invalid shift amount for vector immediate inst.");
1179
1180     // Encode MSL shift amount 8, 16  as 0, 1.
1181     int64_t Imm = ShiftExtend.Amount / 8 - 1;
1182     Inst.addOperand(MCOperand::CreateImm(Imm));
1183   }
1184
1185   // For the extend in load-store (register offset) instructions.
1186   template<unsigned MemSize>
1187   void addAddrRegExtendOperands(MCInst &Inst, unsigned N) const {
1188     addAddrRegExtendOperands(Inst, N, MemSize);
1189   }
1190
1191   void addAddrRegExtendOperands(MCInst &Inst, unsigned N,
1192                                 unsigned MemSize) const {
1193     assert(N == 1 && "Invalid number of operands!");
1194
1195     // First bit of Option is set in instruction classes, the high two bits are
1196     // as follows:
1197     unsigned OptionHi = 0;
1198     switch (ShiftExtend.ShiftType) {
1199     case A64SE::UXTW:
1200     case A64SE::LSL:
1201       OptionHi = 1;
1202       break;
1203     case A64SE::SXTW:
1204     case A64SE::SXTX:
1205       OptionHi = 3;
1206       break;
1207     default:
1208       llvm_unreachable("Invalid extend type for register offset");
1209     }
1210
1211     unsigned S = 0;
1212     if (MemSize == 1 && !ShiftExtend.ImplicitAmount)
1213       S = 1;
1214     else if (MemSize != 1 && ShiftExtend.Amount != 0)
1215       S = 1;
1216
1217     Inst.addOperand(MCOperand::CreateImm((OptionHi << 1) | S));
1218   }
1219   void addShiftOperands(MCInst &Inst, unsigned N) const {
1220     assert(N == 1 && "Invalid number of operands!");
1221
1222     Inst.addOperand(MCOperand::CreateImm(ShiftExtend.Amount));
1223   }
1224
1225   void addNeonUImm64MaskOperands(MCInst &Inst, unsigned N) const {
1226     assert(N == 1 && "Invalid number of operands!");
1227
1228     // A bit from each byte in the constant forms the encoded immediate
1229     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1230     uint64_t Value = CE->getValue();
1231
1232     unsigned Imm = 0;
1233     for (unsigned i = 0; i < 8; ++i, Value >>= 8) {
1234       Imm |= (Value & 1) << i;
1235     }
1236     Inst.addOperand(MCOperand::CreateImm(Imm));
1237   }
1238
1239   void addVectorListOperands(MCInst &Inst, unsigned N) const {
1240     assert(N == 1 && "Invalid number of operands!");
1241     Inst.addOperand(MCOperand::CreateReg(VectorList.RegNum));
1242   }
1243 };
1244
1245 } // end anonymous namespace.
1246
1247 AArch64AsmParser::OperandMatchResultTy
1248 AArch64AsmParser::ParseOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands,
1249                                StringRef Mnemonic) {
1250
1251   // See if the operand has a custom parser
1252   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
1253
1254   // It could either succeed, fail or just not care.
1255   if (ResTy != MatchOperand_NoMatch)
1256     return ResTy;
1257
1258   switch (getLexer().getKind()) {
1259   default:
1260     Error(Parser.getTok().getLoc(), "unexpected token in operand");
1261     return MatchOperand_ParseFail;
1262   case AsmToken::Identifier: {
1263     // It might be in the LSL/UXTB family ...
1264     OperandMatchResultTy GotShift = ParseShiftExtend(Operands);
1265
1266     // We can only continue if no tokens were eaten.
1267     if (GotShift != MatchOperand_NoMatch)
1268       return GotShift;
1269
1270     // ... or it might be a register ...
1271     uint32_t NumLanes = 0;
1272     OperandMatchResultTy GotReg = ParseRegister(Operands, NumLanes);
1273     assert(GotReg != MatchOperand_ParseFail
1274            && "register parsing shouldn't partially succeed");
1275
1276     if (GotReg == MatchOperand_Success) {
1277       if (Parser.getTok().is(AsmToken::LBrac))
1278         return ParseNEONLane(Operands, NumLanes);
1279       else
1280         return MatchOperand_Success;
1281     }
1282     // ... or it might be a symbolish thing
1283   }
1284     // Fall through
1285   case AsmToken::LParen:  // E.g. (strcmp-4)
1286   case AsmToken::Integer: // 1f, 2b labels
1287   case AsmToken::String:  // quoted labels
1288   case AsmToken::Dot:     // . is Current location
1289   case AsmToken::Dollar:  // $ is PC
1290   case AsmToken::Colon: {
1291     SMLoc StartLoc  = Parser.getTok().getLoc();
1292     SMLoc EndLoc;
1293     const MCExpr *ImmVal = 0;
1294
1295     if (ParseImmediate(ImmVal) != MatchOperand_Success)
1296       return MatchOperand_ParseFail;
1297
1298     EndLoc = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1299     Operands.push_back(AArch64Operand::CreateImm(ImmVal, StartLoc, EndLoc));
1300     return MatchOperand_Success;
1301   }
1302   case AsmToken::Hash: {   // Immediates
1303     SMLoc StartLoc = Parser.getTok().getLoc();
1304     SMLoc EndLoc;
1305     const MCExpr *ImmVal = 0;
1306     Parser.Lex();
1307
1308     if (ParseImmediate(ImmVal) != MatchOperand_Success)
1309       return MatchOperand_ParseFail;
1310
1311     EndLoc = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1312     Operands.push_back(AArch64Operand::CreateImm(ImmVal, StartLoc, EndLoc));
1313     return MatchOperand_Success;
1314   }
1315   case AsmToken::LBrac: {
1316     SMLoc Loc = Parser.getTok().getLoc();
1317     Operands.push_back(AArch64Operand::CreateToken("[", Loc));
1318     Parser.Lex(); // Eat '['
1319
1320     // There's no comma after a '[', so we can parse the next operand
1321     // immediately.
1322     return ParseOperand(Operands, Mnemonic);
1323   }
1324   // The following will likely be useful later, but not in very early cases
1325   case AsmToken::LCurly: // SIMD vector list is not parsed here
1326     llvm_unreachable("Don't know how to deal with '{' in operand");
1327     return MatchOperand_ParseFail;
1328   }
1329 }
1330
1331 AArch64AsmParser::OperandMatchResultTy
1332 AArch64AsmParser::ParseImmediate(const MCExpr *&ExprVal) {
1333   if (getLexer().is(AsmToken::Colon)) {
1334     AArch64MCExpr::VariantKind RefKind;
1335
1336     OperandMatchResultTy ResTy = ParseRelocPrefix(RefKind);
1337     if (ResTy != MatchOperand_Success)
1338       return ResTy;
1339
1340     const MCExpr *SubExprVal;
1341     if (getParser().parseExpression(SubExprVal))
1342       return MatchOperand_ParseFail;
1343
1344     ExprVal = AArch64MCExpr::Create(RefKind, SubExprVal, getContext());
1345     return MatchOperand_Success;
1346   }
1347
1348   // No weird AArch64MCExpr prefix
1349   return getParser().parseExpression(ExprVal)
1350     ? MatchOperand_ParseFail : MatchOperand_Success;
1351 }
1352
1353 // A lane attached to a NEON register. "[N]", which should yield three tokens:
1354 // '[', N, ']'. A hash is not allowed to precede the immediate here.
1355 AArch64AsmParser::OperandMatchResultTy
1356 AArch64AsmParser::ParseNEONLane(SmallVectorImpl<MCParsedAsmOperand*> &Operands,
1357                                 uint32_t NumLanes) {
1358   SMLoc Loc = Parser.getTok().getLoc();
1359
1360   assert(Parser.getTok().is(AsmToken::LBrac) && "inappropriate operand");
1361   Operands.push_back(AArch64Operand::CreateToken("[", Loc));
1362   Parser.Lex(); // Eat '['
1363
1364   if (Parser.getTok().isNot(AsmToken::Integer)) {
1365     Error(Parser.getTok().getLoc(), "expected lane number");
1366     return MatchOperand_ParseFail;
1367   }
1368
1369   if (Parser.getTok().getIntVal() >= NumLanes) {
1370     Error(Parser.getTok().getLoc(), "lane number incompatible with layout");
1371     return MatchOperand_ParseFail;
1372   }
1373
1374   const MCExpr *Lane = MCConstantExpr::Create(Parser.getTok().getIntVal(),
1375                                               getContext());
1376   SMLoc S = Parser.getTok().getLoc();
1377   Parser.Lex(); // Eat actual lane
1378   SMLoc E = Parser.getTok().getLoc();
1379   Operands.push_back(AArch64Operand::CreateImm(Lane, S, E));
1380
1381
1382   if (Parser.getTok().isNot(AsmToken::RBrac)) {
1383     Error(Parser.getTok().getLoc(), "expected ']' after lane");
1384     return MatchOperand_ParseFail;
1385   }
1386
1387   Operands.push_back(AArch64Operand::CreateToken("]", Loc));
1388   Parser.Lex(); // Eat ']'
1389
1390   return MatchOperand_Success;
1391 }
1392
1393 AArch64AsmParser::OperandMatchResultTy
1394 AArch64AsmParser::ParseRelocPrefix(AArch64MCExpr::VariantKind &RefKind) {
1395   assert(getLexer().is(AsmToken::Colon) && "expected a ':'");
1396   Parser.Lex();
1397
1398   if (getLexer().isNot(AsmToken::Identifier)) {
1399     Error(Parser.getTok().getLoc(),
1400           "expected relocation specifier in operand after ':'");
1401     return MatchOperand_ParseFail;
1402   }
1403
1404   std::string LowerCase = Parser.getTok().getIdentifier().lower();
1405   RefKind = StringSwitch<AArch64MCExpr::VariantKind>(LowerCase)
1406     .Case("got",              AArch64MCExpr::VK_AARCH64_GOT)
1407     .Case("got_lo12",         AArch64MCExpr::VK_AARCH64_GOT_LO12)
1408     .Case("lo12",             AArch64MCExpr::VK_AARCH64_LO12)
1409     .Case("abs_g0",           AArch64MCExpr::VK_AARCH64_ABS_G0)
1410     .Case("abs_g0_nc",        AArch64MCExpr::VK_AARCH64_ABS_G0_NC)
1411     .Case("abs_g1",           AArch64MCExpr::VK_AARCH64_ABS_G1)
1412     .Case("abs_g1_nc",        AArch64MCExpr::VK_AARCH64_ABS_G1_NC)
1413     .Case("abs_g2",           AArch64MCExpr::VK_AARCH64_ABS_G2)
1414     .Case("abs_g2_nc",        AArch64MCExpr::VK_AARCH64_ABS_G2_NC)
1415     .Case("abs_g3",           AArch64MCExpr::VK_AARCH64_ABS_G3)
1416     .Case("abs_g0_s",         AArch64MCExpr::VK_AARCH64_SABS_G0)
1417     .Case("abs_g1_s",         AArch64MCExpr::VK_AARCH64_SABS_G1)
1418     .Case("abs_g2_s",         AArch64MCExpr::VK_AARCH64_SABS_G2)
1419     .Case("dtprel_g2",        AArch64MCExpr::VK_AARCH64_DTPREL_G2)
1420     .Case("dtprel_g1",        AArch64MCExpr::VK_AARCH64_DTPREL_G1)
1421     .Case("dtprel_g1_nc",     AArch64MCExpr::VK_AARCH64_DTPREL_G1_NC)
1422     .Case("dtprel_g0",        AArch64MCExpr::VK_AARCH64_DTPREL_G0)
1423     .Case("dtprel_g0_nc",     AArch64MCExpr::VK_AARCH64_DTPREL_G0_NC)
1424     .Case("dtprel_hi12",      AArch64MCExpr::VK_AARCH64_DTPREL_HI12)
1425     .Case("dtprel_lo12",      AArch64MCExpr::VK_AARCH64_DTPREL_LO12)
1426     .Case("dtprel_lo12_nc",   AArch64MCExpr::VK_AARCH64_DTPREL_LO12_NC)
1427     .Case("gottprel_g1",      AArch64MCExpr::VK_AARCH64_GOTTPREL_G1)
1428     .Case("gottprel_g0_nc",   AArch64MCExpr::VK_AARCH64_GOTTPREL_G0_NC)
1429     .Case("gottprel",         AArch64MCExpr::VK_AARCH64_GOTTPREL)
1430     .Case("gottprel_lo12",    AArch64MCExpr::VK_AARCH64_GOTTPREL_LO12)
1431     .Case("tprel_g2",         AArch64MCExpr::VK_AARCH64_TPREL_G2)
1432     .Case("tprel_g1",         AArch64MCExpr::VK_AARCH64_TPREL_G1)
1433     .Case("tprel_g1_nc",      AArch64MCExpr::VK_AARCH64_TPREL_G1_NC)
1434     .Case("tprel_g0",         AArch64MCExpr::VK_AARCH64_TPREL_G0)
1435     .Case("tprel_g0_nc",      AArch64MCExpr::VK_AARCH64_TPREL_G0_NC)
1436     .Case("tprel_hi12",       AArch64MCExpr::VK_AARCH64_TPREL_HI12)
1437     .Case("tprel_lo12",       AArch64MCExpr::VK_AARCH64_TPREL_LO12)
1438     .Case("tprel_lo12_nc",    AArch64MCExpr::VK_AARCH64_TPREL_LO12_NC)
1439     .Case("tlsdesc",          AArch64MCExpr::VK_AARCH64_TLSDESC)
1440     .Case("tlsdesc_lo12",     AArch64MCExpr::VK_AARCH64_TLSDESC_LO12)
1441     .Default(AArch64MCExpr::VK_AARCH64_None);
1442
1443   if (RefKind == AArch64MCExpr::VK_AARCH64_None) {
1444     Error(Parser.getTok().getLoc(),
1445           "expected relocation specifier in operand after ':'");
1446     return MatchOperand_ParseFail;
1447   }
1448   Parser.Lex(); // Eat identifier
1449
1450   if (getLexer().isNot(AsmToken::Colon)) {
1451     Error(Parser.getTok().getLoc(),
1452           "expected ':' after relocation specifier");
1453     return MatchOperand_ParseFail;
1454   }
1455   Parser.Lex();
1456   return MatchOperand_Success;
1457 }
1458
1459 AArch64AsmParser::OperandMatchResultTy
1460 AArch64AsmParser::ParseImmWithLSLOperand(
1461                                SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1462   // FIXME?: I want to live in a world where immediates must start with
1463   // #. Please don't dash my hopes (well, do if you have a good reason).
1464   if (Parser.getTok().isNot(AsmToken::Hash)) return MatchOperand_NoMatch;
1465
1466   SMLoc S = Parser.getTok().getLoc();
1467   Parser.Lex(); // Eat '#'
1468
1469   const MCExpr *Imm;
1470   if (ParseImmediate(Imm) != MatchOperand_Success)
1471     return MatchOperand_ParseFail;
1472   else if (Parser.getTok().isNot(AsmToken::Comma)) {
1473     SMLoc E = Parser.getTok().getLoc();
1474     Operands.push_back(AArch64Operand::CreateImmWithLSL(Imm, 0, true, S, E));
1475     return MatchOperand_Success;
1476   }
1477
1478   // Eat ','
1479   Parser.Lex();
1480
1481   // The optional operand must be "lsl #N" where N is non-negative.
1482   if (Parser.getTok().is(AsmToken::Identifier)
1483       && Parser.getTok().getIdentifier().lower() == "lsl") {
1484     Parser.Lex();
1485
1486     if (Parser.getTok().is(AsmToken::Hash)) {
1487       Parser.Lex();
1488
1489       if (Parser.getTok().isNot(AsmToken::Integer)) {
1490         Error(Parser.getTok().getLoc(), "only 'lsl #+N' valid after immediate");
1491         return MatchOperand_ParseFail;
1492       }
1493     }
1494   }
1495
1496   int64_t ShiftAmount = Parser.getTok().getIntVal();
1497
1498   if (ShiftAmount < 0) {
1499     Error(Parser.getTok().getLoc(), "positive shift amount required");
1500     return MatchOperand_ParseFail;
1501   }
1502   Parser.Lex(); // Eat the number
1503
1504   SMLoc E = Parser.getTok().getLoc();
1505   Operands.push_back(AArch64Operand::CreateImmWithLSL(Imm, ShiftAmount,
1506                                                       false, S, E));
1507   return MatchOperand_Success;
1508 }
1509
1510
1511 AArch64AsmParser::OperandMatchResultTy
1512 AArch64AsmParser::ParseCondCodeOperand(
1513                                SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1514   if (Parser.getTok().isNot(AsmToken::Identifier))
1515     return MatchOperand_NoMatch;
1516
1517   StringRef Tok = Parser.getTok().getIdentifier();
1518   A64CC::CondCodes CondCode = A64StringToCondCode(Tok);
1519
1520   if (CondCode == A64CC::Invalid)
1521     return MatchOperand_NoMatch;
1522
1523   SMLoc S = Parser.getTok().getLoc();
1524   Parser.Lex(); // Eat condition code
1525   SMLoc E = Parser.getTok().getLoc();
1526
1527   Operands.push_back(AArch64Operand::CreateCondCode(CondCode, S, E));
1528   return MatchOperand_Success;
1529 }
1530
1531 AArch64AsmParser::OperandMatchResultTy
1532 AArch64AsmParser::ParseCRxOperand(
1533                                SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1534   SMLoc S = Parser.getTok().getLoc();
1535   if (Parser.getTok().isNot(AsmToken::Identifier)) {
1536     Error(S, "Expected cN operand where 0 <= N <= 15");
1537     return MatchOperand_ParseFail;
1538   }
1539
1540   std::string LowerTok = Parser.getTok().getIdentifier().lower();
1541   StringRef Tok(LowerTok);
1542   if (Tok[0] != 'c') {
1543     Error(S, "Expected cN operand where 0 <= N <= 15");
1544     return MatchOperand_ParseFail;
1545   }
1546
1547   uint32_t CRNum;
1548   bool BadNum = Tok.drop_front().getAsInteger(10, CRNum);
1549   if (BadNum || CRNum > 15) {
1550     Error(S, "Expected cN operand where 0 <= N <= 15");
1551     return MatchOperand_ParseFail;
1552   }
1553
1554   const MCExpr *CRImm = MCConstantExpr::Create(CRNum, getContext());
1555
1556   Parser.Lex();
1557   SMLoc E = Parser.getTok().getLoc();
1558
1559   Operands.push_back(AArch64Operand::CreateImm(CRImm, S, E));
1560   return MatchOperand_Success;
1561 }
1562
1563 AArch64AsmParser::OperandMatchResultTy
1564 AArch64AsmParser::ParseFPImmOperand(
1565                                SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1566
1567   // FIXME?: I want to live in a world where immediates must start with
1568   // #. Please don't dash my hopes (well, do if you have a good reason).
1569   if (Parser.getTok().isNot(AsmToken::Hash)) return MatchOperand_NoMatch;
1570
1571   SMLoc S = Parser.getTok().getLoc();
1572   Parser.Lex(); // Eat '#'
1573
1574   bool Negative = false;
1575   if (Parser.getTok().is(AsmToken::Minus)) {
1576     Negative = true;
1577     Parser.Lex(); // Eat '-'
1578   } else if (Parser.getTok().is(AsmToken::Plus)) {
1579     Parser.Lex(); // Eat '+'
1580   }
1581
1582   if (Parser.getTok().isNot(AsmToken::Real)) {
1583     Error(S, "Expected floating-point immediate");
1584     return MatchOperand_ParseFail;
1585   }
1586
1587   APFloat RealVal(APFloat::IEEEdouble, Parser.getTok().getString());
1588   if (Negative) RealVal.changeSign();
1589   double DblVal = RealVal.convertToDouble();
1590
1591   Parser.Lex(); // Eat real number
1592   SMLoc E = Parser.getTok().getLoc();
1593
1594   Operands.push_back(AArch64Operand::CreateFPImm(DblVal, S, E));
1595   return MatchOperand_Success;
1596 }
1597
1598
1599 // Automatically generated
1600 static unsigned MatchRegisterName(StringRef Name);
1601
1602 bool
1603 AArch64AsmParser::IdentifyRegister(unsigned &RegNum, SMLoc &RegEndLoc,
1604                                    StringRef &Layout,
1605                                    SMLoc &LayoutLoc) const {
1606   const AsmToken &Tok = Parser.getTok();
1607
1608   if (Tok.isNot(AsmToken::Identifier))
1609     return false;
1610
1611   std::string LowerReg = Tok.getString().lower();
1612   size_t DotPos = LowerReg.find('.');
1613
1614   bool IsVec128 = false;
1615   SMLoc S = Tok.getLoc();
1616   RegEndLoc = SMLoc::getFromPointer(S.getPointer() + DotPos);
1617
1618   if (DotPos == std::string::npos) {
1619     Layout = StringRef();
1620   } else {
1621     // Everything afterwards needs to be a literal token, expected to be
1622     // '.2d','.b' etc for vector registers.
1623
1624     // This StringSwitch validates the input and (perhaps more importantly)
1625     // gives us a permanent string to use in the token (a pointer into LowerReg
1626     // would go out of scope when we return).
1627     LayoutLoc = SMLoc::getFromPointer(S.getPointer() + DotPos + 1);
1628     std::string LayoutText = LowerReg.substr(DotPos, StringRef::npos);
1629
1630     // See if it's a 128-bit layout first.
1631     Layout = StringSwitch<const char *>(LayoutText)
1632       .Case(".d", ".d").Case(".2d", ".2d")
1633       .Case(".s", ".s").Case(".4s", ".4s")
1634       .Case(".h", ".h").Case(".8h", ".8h")
1635       .Case(".b", ".b").Case(".16b", ".16b")
1636       .Default("");
1637
1638     if (Layout.size() != 0)
1639       IsVec128 = true;
1640     else {
1641       Layout = StringSwitch<const char *>(LayoutText)
1642                    .Case(".1d", ".1d")
1643                    .Case(".2s", ".2s")
1644                    .Case(".4h", ".4h")
1645                    .Case(".8b", ".8b")
1646                    .Default("");
1647     }
1648
1649     if (Layout.size() == 0) {
1650       // If we've still not pinned it down the register is malformed.
1651       return false;
1652     }
1653   }
1654
1655   RegNum = MatchRegisterName(LowerReg.substr(0, DotPos));
1656   if (RegNum == AArch64::NoRegister) {
1657     RegNum = StringSwitch<unsigned>(LowerReg.substr(0, DotPos))
1658       .Case("ip0", AArch64::X16)
1659       .Case("ip1", AArch64::X17)
1660       .Case("fp", AArch64::X29)
1661       .Case("lr", AArch64::X30)
1662       .Case("v0", IsVec128 ? AArch64::Q0 : AArch64::D0)
1663       .Case("v1", IsVec128 ? AArch64::Q1 : AArch64::D1)
1664       .Case("v2", IsVec128 ? AArch64::Q2 : AArch64::D2)
1665       .Case("v3", IsVec128 ? AArch64::Q3 : AArch64::D3)
1666       .Case("v4", IsVec128 ? AArch64::Q4 : AArch64::D4)
1667       .Case("v5", IsVec128 ? AArch64::Q5 : AArch64::D5)
1668       .Case("v6", IsVec128 ? AArch64::Q6 : AArch64::D6)
1669       .Case("v7", IsVec128 ? AArch64::Q7 : AArch64::D7)
1670       .Case("v8", IsVec128 ? AArch64::Q8 : AArch64::D8)
1671       .Case("v9", IsVec128 ? AArch64::Q9 : AArch64::D9)
1672       .Case("v10", IsVec128 ? AArch64::Q10 : AArch64::D10)
1673       .Case("v11", IsVec128 ? AArch64::Q11 : AArch64::D11)
1674       .Case("v12", IsVec128 ? AArch64::Q12 : AArch64::D12)
1675       .Case("v13", IsVec128 ? AArch64::Q13 : AArch64::D13)
1676       .Case("v14", IsVec128 ? AArch64::Q14 : AArch64::D14)
1677       .Case("v15", IsVec128 ? AArch64::Q15 : AArch64::D15)
1678       .Case("v16", IsVec128 ? AArch64::Q16 : AArch64::D16)
1679       .Case("v17", IsVec128 ? AArch64::Q17 : AArch64::D17)
1680       .Case("v18", IsVec128 ? AArch64::Q18 : AArch64::D18)
1681       .Case("v19", IsVec128 ? AArch64::Q19 : AArch64::D19)
1682       .Case("v20", IsVec128 ? AArch64::Q20 : AArch64::D20)
1683       .Case("v21", IsVec128 ? AArch64::Q21 : AArch64::D21)
1684       .Case("v22", IsVec128 ? AArch64::Q22 : AArch64::D22)
1685       .Case("v23", IsVec128 ? AArch64::Q23 : AArch64::D23)
1686       .Case("v24", IsVec128 ? AArch64::Q24 : AArch64::D24)
1687       .Case("v25", IsVec128 ? AArch64::Q25 : AArch64::D25)
1688       .Case("v26", IsVec128 ? AArch64::Q26 : AArch64::D26)
1689       .Case("v27", IsVec128 ? AArch64::Q27 : AArch64::D27)
1690       .Case("v28", IsVec128 ? AArch64::Q28 : AArch64::D28)
1691       .Case("v29", IsVec128 ? AArch64::Q29 : AArch64::D29)
1692       .Case("v30", IsVec128 ? AArch64::Q30 : AArch64::D30)
1693       .Case("v31", IsVec128 ? AArch64::Q31 : AArch64::D31)
1694       .Default(AArch64::NoRegister);
1695   }
1696   if (RegNum == AArch64::NoRegister)
1697     return false;
1698
1699   return true;
1700 }
1701
1702 AArch64AsmParser::OperandMatchResultTy
1703 AArch64AsmParser::ParseRegister(SmallVectorImpl<MCParsedAsmOperand*> &Operands,
1704                                 uint32_t &NumLanes) {
1705   unsigned RegNum;
1706   StringRef Layout;
1707   SMLoc RegEndLoc, LayoutLoc;
1708   SMLoc S = Parser.getTok().getLoc();
1709
1710   if (!IdentifyRegister(RegNum, RegEndLoc, Layout, LayoutLoc))
1711     return MatchOperand_NoMatch;
1712
1713   Operands.push_back(AArch64Operand::CreateReg(RegNum, S, RegEndLoc));
1714
1715   if (Layout.size() != 0) {
1716     unsigned long long TmpLanes = 0;
1717     llvm::getAsUnsignedInteger(Layout.substr(1), 10, TmpLanes);
1718     if (TmpLanes != 0) {
1719       NumLanes = TmpLanes;
1720     } else {
1721       // If the number of lanes isn't specified explicitly, a valid instruction
1722       // will have an element specifier and be capable of acting on the entire
1723       // vector register.
1724       switch (Layout.back()) {
1725       default: llvm_unreachable("Invalid layout specifier");
1726       case 'b': NumLanes = 16; break;
1727       case 'h': NumLanes = 8; break;
1728       case 's': NumLanes = 4; break;
1729       case 'd': NumLanes = 2; break;
1730       }
1731     }
1732
1733     Operands.push_back(AArch64Operand::CreateToken(Layout, LayoutLoc));
1734   }
1735
1736   Parser.Lex();
1737   return MatchOperand_Success;
1738 }
1739
1740 bool
1741 AArch64AsmParser::ParseRegister(unsigned &RegNo, SMLoc &StartLoc,
1742                                 SMLoc &EndLoc) {
1743   // This callback is used for things like DWARF frame directives in
1744   // assembly. They don't care about things like NEON layouts or lanes, they
1745   // just want to be able to produce the DWARF register number.
1746   StringRef LayoutSpec;
1747   SMLoc RegEndLoc, LayoutLoc;
1748   StartLoc = Parser.getTok().getLoc();
1749
1750   if (!IdentifyRegister(RegNo, RegEndLoc, LayoutSpec, LayoutLoc))
1751     return true;
1752
1753   Parser.Lex();
1754   EndLoc = Parser.getTok().getLoc();
1755
1756   return false;
1757 }
1758
1759 AArch64AsmParser::OperandMatchResultTy
1760 AArch64AsmParser::ParseNamedImmOperand(const NamedImmMapper &Mapper,
1761                                SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1762   // Since these operands occur in very limited circumstances, without
1763   // alternatives, we actually signal an error if there is no match. If relaxing
1764   // this, beware of unintended consequences: an immediate will be accepted
1765   // during matching, no matter how it gets into the AArch64Operand.
1766   const AsmToken &Tok = Parser.getTok();
1767   SMLoc S = Tok.getLoc();
1768
1769   if (Tok.is(AsmToken::Identifier)) {
1770     bool ValidName;
1771     uint32_t Code = Mapper.fromString(Tok.getString().lower(), ValidName);
1772
1773     if (!ValidName) {
1774       Error(S, "operand specifier not recognised");
1775       return MatchOperand_ParseFail;
1776     }
1777
1778     Parser.Lex(); // We're done with the identifier. Eat it
1779
1780     SMLoc E = Parser.getTok().getLoc();
1781     const MCExpr *Imm = MCConstantExpr::Create(Code, getContext());
1782     Operands.push_back(AArch64Operand::CreateImm(Imm, S, E));
1783     return MatchOperand_Success;
1784   } else if (Tok.is(AsmToken::Hash)) {
1785     Parser.Lex();
1786
1787     const MCExpr *ImmVal;
1788     if (ParseImmediate(ImmVal) != MatchOperand_Success)
1789       return MatchOperand_ParseFail;
1790
1791     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ImmVal);
1792     if (!CE || CE->getValue() < 0 || !Mapper.validImm(CE->getValue())) {
1793       Error(S, "Invalid immediate for instruction");
1794       return MatchOperand_ParseFail;
1795     }
1796
1797     SMLoc E = Parser.getTok().getLoc();
1798     Operands.push_back(AArch64Operand::CreateImm(ImmVal, S, E));
1799     return MatchOperand_Success;
1800   }
1801
1802   Error(S, "unexpected operand for instruction");
1803   return MatchOperand_ParseFail;
1804 }
1805
1806 AArch64AsmParser::OperandMatchResultTy
1807 AArch64AsmParser::ParseSysRegOperand(
1808                                SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1809   const AsmToken &Tok = Parser.getTok();
1810
1811   // Any MSR/MRS operand will be an identifier, and we want to store it as some
1812   // kind of string: SPSel is valid for two different forms of MSR with two
1813   // different encodings. There's no collision at the moment, but the potential
1814   // is there.
1815   if (!Tok.is(AsmToken::Identifier)) {
1816     return MatchOperand_NoMatch;
1817   }
1818
1819   SMLoc S = Tok.getLoc();
1820   Operands.push_back(AArch64Operand::CreateSysReg(Tok.getString(), S));
1821   Parser.Lex(); // Eat identifier
1822
1823   return MatchOperand_Success;
1824 }
1825
1826 AArch64AsmParser::OperandMatchResultTy
1827 AArch64AsmParser::ParseLSXAddressOperand(
1828                                SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1829   SMLoc S = Parser.getTok().getLoc();
1830
1831   unsigned RegNum;
1832   SMLoc RegEndLoc, LayoutLoc;
1833   StringRef Layout;
1834   if(!IdentifyRegister(RegNum, RegEndLoc, Layout, LayoutLoc)
1835      || !AArch64MCRegisterClasses[AArch64::GPR64xspRegClassID].contains(RegNum)
1836      || Layout.size() != 0) {
1837     // Check Layout.size because we don't want to let "x3.4s" or similar
1838     // through.
1839     return MatchOperand_NoMatch;
1840   }
1841   Parser.Lex(); // Eat register
1842
1843   if (Parser.getTok().is(AsmToken::RBrac)) {
1844     // We're done
1845     SMLoc E = Parser.getTok().getLoc();
1846     Operands.push_back(AArch64Operand::CreateWrappedReg(RegNum, S, E));
1847     return MatchOperand_Success;
1848   }
1849
1850   // Otherwise, only ", #0" is valid
1851
1852   if (Parser.getTok().isNot(AsmToken::Comma)) {
1853     Error(Parser.getTok().getLoc(), "expected ',' or ']' after register");
1854     return MatchOperand_ParseFail;
1855   }
1856   Parser.Lex(); // Eat ','
1857
1858   if (Parser.getTok().isNot(AsmToken::Hash)) {
1859     Error(Parser.getTok().getLoc(), "expected '#0'");
1860     return MatchOperand_ParseFail;
1861   }
1862   Parser.Lex(); // Eat '#'
1863
1864   if (Parser.getTok().isNot(AsmToken::Integer)
1865       || Parser.getTok().getIntVal() != 0 ) {
1866     Error(Parser.getTok().getLoc(), "expected '#0'");
1867     return MatchOperand_ParseFail;
1868   }
1869   Parser.Lex(); // Eat '0'
1870
1871   SMLoc E = Parser.getTok().getLoc();
1872   Operands.push_back(AArch64Operand::CreateWrappedReg(RegNum, S, E));
1873   return MatchOperand_Success;
1874 }
1875
1876 AArch64AsmParser::OperandMatchResultTy
1877 AArch64AsmParser::ParseShiftExtend(
1878                                SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1879   StringRef IDVal = Parser.getTok().getIdentifier();
1880   std::string LowerID = IDVal.lower();
1881
1882   A64SE::ShiftExtSpecifiers Spec =
1883       StringSwitch<A64SE::ShiftExtSpecifiers>(LowerID)
1884         .Case("lsl", A64SE::LSL)
1885         .Case("msl", A64SE::MSL)
1886         .Case("lsr", A64SE::LSR)
1887         .Case("asr", A64SE::ASR)
1888         .Case("ror", A64SE::ROR)
1889         .Case("uxtb", A64SE::UXTB)
1890         .Case("uxth", A64SE::UXTH)
1891         .Case("uxtw", A64SE::UXTW)
1892         .Case("uxtx", A64SE::UXTX)
1893         .Case("sxtb", A64SE::SXTB)
1894         .Case("sxth", A64SE::SXTH)
1895         .Case("sxtw", A64SE::SXTW)
1896         .Case("sxtx", A64SE::SXTX)
1897         .Default(A64SE::Invalid);
1898
1899   if (Spec == A64SE::Invalid)
1900     return MatchOperand_NoMatch;
1901
1902   // Eat the shift
1903   SMLoc S, E;
1904   S = Parser.getTok().getLoc();
1905   Parser.Lex();
1906
1907   if (Spec != A64SE::LSL && Spec != A64SE::LSR && Spec != A64SE::ASR &&
1908       Spec != A64SE::ROR && Spec != A64SE::MSL) {
1909     // The shift amount can be omitted for the extending versions, but not real
1910     // shifts:
1911     //     add x0, x0, x0, uxtb
1912     // is valid, and equivalent to
1913     //     add x0, x0, x0, uxtb #0
1914
1915     if (Parser.getTok().is(AsmToken::Comma) ||
1916         Parser.getTok().is(AsmToken::EndOfStatement) ||
1917         Parser.getTok().is(AsmToken::RBrac)) {
1918       Operands.push_back(AArch64Operand::CreateShiftExtend(Spec, 0, true,
1919                                                            S, E));
1920       return MatchOperand_Success;
1921     }
1922   }
1923
1924   // Eat # at beginning of immediate
1925   if (!Parser.getTok().is(AsmToken::Hash)) {
1926     Error(Parser.getTok().getLoc(),
1927           "expected #imm after shift specifier");
1928     return MatchOperand_ParseFail;
1929   }
1930   Parser.Lex();
1931
1932   // Make sure we do actually have a number
1933   if (!Parser.getTok().is(AsmToken::Integer)) {
1934     Error(Parser.getTok().getLoc(),
1935           "expected integer shift amount");
1936     return MatchOperand_ParseFail;
1937   }
1938   unsigned Amount = Parser.getTok().getIntVal();
1939   Parser.Lex();
1940   E = Parser.getTok().getLoc();
1941
1942   Operands.push_back(AArch64Operand::CreateShiftExtend(Spec, Amount, false,
1943                                                        S, E));
1944
1945   return MatchOperand_Success;
1946 }
1947
1948 /// Try to parse a vector register token, If it is a vector register,
1949 /// the token is eaten and return true. Otherwise return false.
1950 bool AArch64AsmParser::TryParseVector(uint32_t &RegNum, SMLoc &RegEndLoc,
1951                                       StringRef &Layout, SMLoc &LayoutLoc) {
1952   bool IsVector = true;
1953
1954   if (!IdentifyRegister(RegNum, RegEndLoc, Layout, LayoutLoc))
1955     IsVector = false;
1956
1957   if (!AArch64MCRegisterClasses[AArch64::FPR64RegClassID].contains(RegNum) &&
1958       !AArch64MCRegisterClasses[AArch64::FPR128RegClassID].contains(RegNum))
1959     IsVector = false;
1960
1961   if (Layout.size() == 0)
1962     IsVector = false;
1963
1964   if (!IsVector)
1965     Error(Parser.getTok().getLoc(), "expected vector type register");
1966
1967   Parser.Lex(); // Eat this token.
1968   return IsVector;
1969 }
1970
1971
1972 // A vector list contains 1-4 consecutive registers.
1973 // Now there are two kinds of vector list when number of vector > 1:
1974 //   (1) {Vn.layout, Vn+1.layout, ... , Vm.layout}
1975 //   (2) {Vn.layout - Vm.layout}
1976 AArch64AsmParser::OperandMatchResultTy AArch64AsmParser::ParseVectorList(
1977     SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
1978   if (Parser.getTok().isNot(AsmToken::LCurly)) {
1979     Error(Parser.getTok().getLoc(), "'{' expected");
1980     return MatchOperand_ParseFail;
1981   }
1982   SMLoc SLoc = Parser.getTok().getLoc();
1983   Parser.Lex(); // Eat '{' token.
1984
1985   unsigned Reg, Count = 1;
1986   StringRef LayoutStr;
1987   SMLoc RegEndLoc, LayoutLoc;
1988   if (!TryParseVector(Reg, RegEndLoc, LayoutStr, LayoutLoc))
1989     return MatchOperand_ParseFail;
1990
1991   if (Parser.getTok().is(AsmToken::Minus)) {
1992     Parser.Lex(); // Eat the minus.
1993
1994     unsigned Reg2;
1995     StringRef LayoutStr2;
1996     SMLoc RegEndLoc2, LayoutLoc2;
1997     SMLoc RegLoc2 = Parser.getTok().getLoc();
1998
1999     if (!TryParseVector(Reg2, RegEndLoc2, LayoutStr2, LayoutLoc2))
2000       return MatchOperand_ParseFail;
2001     unsigned Space = (Reg < Reg2) ? (Reg2 - Reg) : (Reg2 + 32 - Reg);
2002
2003     if (LayoutStr != LayoutStr2) {
2004       Error(LayoutLoc2, "expected the same vector layout");
2005       return MatchOperand_ParseFail;
2006     }
2007     if (Space == 0 || Space > 3) {
2008       Error(RegLoc2, "invalid number of vectors");
2009       return MatchOperand_ParseFail;
2010     }
2011
2012     Count += Space;
2013   } else {
2014     unsigned LastReg = Reg;
2015     while (Parser.getTok().is(AsmToken::Comma)) {
2016       Parser.Lex(); // Eat the comma.
2017       unsigned Reg2;
2018       StringRef LayoutStr2;
2019       SMLoc RegEndLoc2, LayoutLoc2;
2020       SMLoc RegLoc2 = Parser.getTok().getLoc();
2021
2022       if (!TryParseVector(Reg2, RegEndLoc2, LayoutStr2, LayoutLoc2))
2023         return MatchOperand_ParseFail;
2024       unsigned Space = (LastReg < Reg2) ? (Reg2 - LastReg)
2025                                         : (Reg2 + 32 - LastReg);
2026       Count++;
2027
2028       // The space between two vectors should be 1. And they should have the same layout.
2029       // Total count shouldn't be great than 4
2030       if (Space != 1) {
2031         Error(RegLoc2, "invalid space between two vectors");
2032         return MatchOperand_ParseFail;
2033       }
2034       if (LayoutStr != LayoutStr2) {
2035         Error(LayoutLoc2, "expected the same vector layout");
2036         return MatchOperand_ParseFail;
2037       }
2038       if (Count > 4) {
2039         Error(RegLoc2, "invalid number of vectors");
2040         return MatchOperand_ParseFail;
2041       }
2042
2043       LastReg = Reg2;
2044     }
2045   }
2046
2047   if (Parser.getTok().isNot(AsmToken::RCurly)) {
2048     Error(Parser.getTok().getLoc(), "'}' expected");
2049     return MatchOperand_ParseFail;
2050   }
2051   SMLoc ELoc = Parser.getTok().getLoc();
2052   Parser.Lex(); // Eat '}' token.
2053
2054   A64Layout::VectorLayout Layout = A64StringToVectorLayout(LayoutStr);
2055   if (Count > 1) { // If count > 1, create vector list using super register.
2056     bool IsVec64 = (Layout < A64Layout::_16B) ? true : false;
2057     static unsigned SupRegIDs[3][2] = {
2058       { AArch64::QPairRegClassID, AArch64::DPairRegClassID },
2059       { AArch64::QTripleRegClassID, AArch64::DTripleRegClassID },
2060       { AArch64::QQuadRegClassID, AArch64::DQuadRegClassID }
2061     };
2062     unsigned SupRegID = SupRegIDs[Count - 2][static_cast<int>(IsVec64)];
2063     unsigned Sub0 = IsVec64 ? AArch64::dsub_0 : AArch64::qsub_0;
2064     const MCRegisterInfo *MRI = getContext().getRegisterInfo();
2065     Reg = MRI->getMatchingSuperReg(Reg, Sub0,
2066                                    &AArch64MCRegisterClasses[SupRegID]);
2067   }
2068   Operands.push_back(
2069       AArch64Operand::CreateVectorList(Reg, Count, Layout, SLoc, ELoc));
2070
2071   return MatchOperand_Success;
2072 }
2073
2074 // FIXME: We would really like to be able to tablegen'erate this.
2075 bool AArch64AsmParser::
2076 validateInstruction(MCInst &Inst,
2077                     const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2078   switch (Inst.getOpcode()) {
2079   case AArch64::BFIwwii:
2080   case AArch64::BFIxxii:
2081   case AArch64::SBFIZwwii:
2082   case AArch64::SBFIZxxii:
2083   case AArch64::UBFIZwwii:
2084   case AArch64::UBFIZxxii:  {
2085     unsigned ImmOps = Inst.getNumOperands() - 2;
2086     int64_t ImmR = Inst.getOperand(ImmOps).getImm();
2087     int64_t ImmS = Inst.getOperand(ImmOps+1).getImm();
2088
2089     if (ImmR != 0 && ImmS >= ImmR) {
2090       return Error(Operands[4]->getStartLoc(),
2091                    "requested insert overflows register");
2092     }
2093     return false;
2094   }
2095   case AArch64::BFXILwwii:
2096   case AArch64::BFXILxxii:
2097   case AArch64::SBFXwwii:
2098   case AArch64::SBFXxxii:
2099   case AArch64::UBFXwwii:
2100   case AArch64::UBFXxxii: {
2101     unsigned ImmOps = Inst.getNumOperands() - 2;
2102     int64_t ImmR = Inst.getOperand(ImmOps).getImm();
2103     int64_t ImmS = Inst.getOperand(ImmOps+1).getImm();
2104     int64_t RegWidth = 0;
2105     switch (Inst.getOpcode()) {
2106     case AArch64::SBFXxxii: case AArch64::UBFXxxii: case AArch64::BFXILxxii:
2107       RegWidth = 64;
2108       break;
2109     case AArch64::SBFXwwii: case AArch64::UBFXwwii: case AArch64::BFXILwwii:
2110       RegWidth = 32;
2111       break;
2112     }
2113
2114     if (ImmS >= RegWidth || ImmS < ImmR) {
2115       return Error(Operands[4]->getStartLoc(),
2116                    "requested extract overflows register");
2117     }
2118     return false;
2119   }
2120   case AArch64::ICix: {
2121     int64_t ImmVal = Inst.getOperand(0).getImm();
2122     A64IC::ICValues ICOp = static_cast<A64IC::ICValues>(ImmVal);
2123     if (!A64IC::NeedsRegister(ICOp)) {
2124       return Error(Operands[1]->getStartLoc(),
2125                    "specified IC op does not use a register");
2126     }
2127     return false;
2128   }
2129   case AArch64::ICi: {
2130     int64_t ImmVal = Inst.getOperand(0).getImm();
2131     A64IC::ICValues ICOp = static_cast<A64IC::ICValues>(ImmVal);
2132     if (A64IC::NeedsRegister(ICOp)) {
2133       return Error(Operands[1]->getStartLoc(),
2134                    "specified IC op requires a register");
2135     }
2136     return false;
2137   }
2138   case AArch64::TLBIix: {
2139     int64_t ImmVal = Inst.getOperand(0).getImm();
2140     A64TLBI::TLBIValues TLBIOp = static_cast<A64TLBI::TLBIValues>(ImmVal);
2141     if (!A64TLBI::NeedsRegister(TLBIOp)) {
2142       return Error(Operands[1]->getStartLoc(),
2143                    "specified TLBI op does not use a register");
2144     }
2145     return false;
2146   }
2147   case AArch64::TLBIi: {
2148     int64_t ImmVal = Inst.getOperand(0).getImm();
2149     A64TLBI::TLBIValues TLBIOp = static_cast<A64TLBI::TLBIValues>(ImmVal);
2150     if (A64TLBI::NeedsRegister(TLBIOp)) {
2151       return Error(Operands[1]->getStartLoc(),
2152                    "specified TLBI op requires a register");
2153     }
2154     return false;
2155   }
2156   }
2157
2158   return false;
2159 }
2160
2161
2162 // Parses the instruction *together with* all operands, appending each parsed
2163 // operand to the "Operands" list
2164 bool AArch64AsmParser::ParseInstruction(ParseInstructionInfo &Info,
2165                                         StringRef Name, SMLoc NameLoc,
2166                                SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2167   size_t CondCodePos = Name.find('.');
2168
2169   StringRef Mnemonic = Name.substr(0, CondCodePos);
2170   Operands.push_back(AArch64Operand::CreateToken(Mnemonic, NameLoc));
2171
2172   if (CondCodePos != StringRef::npos) {
2173     // We have a condition code
2174     SMLoc S = SMLoc::getFromPointer(NameLoc.getPointer() + CondCodePos + 1);
2175     StringRef CondStr = Name.substr(CondCodePos + 1, StringRef::npos);
2176     A64CC::CondCodes Code;
2177
2178     Code = A64StringToCondCode(CondStr);
2179
2180     if (Code == A64CC::Invalid) {
2181       Error(S, "invalid condition code");
2182       Parser.eatToEndOfStatement();
2183       return true;
2184     }
2185
2186     SMLoc DotL = SMLoc::getFromPointer(NameLoc.getPointer() + CondCodePos);
2187
2188     Operands.push_back(AArch64Operand::CreateToken(".",  DotL));
2189     SMLoc E = SMLoc::getFromPointer(NameLoc.getPointer() + CondCodePos + 3);
2190     Operands.push_back(AArch64Operand::CreateCondCode(Code, S, E));
2191   }
2192
2193   // Now we parse the operands of this instruction
2194   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2195     // Read the first operand.
2196     if (ParseOperand(Operands, Mnemonic)) {
2197       Parser.eatToEndOfStatement();
2198       return true;
2199     }
2200
2201     while (getLexer().is(AsmToken::Comma)) {
2202       Parser.Lex();  // Eat the comma.
2203
2204       // Parse and remember the operand.
2205       if (ParseOperand(Operands, Mnemonic)) {
2206         Parser.eatToEndOfStatement();
2207         return true;
2208       }
2209
2210
2211       // After successfully parsing some operands there are two special cases to
2212       // consider (i.e. notional operands not separated by commas). Both are due
2213       // to memory specifiers:
2214       //  + An RBrac will end an address for load/store/prefetch
2215       //  + An '!' will indicate a pre-indexed operation.
2216       //
2217       // It's someone else's responsibility to make sure these tokens are sane
2218       // in the given context!
2219       if (Parser.getTok().is(AsmToken::RBrac)) {
2220         SMLoc Loc = Parser.getTok().getLoc();
2221         Operands.push_back(AArch64Operand::CreateToken("]", Loc));
2222         Parser.Lex();
2223       }
2224
2225       if (Parser.getTok().is(AsmToken::Exclaim)) {
2226         SMLoc Loc = Parser.getTok().getLoc();
2227         Operands.push_back(AArch64Operand::CreateToken("!", Loc));
2228         Parser.Lex();
2229       }
2230     }
2231   }
2232
2233   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2234     SMLoc Loc = getLexer().getLoc();
2235     Parser.eatToEndOfStatement();
2236     return Error(Loc, "expected comma before next operand");
2237   }
2238
2239   // Eat the EndOfStatement
2240   Parser.Lex();
2241
2242   return false;
2243 }
2244
2245 bool AArch64AsmParser::ParseDirective(AsmToken DirectiveID) {
2246   StringRef IDVal = DirectiveID.getIdentifier();
2247   if (IDVal == ".hword")
2248     return ParseDirectiveWord(2, DirectiveID.getLoc());
2249   else if (IDVal == ".word")
2250     return ParseDirectiveWord(4, DirectiveID.getLoc());
2251   else if (IDVal == ".xword")
2252     return ParseDirectiveWord(8, DirectiveID.getLoc());
2253   else if (IDVal == ".tlsdesccall")
2254     return ParseDirectiveTLSDescCall(DirectiveID.getLoc());
2255
2256   return true;
2257 }
2258
2259 /// parseDirectiveWord
2260 ///  ::= .word [ expression (, expression)* ]
2261 bool AArch64AsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
2262   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2263     for (;;) {
2264       const MCExpr *Value;
2265       if (getParser().parseExpression(Value))
2266         return true;
2267
2268       getParser().getStreamer().EmitValue(Value, Size);
2269
2270       if (getLexer().is(AsmToken::EndOfStatement))
2271         break;
2272
2273       // FIXME: Improve diagnostic.
2274       if (getLexer().isNot(AsmToken::Comma))
2275         return Error(L, "unexpected token in directive");
2276       Parser.Lex();
2277     }
2278   }
2279
2280   Parser.Lex();
2281   return false;
2282 }
2283
2284 // parseDirectiveTLSDescCall:
2285 //   ::= .tlsdesccall symbol
2286 bool AArch64AsmParser::ParseDirectiveTLSDescCall(SMLoc L) {
2287   StringRef Name;
2288   if (getParser().parseIdentifier(Name))
2289     return Error(L, "expected symbol after directive");
2290
2291   MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2292   const MCSymbolRefExpr *Expr = MCSymbolRefExpr::Create(Sym, getContext());
2293
2294   MCInst Inst;
2295   Inst.setOpcode(AArch64::TLSDESCCALL);
2296   Inst.addOperand(MCOperand::CreateExpr(Expr));
2297
2298   getParser().getStreamer().EmitInstruction(Inst);
2299   return false;
2300 }
2301
2302
2303 bool AArch64AsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
2304                                  SmallVectorImpl<MCParsedAsmOperand*> &Operands,
2305                                  MCStreamer &Out, unsigned &ErrorInfo,
2306                                  bool MatchingInlineAsm) {
2307   MCInst Inst;
2308   unsigned MatchResult;
2309   MatchResult = MatchInstructionImpl(Operands, Inst, ErrorInfo,
2310                                      MatchingInlineAsm);
2311
2312   if (ErrorInfo != ~0U && ErrorInfo >= Operands.size())
2313     return Error(IDLoc, "too few operands for instruction");
2314
2315   switch (MatchResult) {
2316   default: break;
2317   case Match_Success:
2318     if (validateInstruction(Inst, Operands))
2319       return true;
2320
2321     Out.EmitInstruction(Inst);
2322     return false;
2323   case Match_MissingFeature:
2324     Error(IDLoc, "instruction requires a CPU feature not currently enabled");
2325     return true;
2326   case Match_InvalidOperand: {
2327     SMLoc ErrorLoc = IDLoc;
2328     if (ErrorInfo != ~0U) {
2329       ErrorLoc = ((AArch64Operand*)Operands[ErrorInfo])->getStartLoc();
2330       if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
2331     }
2332
2333     return Error(ErrorLoc, "invalid operand for instruction");
2334   }
2335   case Match_MnemonicFail:
2336     return Error(IDLoc, "invalid instruction");
2337
2338   case Match_AddSubRegExtendSmall:
2339     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2340       "expected '[su]xt[bhw]' or 'lsl' with optional integer in range [0, 4]");
2341   case Match_AddSubRegExtendLarge:
2342     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2343       "expected 'sxtx' 'uxtx' or 'lsl' with optional integer in range [0, 4]");
2344   case Match_AddSubRegShift32:
2345     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2346        "expected 'lsl', 'lsr' or 'asr' with optional integer in range [0, 31]");
2347   case Match_AddSubRegShift64:
2348     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2349        "expected 'lsl', 'lsr' or 'asr' with optional integer in range [0, 63]");
2350   case Match_AddSubSecondSource:
2351       return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2352           "expected compatible register, symbol or integer in range [0, 4095]");
2353   case Match_CVTFixedPos32:
2354     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2355                  "expected integer in range [1, 32]");
2356   case Match_CVTFixedPos64:
2357     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2358                  "expected integer in range [1, 64]");
2359   case Match_CondCode:
2360     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2361                  "expected AArch64 condition code");
2362   case Match_FPImm:
2363     // Any situation which allows a nontrivial floating-point constant also
2364     // allows a register.
2365     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2366                  "expected compatible register or floating-point constant");
2367   case Match_FPZero:
2368     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2369                  "expected floating-point constant #0.0 or invalid register type");
2370   case Match_Label:
2371     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2372                  "expected label or encodable integer pc offset");
2373   case Match_Lane1:
2374     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2375                  "expected lane specifier '[1]'");
2376   case Match_LoadStoreExtend32_1:
2377     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2378                  "expected 'uxtw' or 'sxtw' with optional shift of #0");
2379   case Match_LoadStoreExtend32_2:
2380     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2381                  "expected 'uxtw' or 'sxtw' with optional shift of #0 or #1");
2382   case Match_LoadStoreExtend32_4:
2383     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2384                  "expected 'uxtw' or 'sxtw' with optional shift of #0 or #2");
2385   case Match_LoadStoreExtend32_8:
2386     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2387                  "expected 'uxtw' or 'sxtw' with optional shift of #0 or #3");
2388   case Match_LoadStoreExtend32_16:
2389     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2390                  "expected 'lsl' or 'sxtw' with optional shift of #0 or #4");
2391   case Match_LoadStoreExtend64_1:
2392     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2393                  "expected 'lsl' or 'sxtx' with optional shift of #0");
2394   case Match_LoadStoreExtend64_2:
2395     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2396                  "expected 'lsl' or 'sxtx' with optional shift of #0 or #1");
2397   case Match_LoadStoreExtend64_4:
2398     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2399                  "expected 'lsl' or 'sxtx' with optional shift of #0 or #2");
2400   case Match_LoadStoreExtend64_8:
2401     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2402                  "expected 'lsl' or 'sxtx' with optional shift of #0 or #3");
2403   case Match_LoadStoreExtend64_16:
2404     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2405                  "expected 'lsl' or 'sxtx' with optional shift of #0 or #4");
2406   case Match_LoadStoreSImm7_4:
2407     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2408                  "expected integer multiple of 4 in range [-256, 252]");
2409   case Match_LoadStoreSImm7_8:
2410     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2411                  "expected integer multiple of 8 in range [-512, 508]");
2412   case Match_LoadStoreSImm7_16:
2413     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2414                  "expected integer multiple of 16 in range [-1024, 1016]");
2415   case Match_LoadStoreSImm9:
2416     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2417                  "expected integer in range [-256, 255]");
2418   case Match_LoadStoreUImm12_1:
2419     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2420                  "expected symbolic reference or integer in range [0, 4095]");
2421   case Match_LoadStoreUImm12_2:
2422     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2423                  "expected symbolic reference or integer in range [0, 8190]");
2424   case Match_LoadStoreUImm12_4:
2425     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2426                  "expected symbolic reference or integer in range [0, 16380]");
2427   case Match_LoadStoreUImm12_8:
2428     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2429                  "expected symbolic reference or integer in range [0, 32760]");
2430   case Match_LoadStoreUImm12_16:
2431     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2432                  "expected symbolic reference or integer in range [0, 65520]");
2433   case Match_LogicalSecondSource:
2434     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2435                  "expected compatible register or logical immediate");
2436   case Match_MOVWUImm16:
2437     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2438                  "expected relocated symbol or integer in range [0, 65535]");
2439   case Match_MRS:
2440     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2441                  "expected readable system register");
2442   case Match_MSR:
2443     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2444                  "expected writable system register or pstate");
2445   case Match_NamedImm_at:
2446     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2447                 "expected symbolic 'at' operand: s1e[0-3][rw] or s12e[01][rw]");
2448   case Match_NamedImm_dbarrier:
2449     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2450              "expected integer in range [0, 15] or symbolic barrier operand");
2451   case Match_NamedImm_dc:
2452     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2453                  "expected symbolic 'dc' operand");
2454   case Match_NamedImm_ic:
2455     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2456                  "expected 'ic' operand: 'ialluis', 'iallu' or 'ivau'");
2457   case Match_NamedImm_isb:
2458     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2459                  "expected integer in range [0, 15] or 'sy'");
2460   case Match_NamedImm_prefetch:
2461     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2462                  "expected prefetch hint: p(ld|st|i)l[123](strm|keep)");
2463   case Match_NamedImm_tlbi:
2464     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2465                  "expected translation buffer invalidation operand");
2466   case Match_UImm16:
2467     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2468                  "expected integer in range [0, 65535]");
2469   case Match_UImm3:
2470     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2471                  "expected integer in range [0, 7]");
2472   case Match_UImm4:
2473     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2474                  "expected integer in range [0, 15]");
2475   case Match_UImm5:
2476     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2477                  "expected integer in range [0, 31]");
2478   case Match_UImm6:
2479     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2480                  "expected integer in range [0, 63]");
2481   case Match_UImm7:
2482     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2483                  "expected integer in range [0, 127]");
2484   case Match_Width32:
2485     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2486                  "expected integer in range [<lsb>, 31]");
2487   case Match_Width64:
2488     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2489                  "expected integer in range [<lsb>, 63]");
2490   case Match_ShrImm8:
2491     return Error(((AArch64Operand *)Operands[ErrorInfo])->getStartLoc(),
2492                  "expected integer in range [1, 8]");
2493   case Match_ShrImm16:
2494     return Error(((AArch64Operand *)Operands[ErrorInfo])->getStartLoc(),
2495                  "expected integer in range [1, 16]");
2496   case Match_ShrImm32:
2497     return Error(((AArch64Operand *)Operands[ErrorInfo])->getStartLoc(),
2498                  "expected integer in range [1, 32]");
2499   case Match_ShrImm64:
2500     return Error(((AArch64Operand *)Operands[ErrorInfo])->getStartLoc(),
2501                  "expected integer in range [1, 64]");
2502   case Match_ShlImm8:
2503     return Error(((AArch64Operand *)Operands[ErrorInfo])->getStartLoc(),
2504                  "expected integer in range [0, 7]");
2505   case Match_ShlImm16:
2506     return Error(((AArch64Operand *)Operands[ErrorInfo])->getStartLoc(),
2507                  "expected integer in range [0, 15]");
2508   case Match_ShlImm32:
2509     return Error(((AArch64Operand *)Operands[ErrorInfo])->getStartLoc(),
2510                  "expected integer in range [0, 31]");
2511   case Match_ShlImm64:
2512     return Error(((AArch64Operand *)Operands[ErrorInfo])->getStartLoc(),
2513                  "expected integer in range [0, 63]");
2514   }
2515
2516   llvm_unreachable("Implement any new match types added!");
2517   return true;
2518 }
2519
2520 void AArch64Operand::print(raw_ostream &OS) const {
2521   switch (Kind) {
2522   case k_CondCode:
2523     OS << "<CondCode: " << CondCode.Code << ">";
2524     break;
2525   case k_FPImmediate:
2526     OS << "<fpimm: " << FPImm.Val << ">";
2527     break;
2528   case k_ImmWithLSL:
2529     OS << "<immwithlsl: imm=" << ImmWithLSL.Val
2530        << ", shift=" << ImmWithLSL.ShiftAmount << ">";
2531     break;
2532   case k_Immediate:
2533     getImm()->print(OS);
2534     break;
2535   case k_Register:
2536     OS << "<register " << getReg() << '>';
2537     break;
2538   case k_Token:
2539     OS << '\'' << getToken() << '\'';
2540     break;
2541   case k_ShiftExtend:
2542     OS << "<shift: type=" << ShiftExtend.ShiftType
2543        << ", amount=" << ShiftExtend.Amount << ">";
2544     break;
2545   case k_SysReg: {
2546     StringRef Name(SysReg.Data, SysReg.Length);
2547     OS << "<sysreg: " << Name << '>';
2548     break;
2549   }
2550   default:
2551     llvm_unreachable("No idea how to print this kind of operand");
2552     break;
2553   }
2554 }
2555
2556 void AArch64Operand::dump() const {
2557   print(errs());
2558 }
2559
2560
2561 /// Force static initialization.
2562 extern "C" void LLVMInitializeAArch64AsmParser() {
2563   RegisterMCAsmParser<AArch64AsmParser> X(TheAArch64Target);
2564 }
2565
2566 #define GET_REGISTER_MATCHER
2567 #define GET_MATCHER_IMPLEMENTATION
2568 #include "AArch64GenAsmMatcher.inc"