Implement AArch64 vector load/store multiple N-element structure class SIMD(lselem).
[oota-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   bool isNeonMovImmShiftLSL() const {
702     if (!isShiftOrExtend())
703       return false;
704
705     if (ShiftExtend.ShiftType != A64SE::LSL)
706       return false;
707
708     // Valid shift amount is 0, 8, 16 and 24.
709     return ShiftExtend.Amount % 8 == 0 && ShiftExtend.Amount <= 24;
710   }
711
712   bool isNeonMovImmShiftLSLH() const {
713     if (!isShiftOrExtend())
714       return false;
715
716     if (ShiftExtend.ShiftType != A64SE::LSL)
717       return false;
718
719     // Valid shift amount is 0 and 8.
720     return ShiftExtend.Amount == 0 || ShiftExtend.Amount == 8;
721   }
722
723   bool isNeonMovImmShiftMSL() const {
724     if (!isShiftOrExtend())
725       return false;
726
727     if (ShiftExtend.ShiftType != A64SE::MSL)
728       return false;
729
730     // Valid shift amount is 8 and 16.
731     return ShiftExtend.Amount == 8 || ShiftExtend.Amount == 16;
732   }
733
734   template <A64Layout::VectorLayout Layout, unsigned Count>
735   bool isVectorList() const {
736     return Kind == k_VectorList && VectorList.Layout == Layout &&
737            VectorList.Count == Count;
738   }
739
740   template <int MemSize> bool isSImm7Scaled() const {
741     if (!isImm())
742       return false;
743
744     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
745     if (!CE) return false;
746
747     int64_t Val = CE->getValue();
748     if (Val % MemSize != 0) return false;
749
750     Val /= MemSize;
751
752     return Val >= -64 && Val < 64;
753   }
754
755   template<int BitWidth>
756   bool isSImm() const {
757     if (!isImm()) return false;
758
759     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
760     if (!CE) return false;
761
762     return CE->getValue() >= -(1LL << (BitWidth - 1))
763       && CE->getValue() < (1LL << (BitWidth - 1));
764   }
765
766   template<int bitWidth>
767   bool isUImm() const {
768     if (!isImm()) return false;
769
770     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
771     if (!CE) return false;
772
773     return CE->getValue() >= 0 && CE->getValue() < (1LL << bitWidth);
774   }
775
776   bool isUImm() const {
777     if (!isImm()) return false;
778
779     return isa<MCConstantExpr>(getImm());
780   }
781
782   bool isNeonUImm64Mask() const {
783     if (!isImm())
784       return false;
785
786     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
787     if (!CE)
788       return false;
789
790     uint64_t Value = CE->getValue();
791
792     // i64 value with each byte being either 0x00 or 0xff.
793     for (unsigned i = 0; i < 8; ++i, Value >>= 8)
794       if ((Value & 0xff) != 0 && (Value & 0xff) != 0xff)
795         return false;
796     return true;
797   }
798
799   static AArch64Operand *CreateImmWithLSL(const MCExpr *Val,
800                                           unsigned ShiftAmount,
801                                           bool ImplicitAmount,
802                                                                                   SMLoc S,SMLoc E) {
803     AArch64Operand *Op = new AArch64Operand(k_ImmWithLSL, S, E);
804     Op->ImmWithLSL.Val = Val;
805     Op->ImmWithLSL.ShiftAmount = ShiftAmount;
806     Op->ImmWithLSL.ImplicitAmount = ImplicitAmount;
807     return Op;
808   }
809
810   static AArch64Operand *CreateCondCode(A64CC::CondCodes Code,
811                                         SMLoc S, SMLoc E) {
812     AArch64Operand *Op = new AArch64Operand(k_CondCode, S, E);
813     Op->CondCode.Code = Code;
814     return Op;
815   }
816
817   static AArch64Operand *CreateFPImm(double Val,
818                                      SMLoc S, SMLoc E) {
819     AArch64Operand *Op = new AArch64Operand(k_FPImmediate, S, E);
820     Op->FPImm.Val = Val;
821     return Op;
822   }
823
824   static AArch64Operand *CreateImm(const MCExpr *Val, SMLoc S, SMLoc E) {
825     AArch64Operand *Op = new AArch64Operand(k_Immediate, S, E);
826     Op->Imm.Val = Val;
827     return Op;
828   }
829
830   static AArch64Operand *CreateReg(unsigned RegNum, SMLoc S, SMLoc E) {
831     AArch64Operand *Op = new AArch64Operand(k_Register, S, E);
832     Op->Reg.RegNum = RegNum;
833     return Op;
834   }
835
836   static AArch64Operand *CreateWrappedReg(unsigned RegNum, SMLoc S, SMLoc E) {
837     AArch64Operand *Op = new AArch64Operand(k_WrappedRegister, S, E);
838     Op->Reg.RegNum = RegNum;
839     return Op;
840   }
841
842   static AArch64Operand *CreateShiftExtend(A64SE::ShiftExtSpecifiers ShiftTyp,
843                                            unsigned Amount,
844                                            bool ImplicitAmount,
845                                            SMLoc S, SMLoc E) {
846     AArch64Operand *Op = new AArch64Operand(k_ShiftExtend, S, E);
847     Op->ShiftExtend.ShiftType = ShiftTyp;
848     Op->ShiftExtend.Amount = Amount;
849     Op->ShiftExtend.ImplicitAmount = ImplicitAmount;
850     return Op;
851   }
852
853   static AArch64Operand *CreateSysReg(StringRef Str, SMLoc S) {
854     AArch64Operand *Op = new AArch64Operand(k_SysReg, S, S);
855     Op->Tok.Data = Str.data();
856     Op->Tok.Length = Str.size();
857     return Op;
858   }
859
860   static AArch64Operand *CreateVectorList(unsigned RegNum, unsigned Count,
861                                           A64Layout::VectorLayout Layout,
862                                           SMLoc S, SMLoc E) {
863     AArch64Operand *Op = new AArch64Operand(k_VectorList, S, E);
864     Op->VectorList.RegNum = RegNum;
865     Op->VectorList.Count = Count;
866     Op->VectorList.Layout = Layout;
867     Op->StartLoc = S;
868     Op->EndLoc = E;
869     return Op;
870   }
871
872   static AArch64Operand *CreateToken(StringRef Str, SMLoc S) {
873     AArch64Operand *Op = new AArch64Operand(k_Token, S, S);
874     Op->Tok.Data = Str.data();
875     Op->Tok.Length = Str.size();
876     return Op;
877   }
878
879
880   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
881     // Add as immediates when possible.
882     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
883       Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
884     else
885       Inst.addOperand(MCOperand::CreateExpr(Expr));
886   }
887
888   template<unsigned RegWidth>
889   void addBFILSBOperands(MCInst &Inst, unsigned N) const {
890     assert(N == 1 && "Invalid number of operands!");
891     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
892     unsigned EncodedVal = (RegWidth - CE->getValue()) % RegWidth;
893     Inst.addOperand(MCOperand::CreateImm(EncodedVal));
894   }
895
896   void addBFIWidthOperands(MCInst &Inst, unsigned N) const {
897     assert(N == 1 && "Invalid number of operands!");
898     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
899     Inst.addOperand(MCOperand::CreateImm(CE->getValue() - 1));
900   }
901
902   void addBFXWidthOperands(MCInst &Inst, unsigned N) const {
903     assert(N == 1 && "Invalid number of operands!");
904
905     uint64_t LSB = Inst.getOperand(Inst.getNumOperands()-1).getImm();
906     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
907
908     Inst.addOperand(MCOperand::CreateImm(LSB + CE->getValue() - 1));
909   }
910
911   void addCondCodeOperands(MCInst &Inst, unsigned N) const {
912     assert(N == 1 && "Invalid number of operands!");
913     Inst.addOperand(MCOperand::CreateImm(getCondCode()));
914   }
915
916   void addCVTFixedPosOperands(MCInst &Inst, unsigned N) const {
917     assert(N == 1 && "Invalid number of operands!");
918
919     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
920     Inst.addOperand(MCOperand::CreateImm(64 - CE->getValue()));
921   }
922
923   void addFMOVImmOperands(MCInst &Inst, unsigned N) const {
924     assert(N == 1 && "Invalid number of operands!");
925
926     APFloat RealVal(FPImm.Val);
927     uint32_t ImmVal;
928     A64Imms::isFPImm(RealVal, ImmVal);
929
930     Inst.addOperand(MCOperand::CreateImm(ImmVal));
931   }
932
933   void addFPZeroOperands(MCInst &Inst, unsigned N) const {
934     assert(N == 1 && "Invalid number of operands");
935     Inst.addOperand(MCOperand::CreateImm(0));
936   }
937
938   void addInvCondCodeOperands(MCInst &Inst, unsigned N) const {
939     assert(N == 1 && "Invalid number of operands!");
940     unsigned Encoded = A64InvertCondCode(getCondCode());
941     Inst.addOperand(MCOperand::CreateImm(Encoded));
942   }
943
944   void addRegOperands(MCInst &Inst, unsigned N) const {
945     assert(N == 1 && "Invalid number of operands!");
946     Inst.addOperand(MCOperand::CreateReg(getReg()));
947   }
948
949   void addImmOperands(MCInst &Inst, unsigned N) const {
950     assert(N == 1 && "Invalid number of operands!");
951     addExpr(Inst, getImm());
952   }
953
954   template<int MemSize>
955   void addSImm7ScaledOperands(MCInst &Inst, unsigned N) const {
956     assert(N == 1 && "Invalid number of operands!");
957
958     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
959     uint64_t Val = CE->getValue() / MemSize;
960     Inst.addOperand(MCOperand::CreateImm(Val  & 0x7f));
961   }
962
963   template<int BitWidth>
964   void addSImmOperands(MCInst &Inst, unsigned N) const {
965     assert(N == 1 && "Invalid number of operands!");
966
967     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
968     uint64_t Val = CE->getValue();
969     Inst.addOperand(MCOperand::CreateImm(Val  & ((1ULL << BitWidth) - 1)));
970   }
971
972   void addImmWithLSLOperands(MCInst &Inst, unsigned N) const {
973     assert (N == 1 && "Invalid number of operands!");
974
975     addExpr(Inst, ImmWithLSL.Val);
976   }
977
978   template<unsigned field_width, unsigned scale>
979   void addLabelOperands(MCInst &Inst, unsigned N) const {
980     assert(N == 1 && "Invalid number of operands!");
981
982     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val);
983
984     if (!CE) {
985       addExpr(Inst, Imm.Val);
986       return;
987     }
988
989     int64_t Val = CE->getValue();
990     assert(Val % scale == 0 && "Unaligned immediate in instruction");
991     Val /= scale;
992
993     Inst.addOperand(MCOperand::CreateImm(Val & ((1LL << field_width) - 1)));
994   }
995
996   template<int MemSize>
997   void addOffsetUImm12Operands(MCInst &Inst, unsigned N) const {
998     assert(N == 1 && "Invalid number of operands!");
999
1000     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm())) {
1001       Inst.addOperand(MCOperand::CreateImm(CE->getValue() / MemSize));
1002     } else {
1003       Inst.addOperand(MCOperand::CreateExpr(getImm()));
1004     }
1005   }
1006
1007   template<unsigned RegWidth>
1008   void addLogicalImmOperands(MCInst &Inst, unsigned N) const {
1009     assert(N == 1 && "Invalid number of operands");
1010     const MCConstantExpr *CE = cast<MCConstantExpr>(Imm.Val);
1011
1012     uint32_t Bits;
1013     A64Imms::isLogicalImm(RegWidth, CE->getValue(), Bits);
1014
1015     Inst.addOperand(MCOperand::CreateImm(Bits));
1016   }
1017
1018   void addMRSOperands(MCInst &Inst, unsigned N) const {
1019     assert(N == 1 && "Invalid number of operands!");
1020
1021     bool Valid;
1022     StringRef Name(SysReg.Data, SysReg.Length);
1023     uint32_t Bits = A64SysReg::MRSMapper().fromString(Name, Valid);
1024
1025     Inst.addOperand(MCOperand::CreateImm(Bits));
1026   }
1027
1028   void addMSRWithRegOperands(MCInst &Inst, unsigned N) const {
1029     assert(N == 1 && "Invalid number of operands!");
1030
1031     bool Valid;
1032     StringRef Name(SysReg.Data, SysReg.Length);
1033     uint32_t Bits = A64SysReg::MSRMapper().fromString(Name, Valid);
1034
1035     Inst.addOperand(MCOperand::CreateImm(Bits));
1036   }
1037
1038   void addMSRPStateOperands(MCInst &Inst, unsigned N) const {
1039     assert(N == 1 && "Invalid number of operands!");
1040
1041     bool Valid;
1042     StringRef Name(SysReg.Data, SysReg.Length);
1043     uint32_t Bits = A64PState::PStateMapper().fromString(Name, Valid);
1044
1045     Inst.addOperand(MCOperand::CreateImm(Bits));
1046   }
1047
1048   void addMoveWideImmOperands(MCInst &Inst, unsigned N) const {
1049     assert(N == 2 && "Invalid number of operands!");
1050
1051     addExpr(Inst, ImmWithLSL.Val);
1052
1053     AArch64MCExpr::VariantKind Variant;
1054     if (!isNonConstantExpr(ImmWithLSL.Val, Variant)) {
1055       Inst.addOperand(MCOperand::CreateImm(ImmWithLSL.ShiftAmount / 16));
1056       return;
1057     }
1058
1059     // We know it's relocated
1060     switch (Variant) {
1061     case AArch64MCExpr::VK_AARCH64_ABS_G0:
1062     case AArch64MCExpr::VK_AARCH64_ABS_G0_NC:
1063     case AArch64MCExpr::VK_AARCH64_SABS_G0:
1064     case AArch64MCExpr::VK_AARCH64_DTPREL_G0:
1065     case AArch64MCExpr::VK_AARCH64_DTPREL_G0_NC:
1066     case AArch64MCExpr::VK_AARCH64_GOTTPREL_G0_NC:
1067     case AArch64MCExpr::VK_AARCH64_TPREL_G0:
1068     case AArch64MCExpr::VK_AARCH64_TPREL_G0_NC:
1069       Inst.addOperand(MCOperand::CreateImm(0));
1070       break;
1071     case AArch64MCExpr::VK_AARCH64_ABS_G1:
1072     case AArch64MCExpr::VK_AARCH64_ABS_G1_NC:
1073     case AArch64MCExpr::VK_AARCH64_SABS_G1:
1074     case AArch64MCExpr::VK_AARCH64_DTPREL_G1:
1075     case AArch64MCExpr::VK_AARCH64_DTPREL_G1_NC:
1076     case AArch64MCExpr::VK_AARCH64_GOTTPREL_G1:
1077     case AArch64MCExpr::VK_AARCH64_TPREL_G1:
1078     case AArch64MCExpr::VK_AARCH64_TPREL_G1_NC:
1079       Inst.addOperand(MCOperand::CreateImm(1));
1080       break;
1081     case AArch64MCExpr::VK_AARCH64_ABS_G2:
1082     case AArch64MCExpr::VK_AARCH64_ABS_G2_NC:
1083     case AArch64MCExpr::VK_AARCH64_SABS_G2:
1084     case AArch64MCExpr::VK_AARCH64_DTPREL_G2:
1085     case AArch64MCExpr::VK_AARCH64_TPREL_G2:
1086       Inst.addOperand(MCOperand::CreateImm(2));
1087       break;
1088     case AArch64MCExpr::VK_AARCH64_ABS_G3:
1089       Inst.addOperand(MCOperand::CreateImm(3));
1090       break;
1091     default: llvm_unreachable("Inappropriate move wide relocation");
1092     }
1093   }
1094
1095   template<int RegWidth, bool isValidImm(int, uint64_t, int&, int&)>
1096   void addMoveWideMovAliasOperands(MCInst &Inst, unsigned N) const {
1097     assert(N == 2 && "Invalid number of operands!");
1098     int UImm16, Shift;
1099
1100     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
1101     uint64_t Value = CE->getValue();
1102
1103     if (RegWidth == 32) {
1104       Value &= 0xffffffffULL;
1105     }
1106
1107     bool Valid = isValidImm(RegWidth, Value, UImm16, Shift);
1108     (void)Valid;
1109     assert(Valid && "Invalid immediates should have been weeded out by now");
1110
1111     Inst.addOperand(MCOperand::CreateImm(UImm16));
1112     Inst.addOperand(MCOperand::CreateImm(Shift));
1113   }
1114
1115   void addPRFMOperands(MCInst &Inst, unsigned N) const {
1116     assert(N == 1 && "Invalid number of operands!");
1117
1118     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
1119     assert(CE->getValue() >= 0 && CE->getValue() <= 31
1120            && "PRFM operand should be 5-bits");
1121
1122     Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
1123   }
1124
1125   // For Add-sub (extended register) operands.
1126   void addRegExtendOperands(MCInst &Inst, unsigned N) const {
1127     assert(N == 1 && "Invalid number of operands!");
1128
1129     Inst.addOperand(MCOperand::CreateImm(ShiftExtend.Amount));
1130   }
1131
1132   // For Vector Immediates shifted imm operands.
1133   void addNeonMovImmShiftLSLOperands(MCInst &Inst, unsigned N) const {
1134     assert(N == 1 && "Invalid number of operands!");
1135
1136     if (ShiftExtend.Amount % 8 != 0 || ShiftExtend.Amount > 24)
1137       llvm_unreachable("Invalid shift amount for vector immediate inst.");
1138
1139     // Encode LSL shift amount 0, 8, 16, 24 as 0, 1, 2, 3.
1140     int64_t Imm = ShiftExtend.Amount / 8;
1141     Inst.addOperand(MCOperand::CreateImm(Imm));
1142   }
1143
1144   void addNeonMovImmShiftLSLHOperands(MCInst &Inst, unsigned N) const {
1145     assert(N == 1 && "Invalid number of operands!");
1146
1147     if (ShiftExtend.Amount != 0 && ShiftExtend.Amount != 8)
1148       llvm_unreachable("Invalid shift amount for vector immediate inst.");
1149
1150     // Encode LSLH shift amount 0, 8  as 0, 1.
1151     int64_t Imm = ShiftExtend.Amount / 8;
1152     Inst.addOperand(MCOperand::CreateImm(Imm));
1153   }
1154
1155   void addNeonMovImmShiftMSLOperands(MCInst &Inst, unsigned N) const {
1156     assert(N == 1 && "Invalid number of operands!");
1157
1158     if (ShiftExtend.Amount != 8 && ShiftExtend.Amount != 16)
1159       llvm_unreachable("Invalid shift amount for vector immediate inst.");
1160
1161     // Encode MSL shift amount 8, 16  as 0, 1.
1162     int64_t Imm = ShiftExtend.Amount / 8 - 1;
1163     Inst.addOperand(MCOperand::CreateImm(Imm));
1164   }
1165
1166   // For the extend in load-store (register offset) instructions.
1167   template<unsigned MemSize>
1168   void addAddrRegExtendOperands(MCInst &Inst, unsigned N) const {
1169     addAddrRegExtendOperands(Inst, N, MemSize);
1170   }
1171
1172   void addAddrRegExtendOperands(MCInst &Inst, unsigned N,
1173                                 unsigned MemSize) const {
1174     assert(N == 1 && "Invalid number of operands!");
1175
1176     // First bit of Option is set in instruction classes, the high two bits are
1177     // as follows:
1178     unsigned OptionHi = 0;
1179     switch (ShiftExtend.ShiftType) {
1180     case A64SE::UXTW:
1181     case A64SE::LSL:
1182       OptionHi = 1;
1183       break;
1184     case A64SE::SXTW:
1185     case A64SE::SXTX:
1186       OptionHi = 3;
1187       break;
1188     default:
1189       llvm_unreachable("Invalid extend type for register offset");
1190     }
1191
1192     unsigned S = 0;
1193     if (MemSize == 1 && !ShiftExtend.ImplicitAmount)
1194       S = 1;
1195     else if (MemSize != 1 && ShiftExtend.Amount != 0)
1196       S = 1;
1197
1198     Inst.addOperand(MCOperand::CreateImm((OptionHi << 1) | S));
1199   }
1200   void addShiftOperands(MCInst &Inst, unsigned N) const {
1201     assert(N == 1 && "Invalid number of operands!");
1202
1203     Inst.addOperand(MCOperand::CreateImm(ShiftExtend.Amount));
1204   }
1205
1206   void addNeonUImm64MaskOperands(MCInst &Inst, unsigned N) const {
1207     assert(N == 1 && "Invalid number of operands!");
1208
1209     // A bit from each byte in the constant forms the encoded immediate
1210     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1211     uint64_t Value = CE->getValue();
1212
1213     unsigned Imm = 0;
1214     for (unsigned i = 0; i < 8; ++i, Value >>= 8) {
1215       Imm |= (Value & 1) << i;
1216     }
1217     Inst.addOperand(MCOperand::CreateImm(Imm));
1218   }
1219
1220   void addVectorListOperands(MCInst &Inst, unsigned N) const {
1221     assert(N == 1 && "Invalid number of operands!");
1222     Inst.addOperand(MCOperand::CreateReg(VectorList.RegNum));
1223   }
1224 };
1225
1226 } // end anonymous namespace.
1227
1228 AArch64AsmParser::OperandMatchResultTy
1229 AArch64AsmParser::ParseOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands,
1230                                StringRef Mnemonic) {
1231
1232   // See if the operand has a custom parser
1233   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
1234
1235   // It could either succeed, fail or just not care.
1236   if (ResTy != MatchOperand_NoMatch)
1237     return ResTy;
1238
1239   switch (getLexer().getKind()) {
1240   default:
1241     Error(Parser.getTok().getLoc(), "unexpected token in operand");
1242     return MatchOperand_ParseFail;
1243   case AsmToken::Identifier: {
1244     // It might be in the LSL/UXTB family ...
1245     OperandMatchResultTy GotShift = ParseShiftExtend(Operands);
1246
1247     // We can only continue if no tokens were eaten.
1248     if (GotShift != MatchOperand_NoMatch)
1249       return GotShift;
1250
1251     // ... or it might be a register ...
1252     uint32_t NumLanes = 0;
1253     OperandMatchResultTy GotReg = ParseRegister(Operands, NumLanes);
1254     assert(GotReg != MatchOperand_ParseFail
1255            && "register parsing shouldn't partially succeed");
1256
1257     if (GotReg == MatchOperand_Success) {
1258       if (Parser.getTok().is(AsmToken::LBrac))
1259         return ParseNEONLane(Operands, NumLanes);
1260       else
1261         return MatchOperand_Success;
1262     }
1263     // ... or it might be a symbolish thing
1264   }
1265     // Fall through
1266   case AsmToken::LParen:  // E.g. (strcmp-4)
1267   case AsmToken::Integer: // 1f, 2b labels
1268   case AsmToken::String:  // quoted labels
1269   case AsmToken::Dot:     // . is Current location
1270   case AsmToken::Dollar:  // $ is PC
1271   case AsmToken::Colon: {
1272     SMLoc StartLoc  = Parser.getTok().getLoc();
1273     SMLoc EndLoc;
1274     const MCExpr *ImmVal = 0;
1275
1276     if (ParseImmediate(ImmVal) != MatchOperand_Success)
1277       return MatchOperand_ParseFail;
1278
1279     EndLoc = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1280     Operands.push_back(AArch64Operand::CreateImm(ImmVal, StartLoc, EndLoc));
1281     return MatchOperand_Success;
1282   }
1283   case AsmToken::Hash: {   // Immediates
1284     SMLoc StartLoc = Parser.getTok().getLoc();
1285     SMLoc EndLoc;
1286     const MCExpr *ImmVal = 0;
1287     Parser.Lex();
1288
1289     if (ParseImmediate(ImmVal) != MatchOperand_Success)
1290       return MatchOperand_ParseFail;
1291
1292     EndLoc = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1293     Operands.push_back(AArch64Operand::CreateImm(ImmVal, StartLoc, EndLoc));
1294     return MatchOperand_Success;
1295   }
1296   case AsmToken::LBrac: {
1297     SMLoc Loc = Parser.getTok().getLoc();
1298     Operands.push_back(AArch64Operand::CreateToken("[", Loc));
1299     Parser.Lex(); // Eat '['
1300
1301     // There's no comma after a '[', so we can parse the next operand
1302     // immediately.
1303     return ParseOperand(Operands, Mnemonic);
1304   }
1305   // The following will likely be useful later, but not in very early cases
1306   case AsmToken::LCurly: // SIMD vector list is not parsed here
1307     llvm_unreachable("Don't know how to deal with '{' in operand");
1308     return MatchOperand_ParseFail;
1309   }
1310 }
1311
1312 AArch64AsmParser::OperandMatchResultTy
1313 AArch64AsmParser::ParseImmediate(const MCExpr *&ExprVal) {
1314   if (getLexer().is(AsmToken::Colon)) {
1315     AArch64MCExpr::VariantKind RefKind;
1316
1317     OperandMatchResultTy ResTy = ParseRelocPrefix(RefKind);
1318     if (ResTy != MatchOperand_Success)
1319       return ResTy;
1320
1321     const MCExpr *SubExprVal;
1322     if (getParser().parseExpression(SubExprVal))
1323       return MatchOperand_ParseFail;
1324
1325     ExprVal = AArch64MCExpr::Create(RefKind, SubExprVal, getContext());
1326     return MatchOperand_Success;
1327   }
1328
1329   // No weird AArch64MCExpr prefix
1330   return getParser().parseExpression(ExprVal)
1331     ? MatchOperand_ParseFail : MatchOperand_Success;
1332 }
1333
1334 // A lane attached to a NEON register. "[N]", which should yield three tokens:
1335 // '[', N, ']'. A hash is not allowed to precede the immediate here.
1336 AArch64AsmParser::OperandMatchResultTy
1337 AArch64AsmParser::ParseNEONLane(SmallVectorImpl<MCParsedAsmOperand*> &Operands,
1338                                 uint32_t NumLanes) {
1339   SMLoc Loc = Parser.getTok().getLoc();
1340
1341   assert(Parser.getTok().is(AsmToken::LBrac) && "inappropriate operand");
1342   Operands.push_back(AArch64Operand::CreateToken("[", Loc));
1343   Parser.Lex(); // Eat '['
1344
1345   if (Parser.getTok().isNot(AsmToken::Integer)) {
1346     Error(Parser.getTok().getLoc(), "expected lane number");
1347     return MatchOperand_ParseFail;
1348   }
1349
1350   if (Parser.getTok().getIntVal() >= NumLanes) {
1351     Error(Parser.getTok().getLoc(), "lane number incompatible with layout");
1352     return MatchOperand_ParseFail;
1353   }
1354
1355   const MCExpr *Lane = MCConstantExpr::Create(Parser.getTok().getIntVal(),
1356                                               getContext());
1357   SMLoc S = Parser.getTok().getLoc();
1358   Parser.Lex(); // Eat actual lane
1359   SMLoc E = Parser.getTok().getLoc();
1360   Operands.push_back(AArch64Operand::CreateImm(Lane, S, E));
1361
1362
1363   if (Parser.getTok().isNot(AsmToken::RBrac)) {
1364     Error(Parser.getTok().getLoc(), "expected ']' after lane");
1365     return MatchOperand_ParseFail;
1366   }
1367
1368   Operands.push_back(AArch64Operand::CreateToken("]", Loc));
1369   Parser.Lex(); // Eat ']'
1370
1371   return MatchOperand_Success;
1372 }
1373
1374 AArch64AsmParser::OperandMatchResultTy
1375 AArch64AsmParser::ParseRelocPrefix(AArch64MCExpr::VariantKind &RefKind) {
1376   assert(getLexer().is(AsmToken::Colon) && "expected a ':'");
1377   Parser.Lex();
1378
1379   if (getLexer().isNot(AsmToken::Identifier)) {
1380     Error(Parser.getTok().getLoc(),
1381           "expected relocation specifier in operand after ':'");
1382     return MatchOperand_ParseFail;
1383   }
1384
1385   std::string LowerCase = Parser.getTok().getIdentifier().lower();
1386   RefKind = StringSwitch<AArch64MCExpr::VariantKind>(LowerCase)
1387     .Case("got",              AArch64MCExpr::VK_AARCH64_GOT)
1388     .Case("got_lo12",         AArch64MCExpr::VK_AARCH64_GOT_LO12)
1389     .Case("lo12",             AArch64MCExpr::VK_AARCH64_LO12)
1390     .Case("abs_g0",           AArch64MCExpr::VK_AARCH64_ABS_G0)
1391     .Case("abs_g0_nc",        AArch64MCExpr::VK_AARCH64_ABS_G0_NC)
1392     .Case("abs_g1",           AArch64MCExpr::VK_AARCH64_ABS_G1)
1393     .Case("abs_g1_nc",        AArch64MCExpr::VK_AARCH64_ABS_G1_NC)
1394     .Case("abs_g2",           AArch64MCExpr::VK_AARCH64_ABS_G2)
1395     .Case("abs_g2_nc",        AArch64MCExpr::VK_AARCH64_ABS_G2_NC)
1396     .Case("abs_g3",           AArch64MCExpr::VK_AARCH64_ABS_G3)
1397     .Case("abs_g0_s",         AArch64MCExpr::VK_AARCH64_SABS_G0)
1398     .Case("abs_g1_s",         AArch64MCExpr::VK_AARCH64_SABS_G1)
1399     .Case("abs_g2_s",         AArch64MCExpr::VK_AARCH64_SABS_G2)
1400     .Case("dtprel_g2",        AArch64MCExpr::VK_AARCH64_DTPREL_G2)
1401     .Case("dtprel_g1",        AArch64MCExpr::VK_AARCH64_DTPREL_G1)
1402     .Case("dtprel_g1_nc",     AArch64MCExpr::VK_AARCH64_DTPREL_G1_NC)
1403     .Case("dtprel_g0",        AArch64MCExpr::VK_AARCH64_DTPREL_G0)
1404     .Case("dtprel_g0_nc",     AArch64MCExpr::VK_AARCH64_DTPREL_G0_NC)
1405     .Case("dtprel_hi12",      AArch64MCExpr::VK_AARCH64_DTPREL_HI12)
1406     .Case("dtprel_lo12",      AArch64MCExpr::VK_AARCH64_DTPREL_LO12)
1407     .Case("dtprel_lo12_nc",   AArch64MCExpr::VK_AARCH64_DTPREL_LO12_NC)
1408     .Case("gottprel_g1",      AArch64MCExpr::VK_AARCH64_GOTTPREL_G1)
1409     .Case("gottprel_g0_nc",   AArch64MCExpr::VK_AARCH64_GOTTPREL_G0_NC)
1410     .Case("gottprel",         AArch64MCExpr::VK_AARCH64_GOTTPREL)
1411     .Case("gottprel_lo12",    AArch64MCExpr::VK_AARCH64_GOTTPREL_LO12)
1412     .Case("tprel_g2",         AArch64MCExpr::VK_AARCH64_TPREL_G2)
1413     .Case("tprel_g1",         AArch64MCExpr::VK_AARCH64_TPREL_G1)
1414     .Case("tprel_g1_nc",      AArch64MCExpr::VK_AARCH64_TPREL_G1_NC)
1415     .Case("tprel_g0",         AArch64MCExpr::VK_AARCH64_TPREL_G0)
1416     .Case("tprel_g0_nc",      AArch64MCExpr::VK_AARCH64_TPREL_G0_NC)
1417     .Case("tprel_hi12",       AArch64MCExpr::VK_AARCH64_TPREL_HI12)
1418     .Case("tprel_lo12",       AArch64MCExpr::VK_AARCH64_TPREL_LO12)
1419     .Case("tprel_lo12_nc",    AArch64MCExpr::VK_AARCH64_TPREL_LO12_NC)
1420     .Case("tlsdesc",          AArch64MCExpr::VK_AARCH64_TLSDESC)
1421     .Case("tlsdesc_lo12",     AArch64MCExpr::VK_AARCH64_TLSDESC_LO12)
1422     .Default(AArch64MCExpr::VK_AARCH64_None);
1423
1424   if (RefKind == AArch64MCExpr::VK_AARCH64_None) {
1425     Error(Parser.getTok().getLoc(),
1426           "expected relocation specifier in operand after ':'");
1427     return MatchOperand_ParseFail;
1428   }
1429   Parser.Lex(); // Eat identifier
1430
1431   if (getLexer().isNot(AsmToken::Colon)) {
1432     Error(Parser.getTok().getLoc(),
1433           "expected ':' after relocation specifier");
1434     return MatchOperand_ParseFail;
1435   }
1436   Parser.Lex();
1437   return MatchOperand_Success;
1438 }
1439
1440 AArch64AsmParser::OperandMatchResultTy
1441 AArch64AsmParser::ParseImmWithLSLOperand(
1442                                SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1443   // FIXME?: I want to live in a world where immediates must start with
1444   // #. Please don't dash my hopes (well, do if you have a good reason).
1445   if (Parser.getTok().isNot(AsmToken::Hash)) return MatchOperand_NoMatch;
1446
1447   SMLoc S = Parser.getTok().getLoc();
1448   Parser.Lex(); // Eat '#'
1449
1450   const MCExpr *Imm;
1451   if (ParseImmediate(Imm) != MatchOperand_Success)
1452     return MatchOperand_ParseFail;
1453   else if (Parser.getTok().isNot(AsmToken::Comma)) {
1454     SMLoc E = Parser.getTok().getLoc();
1455     Operands.push_back(AArch64Operand::CreateImmWithLSL(Imm, 0, true, S, E));
1456     return MatchOperand_Success;
1457   }
1458
1459   // Eat ','
1460   Parser.Lex();
1461
1462   // The optional operand must be "lsl #N" where N is non-negative.
1463   if (Parser.getTok().is(AsmToken::Identifier)
1464       && Parser.getTok().getIdentifier().lower() == "lsl") {
1465     Parser.Lex();
1466
1467     if (Parser.getTok().is(AsmToken::Hash)) {
1468       Parser.Lex();
1469
1470       if (Parser.getTok().isNot(AsmToken::Integer)) {
1471         Error(Parser.getTok().getLoc(), "only 'lsl #+N' valid after immediate");
1472         return MatchOperand_ParseFail;
1473       }
1474     }
1475   }
1476
1477   int64_t ShiftAmount = Parser.getTok().getIntVal();
1478
1479   if (ShiftAmount < 0) {
1480     Error(Parser.getTok().getLoc(), "positive shift amount required");
1481     return MatchOperand_ParseFail;
1482   }
1483   Parser.Lex(); // Eat the number
1484
1485   SMLoc E = Parser.getTok().getLoc();
1486   Operands.push_back(AArch64Operand::CreateImmWithLSL(Imm, ShiftAmount,
1487                                                       false, S, E));
1488   return MatchOperand_Success;
1489 }
1490
1491
1492 AArch64AsmParser::OperandMatchResultTy
1493 AArch64AsmParser::ParseCondCodeOperand(
1494                                SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1495   if (Parser.getTok().isNot(AsmToken::Identifier))
1496     return MatchOperand_NoMatch;
1497
1498   StringRef Tok = Parser.getTok().getIdentifier();
1499   A64CC::CondCodes CondCode = A64StringToCondCode(Tok);
1500
1501   if (CondCode == A64CC::Invalid)
1502     return MatchOperand_NoMatch;
1503
1504   SMLoc S = Parser.getTok().getLoc();
1505   Parser.Lex(); // Eat condition code
1506   SMLoc E = Parser.getTok().getLoc();
1507
1508   Operands.push_back(AArch64Operand::CreateCondCode(CondCode, S, E));
1509   return MatchOperand_Success;
1510 }
1511
1512 AArch64AsmParser::OperandMatchResultTy
1513 AArch64AsmParser::ParseCRxOperand(
1514                                SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1515   SMLoc S = Parser.getTok().getLoc();
1516   if (Parser.getTok().isNot(AsmToken::Identifier)) {
1517     Error(S, "Expected cN operand where 0 <= N <= 15");
1518     return MatchOperand_ParseFail;
1519   }
1520
1521   std::string LowerTok = Parser.getTok().getIdentifier().lower();
1522   StringRef Tok(LowerTok);
1523   if (Tok[0] != 'c') {
1524     Error(S, "Expected cN operand where 0 <= N <= 15");
1525     return MatchOperand_ParseFail;
1526   }
1527
1528   uint32_t CRNum;
1529   bool BadNum = Tok.drop_front().getAsInteger(10, CRNum);
1530   if (BadNum || CRNum > 15) {
1531     Error(S, "Expected cN operand where 0 <= N <= 15");
1532     return MatchOperand_ParseFail;
1533   }
1534
1535   const MCExpr *CRImm = MCConstantExpr::Create(CRNum, getContext());
1536
1537   Parser.Lex();
1538   SMLoc E = Parser.getTok().getLoc();
1539
1540   Operands.push_back(AArch64Operand::CreateImm(CRImm, S, E));
1541   return MatchOperand_Success;
1542 }
1543
1544 AArch64AsmParser::OperandMatchResultTy
1545 AArch64AsmParser::ParseFPImmOperand(
1546                                SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1547
1548   // FIXME?: I want to live in a world where immediates must start with
1549   // #. Please don't dash my hopes (well, do if you have a good reason).
1550   if (Parser.getTok().isNot(AsmToken::Hash)) return MatchOperand_NoMatch;
1551
1552   SMLoc S = Parser.getTok().getLoc();
1553   Parser.Lex(); // Eat '#'
1554
1555   bool Negative = false;
1556   if (Parser.getTok().is(AsmToken::Minus)) {
1557     Negative = true;
1558     Parser.Lex(); // Eat '-'
1559   } else if (Parser.getTok().is(AsmToken::Plus)) {
1560     Parser.Lex(); // Eat '+'
1561   }
1562
1563   if (Parser.getTok().isNot(AsmToken::Real)) {
1564     Error(S, "Expected floating-point immediate");
1565     return MatchOperand_ParseFail;
1566   }
1567
1568   APFloat RealVal(APFloat::IEEEdouble, Parser.getTok().getString());
1569   if (Negative) RealVal.changeSign();
1570   double DblVal = RealVal.convertToDouble();
1571
1572   Parser.Lex(); // Eat real number
1573   SMLoc E = Parser.getTok().getLoc();
1574
1575   Operands.push_back(AArch64Operand::CreateFPImm(DblVal, S, E));
1576   return MatchOperand_Success;
1577 }
1578
1579
1580 // Automatically generated
1581 static unsigned MatchRegisterName(StringRef Name);
1582
1583 bool
1584 AArch64AsmParser::IdentifyRegister(unsigned &RegNum, SMLoc &RegEndLoc,
1585                                    StringRef &Layout,
1586                                    SMLoc &LayoutLoc) const {
1587   const AsmToken &Tok = Parser.getTok();
1588
1589   if (Tok.isNot(AsmToken::Identifier))
1590     return false;
1591
1592   std::string LowerReg = Tok.getString().lower();
1593   size_t DotPos = LowerReg.find('.');
1594
1595   bool IsVec128 = false;
1596   SMLoc S = Tok.getLoc();
1597   RegEndLoc = SMLoc::getFromPointer(S.getPointer() + DotPos);
1598
1599   if (DotPos == std::string::npos) {
1600     Layout = StringRef();
1601   } else {
1602     // Everything afterwards needs to be a literal token, expected to be
1603     // '.2d','.b' etc for vector registers.
1604
1605     // This StringSwitch validates the input and (perhaps more importantly)
1606     // gives us a permanent string to use in the token (a pointer into LowerReg
1607     // would go out of scope when we return).
1608     LayoutLoc = SMLoc::getFromPointer(S.getPointer() + DotPos + 1);
1609     std::string LayoutText = LowerReg.substr(DotPos, StringRef::npos);
1610
1611     // See if it's a 128-bit layout first.
1612     Layout = StringSwitch<const char *>(LayoutText)
1613       .Case(".d", ".d").Case(".2d", ".2d")
1614       .Case(".s", ".s").Case(".4s", ".4s")
1615       .Case(".h", ".h").Case(".8h", ".8h")
1616       .Case(".b", ".b").Case(".16b", ".16b")
1617       .Default("");
1618
1619     if (Layout.size() != 0)
1620       IsVec128 = true;
1621     else {
1622       Layout = StringSwitch<const char *>(LayoutText)
1623                    .Case(".1d", ".1d")
1624                    .Case(".2s", ".2s")
1625                    .Case(".4h", ".4h")
1626                    .Case(".8b", ".8b")
1627                    .Default("");
1628     }
1629
1630     if (Layout.size() == 0) {
1631       // If we've still not pinned it down the register is malformed.
1632       return false;
1633     }
1634   }
1635
1636   RegNum = MatchRegisterName(LowerReg.substr(0, DotPos));
1637   if (RegNum == AArch64::NoRegister) {
1638     RegNum = StringSwitch<unsigned>(LowerReg.substr(0, DotPos))
1639       .Case("ip0", AArch64::X16)
1640       .Case("ip1", AArch64::X17)
1641       .Case("fp", AArch64::X29)
1642       .Case("lr", AArch64::X30)
1643       .Case("v0", IsVec128 ? AArch64::Q0 : AArch64::D0)
1644       .Case("v1", IsVec128 ? AArch64::Q1 : AArch64::D1)
1645       .Case("v2", IsVec128 ? AArch64::Q2 : AArch64::D2)
1646       .Case("v3", IsVec128 ? AArch64::Q3 : AArch64::D3)
1647       .Case("v4", IsVec128 ? AArch64::Q4 : AArch64::D4)
1648       .Case("v5", IsVec128 ? AArch64::Q5 : AArch64::D5)
1649       .Case("v6", IsVec128 ? AArch64::Q6 : AArch64::D6)
1650       .Case("v7", IsVec128 ? AArch64::Q7 : AArch64::D7)
1651       .Case("v8", IsVec128 ? AArch64::Q8 : AArch64::D8)
1652       .Case("v9", IsVec128 ? AArch64::Q9 : AArch64::D9)
1653       .Case("v10", IsVec128 ? AArch64::Q10 : AArch64::D10)
1654       .Case("v11", IsVec128 ? AArch64::Q11 : AArch64::D11)
1655       .Case("v12", IsVec128 ? AArch64::Q12 : AArch64::D12)
1656       .Case("v13", IsVec128 ? AArch64::Q13 : AArch64::D13)
1657       .Case("v14", IsVec128 ? AArch64::Q14 : AArch64::D14)
1658       .Case("v15", IsVec128 ? AArch64::Q15 : AArch64::D15)
1659       .Case("v16", IsVec128 ? AArch64::Q16 : AArch64::D16)
1660       .Case("v17", IsVec128 ? AArch64::Q17 : AArch64::D17)
1661       .Case("v18", IsVec128 ? AArch64::Q18 : AArch64::D18)
1662       .Case("v19", IsVec128 ? AArch64::Q19 : AArch64::D19)
1663       .Case("v20", IsVec128 ? AArch64::Q20 : AArch64::D20)
1664       .Case("v21", IsVec128 ? AArch64::Q21 : AArch64::D21)
1665       .Case("v22", IsVec128 ? AArch64::Q22 : AArch64::D22)
1666       .Case("v23", IsVec128 ? AArch64::Q23 : AArch64::D23)
1667       .Case("v24", IsVec128 ? AArch64::Q24 : AArch64::D24)
1668       .Case("v25", IsVec128 ? AArch64::Q25 : AArch64::D25)
1669       .Case("v26", IsVec128 ? AArch64::Q26 : AArch64::D26)
1670       .Case("v27", IsVec128 ? AArch64::Q27 : AArch64::D27)
1671       .Case("v28", IsVec128 ? AArch64::Q28 : AArch64::D28)
1672       .Case("v29", IsVec128 ? AArch64::Q29 : AArch64::D29)
1673       .Case("v30", IsVec128 ? AArch64::Q30 : AArch64::D30)
1674       .Case("v31", IsVec128 ? AArch64::Q31 : AArch64::D31)
1675       .Default(AArch64::NoRegister);
1676   }
1677   if (RegNum == AArch64::NoRegister)
1678     return false;
1679
1680   return true;
1681 }
1682
1683 AArch64AsmParser::OperandMatchResultTy
1684 AArch64AsmParser::ParseRegister(SmallVectorImpl<MCParsedAsmOperand*> &Operands,
1685                                 uint32_t &NumLanes) {
1686   unsigned RegNum;
1687   StringRef Layout;
1688   SMLoc RegEndLoc, LayoutLoc;
1689   SMLoc S = Parser.getTok().getLoc();
1690
1691   if (!IdentifyRegister(RegNum, RegEndLoc, Layout, LayoutLoc))
1692     return MatchOperand_NoMatch;
1693
1694   Operands.push_back(AArch64Operand::CreateReg(RegNum, S, RegEndLoc));
1695
1696   if (Layout.size() != 0) {
1697     unsigned long long TmpLanes = 0;
1698     llvm::getAsUnsignedInteger(Layout.substr(1), 10, TmpLanes);
1699     if (TmpLanes != 0) {
1700       NumLanes = TmpLanes;
1701     } else {
1702       // If the number of lanes isn't specified explicitly, a valid instruction
1703       // will have an element specifier and be capable of acting on the entire
1704       // vector register.
1705       switch (Layout.back()) {
1706       default: llvm_unreachable("Invalid layout specifier");
1707       case 'b': NumLanes = 16; break;
1708       case 'h': NumLanes = 8; break;
1709       case 's': NumLanes = 4; break;
1710       case 'd': NumLanes = 2; break;
1711       }
1712     }
1713
1714     Operands.push_back(AArch64Operand::CreateToken(Layout, LayoutLoc));
1715   }
1716
1717   Parser.Lex();
1718   return MatchOperand_Success;
1719 }
1720
1721 bool
1722 AArch64AsmParser::ParseRegister(unsigned &RegNo, SMLoc &StartLoc,
1723                                 SMLoc &EndLoc) {
1724   // This callback is used for things like DWARF frame directives in
1725   // assembly. They don't care about things like NEON layouts or lanes, they
1726   // just want to be able to produce the DWARF register number.
1727   StringRef LayoutSpec;
1728   SMLoc RegEndLoc, LayoutLoc;
1729   StartLoc = Parser.getTok().getLoc();
1730
1731   if (!IdentifyRegister(RegNo, RegEndLoc, LayoutSpec, LayoutLoc))
1732     return true;
1733
1734   Parser.Lex();
1735   EndLoc = Parser.getTok().getLoc();
1736
1737   return false;
1738 }
1739
1740 AArch64AsmParser::OperandMatchResultTy
1741 AArch64AsmParser::ParseNamedImmOperand(const NamedImmMapper &Mapper,
1742                                SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1743   // Since these operands occur in very limited circumstances, without
1744   // alternatives, we actually signal an error if there is no match. If relaxing
1745   // this, beware of unintended consequences: an immediate will be accepted
1746   // during matching, no matter how it gets into the AArch64Operand.
1747   const AsmToken &Tok = Parser.getTok();
1748   SMLoc S = Tok.getLoc();
1749
1750   if (Tok.is(AsmToken::Identifier)) {
1751     bool ValidName;
1752     uint32_t Code = Mapper.fromString(Tok.getString().lower(), ValidName);
1753
1754     if (!ValidName) {
1755       Error(S, "operand specifier not recognised");
1756       return MatchOperand_ParseFail;
1757     }
1758
1759     Parser.Lex(); // We're done with the identifier. Eat it
1760
1761     SMLoc E = Parser.getTok().getLoc();
1762     const MCExpr *Imm = MCConstantExpr::Create(Code, getContext());
1763     Operands.push_back(AArch64Operand::CreateImm(Imm, S, E));
1764     return MatchOperand_Success;
1765   } else if (Tok.is(AsmToken::Hash)) {
1766     Parser.Lex();
1767
1768     const MCExpr *ImmVal;
1769     if (ParseImmediate(ImmVal) != MatchOperand_Success)
1770       return MatchOperand_ParseFail;
1771
1772     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ImmVal);
1773     if (!CE || CE->getValue() < 0 || !Mapper.validImm(CE->getValue())) {
1774       Error(S, "Invalid immediate for instruction");
1775       return MatchOperand_ParseFail;
1776     }
1777
1778     SMLoc E = Parser.getTok().getLoc();
1779     Operands.push_back(AArch64Operand::CreateImm(ImmVal, S, E));
1780     return MatchOperand_Success;
1781   }
1782
1783   Error(S, "unexpected operand for instruction");
1784   return MatchOperand_ParseFail;
1785 }
1786
1787 AArch64AsmParser::OperandMatchResultTy
1788 AArch64AsmParser::ParseSysRegOperand(
1789                                SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1790   const AsmToken &Tok = Parser.getTok();
1791
1792   // Any MSR/MRS operand will be an identifier, and we want to store it as some
1793   // kind of string: SPSel is valid for two different forms of MSR with two
1794   // different encodings. There's no collision at the moment, but the potential
1795   // is there.
1796   if (!Tok.is(AsmToken::Identifier)) {
1797     return MatchOperand_NoMatch;
1798   }
1799
1800   SMLoc S = Tok.getLoc();
1801   Operands.push_back(AArch64Operand::CreateSysReg(Tok.getString(), S));
1802   Parser.Lex(); // Eat identifier
1803
1804   return MatchOperand_Success;
1805 }
1806
1807 AArch64AsmParser::OperandMatchResultTy
1808 AArch64AsmParser::ParseLSXAddressOperand(
1809                                SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1810   SMLoc S = Parser.getTok().getLoc();
1811
1812   unsigned RegNum;
1813   SMLoc RegEndLoc, LayoutLoc;
1814   StringRef Layout;
1815   if(!IdentifyRegister(RegNum, RegEndLoc, Layout, LayoutLoc)
1816      || !AArch64MCRegisterClasses[AArch64::GPR64xspRegClassID].contains(RegNum)
1817      || Layout.size() != 0) {
1818     // Check Layout.size because we don't want to let "x3.4s" or similar
1819     // through.
1820     return MatchOperand_NoMatch;
1821   }
1822   Parser.Lex(); // Eat register
1823
1824   if (Parser.getTok().is(AsmToken::RBrac)) {
1825     // We're done
1826     SMLoc E = Parser.getTok().getLoc();
1827     Operands.push_back(AArch64Operand::CreateWrappedReg(RegNum, S, E));
1828     return MatchOperand_Success;
1829   }
1830
1831   // Otherwise, only ", #0" is valid
1832
1833   if (Parser.getTok().isNot(AsmToken::Comma)) {
1834     Error(Parser.getTok().getLoc(), "expected ',' or ']' after register");
1835     return MatchOperand_ParseFail;
1836   }
1837   Parser.Lex(); // Eat ','
1838
1839   if (Parser.getTok().isNot(AsmToken::Hash)) {
1840     Error(Parser.getTok().getLoc(), "expected '#0'");
1841     return MatchOperand_ParseFail;
1842   }
1843   Parser.Lex(); // Eat '#'
1844
1845   if (Parser.getTok().isNot(AsmToken::Integer)
1846       || Parser.getTok().getIntVal() != 0 ) {
1847     Error(Parser.getTok().getLoc(), "expected '#0'");
1848     return MatchOperand_ParseFail;
1849   }
1850   Parser.Lex(); // Eat '0'
1851
1852   SMLoc E = Parser.getTok().getLoc();
1853   Operands.push_back(AArch64Operand::CreateWrappedReg(RegNum, S, E));
1854   return MatchOperand_Success;
1855 }
1856
1857 AArch64AsmParser::OperandMatchResultTy
1858 AArch64AsmParser::ParseShiftExtend(
1859                                SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1860   StringRef IDVal = Parser.getTok().getIdentifier();
1861   std::string LowerID = IDVal.lower();
1862
1863   A64SE::ShiftExtSpecifiers Spec =
1864       StringSwitch<A64SE::ShiftExtSpecifiers>(LowerID)
1865         .Case("lsl", A64SE::LSL)
1866         .Case("msl", A64SE::MSL)
1867         .Case("lsr", A64SE::LSR)
1868         .Case("asr", A64SE::ASR)
1869         .Case("ror", A64SE::ROR)
1870         .Case("uxtb", A64SE::UXTB)
1871         .Case("uxth", A64SE::UXTH)
1872         .Case("uxtw", A64SE::UXTW)
1873         .Case("uxtx", A64SE::UXTX)
1874         .Case("sxtb", A64SE::SXTB)
1875         .Case("sxth", A64SE::SXTH)
1876         .Case("sxtw", A64SE::SXTW)
1877         .Case("sxtx", A64SE::SXTX)
1878         .Default(A64SE::Invalid);
1879
1880   if (Spec == A64SE::Invalid)
1881     return MatchOperand_NoMatch;
1882
1883   // Eat the shift
1884   SMLoc S, E;
1885   S = Parser.getTok().getLoc();
1886   Parser.Lex();
1887
1888   if (Spec != A64SE::LSL && Spec != A64SE::LSR && Spec != A64SE::ASR &&
1889       Spec != A64SE::ROR && Spec != A64SE::MSL) {
1890     // The shift amount can be omitted for the extending versions, but not real
1891     // shifts:
1892     //     add x0, x0, x0, uxtb
1893     // is valid, and equivalent to
1894     //     add x0, x0, x0, uxtb #0
1895
1896     if (Parser.getTok().is(AsmToken::Comma) ||
1897         Parser.getTok().is(AsmToken::EndOfStatement) ||
1898         Parser.getTok().is(AsmToken::RBrac)) {
1899       Operands.push_back(AArch64Operand::CreateShiftExtend(Spec, 0, true,
1900                                                            S, E));
1901       return MatchOperand_Success;
1902     }
1903   }
1904
1905   // Eat # at beginning of immediate
1906   if (!Parser.getTok().is(AsmToken::Hash)) {
1907     Error(Parser.getTok().getLoc(),
1908           "expected #imm after shift specifier");
1909     return MatchOperand_ParseFail;
1910   }
1911   Parser.Lex();
1912
1913   // Make sure we do actually have a number
1914   if (!Parser.getTok().is(AsmToken::Integer)) {
1915     Error(Parser.getTok().getLoc(),
1916           "expected integer shift amount");
1917     return MatchOperand_ParseFail;
1918   }
1919   unsigned Amount = Parser.getTok().getIntVal();
1920   Parser.Lex();
1921   E = Parser.getTok().getLoc();
1922
1923   Operands.push_back(AArch64Operand::CreateShiftExtend(Spec, Amount, false,
1924                                                        S, E));
1925
1926   return MatchOperand_Success;
1927 }
1928
1929 /// Try to parse a vector register token, If it is a vector register,
1930 /// the token is eaten and return true. Otherwise return false.
1931 bool AArch64AsmParser::TryParseVector(uint32_t &RegNum, SMLoc &RegEndLoc,
1932                                       StringRef &Layout, SMLoc &LayoutLoc) {
1933   bool IsVector = true;
1934
1935   if (!IdentifyRegister(RegNum, RegEndLoc, Layout, LayoutLoc))
1936     IsVector = false;
1937
1938   if (!AArch64MCRegisterClasses[AArch64::FPR64RegClassID].contains(RegNum) &&
1939       !AArch64MCRegisterClasses[AArch64::FPR128RegClassID].contains(RegNum))
1940     IsVector = false;
1941
1942   if (Layout.size() == 0)
1943     IsVector = false;
1944
1945   if (!IsVector)
1946     Error(Parser.getTok().getLoc(), "expected vector type register");
1947
1948   Parser.Lex(); // Eat this token.
1949   return IsVector;
1950 }
1951
1952
1953 // A vector list contains 1-4 consecutive registers.
1954 // Now there are two kinds of vector list when number of vector > 1:
1955 //   (1) {Vn.layout, Vn+1.layout, ... , Vm.layout}
1956 //   (2) {Vn.layout - Vm.layout}
1957 AArch64AsmParser::OperandMatchResultTy AArch64AsmParser::ParseVectorList(
1958     SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
1959   if (Parser.getTok().isNot(AsmToken::LCurly)) {
1960     Error(Parser.getTok().getLoc(), "'{' expected");
1961     return MatchOperand_ParseFail;
1962   }
1963   SMLoc SLoc = Parser.getTok().getLoc();
1964   Parser.Lex(); // Eat '{' token.
1965
1966   unsigned Reg, Count = 1;
1967   StringRef LayoutStr;
1968   SMLoc RegEndLoc, LayoutLoc;
1969   if (!TryParseVector(Reg, RegEndLoc, LayoutStr, LayoutLoc))
1970     return MatchOperand_ParseFail;
1971
1972   if (Parser.getTok().is(AsmToken::Minus)) {
1973     Parser.Lex(); // Eat the minus.
1974
1975     unsigned Reg2;
1976     StringRef LayoutStr2;
1977     SMLoc RegEndLoc2, LayoutLoc2;
1978     SMLoc RegLoc2 = Parser.getTok().getLoc();
1979
1980     if (!TryParseVector(Reg2, RegEndLoc2, LayoutStr2, LayoutLoc2))
1981       return MatchOperand_ParseFail;
1982     unsigned Space = (Reg < Reg2) ? (Reg2 - Reg) : (Reg2 + 32 - Reg);
1983
1984     if (LayoutStr != LayoutStr2) {
1985       Error(LayoutLoc2, "expected the same vector layout");
1986       return MatchOperand_ParseFail;
1987     }
1988     if (Space == 0 || Space > 3) {
1989       Error(RegLoc2, "invalid number of vectors");
1990       return MatchOperand_ParseFail;
1991     }
1992
1993     Count += Space;
1994   } else {
1995     unsigned LastReg = Reg;
1996     while (Parser.getTok().is(AsmToken::Comma)) {
1997       Parser.Lex(); // Eat the comma.
1998       unsigned Reg2;
1999       StringRef LayoutStr2;
2000       SMLoc RegEndLoc2, LayoutLoc2;
2001       SMLoc RegLoc2 = Parser.getTok().getLoc();
2002
2003       if (!TryParseVector(Reg2, RegEndLoc2, LayoutStr2, LayoutLoc2))
2004         return MatchOperand_ParseFail;
2005       unsigned Space = (LastReg < Reg2) ? (Reg2 - LastReg)
2006                                         : (Reg2 + 32 - LastReg);
2007       Count++;
2008
2009       // The space between two vectors should be 1. And they should have the same layout.
2010       // Total count shouldn't be great than 4
2011       if (Space != 1) {
2012         Error(RegLoc2, "invalid space between two vectors");
2013         return MatchOperand_ParseFail;
2014       }
2015       if (LayoutStr != LayoutStr2) {
2016         Error(LayoutLoc2, "expected the same vector layout");
2017         return MatchOperand_ParseFail;
2018       }
2019       if (Count > 4) {
2020         Error(RegLoc2, "invalid number of vectors");
2021         return MatchOperand_ParseFail;
2022       }
2023
2024       LastReg = Reg2;
2025     }
2026   }
2027
2028   if (Parser.getTok().isNot(AsmToken::RCurly)) {
2029     Error(Parser.getTok().getLoc(), "'}' expected");
2030     return MatchOperand_ParseFail;
2031   }
2032   SMLoc ELoc = Parser.getTok().getLoc();
2033   Parser.Lex(); // Eat '}' token.
2034
2035   A64Layout::VectorLayout Layout = A64StringToVectorLayout(LayoutStr);
2036   if (Count > 1) { // If count > 1, create vector list using super register.
2037     bool IsVec64 = (Layout < A64Layout::_16B) ? true : false;
2038     static unsigned SupRegIDs[3][2] = {
2039       { AArch64::QPairRegClassID, AArch64::DPairRegClassID },
2040       { AArch64::QTripleRegClassID, AArch64::DTripleRegClassID },
2041       { AArch64::QQuadRegClassID, AArch64::DQuadRegClassID }
2042     };
2043     unsigned SupRegID = SupRegIDs[Count - 2][static_cast<int>(IsVec64)];
2044     unsigned Sub0 = IsVec64 ? AArch64::dsub_0 : AArch64::qsub_0;
2045     const MCRegisterInfo *MRI = getContext().getRegisterInfo();
2046     Reg = MRI->getMatchingSuperReg(Reg, Sub0,
2047                                    &AArch64MCRegisterClasses[SupRegID]);
2048   }
2049   Operands.push_back(
2050       AArch64Operand::CreateVectorList(Reg, Count, Layout, SLoc, ELoc));
2051
2052   return MatchOperand_Success;
2053 }
2054
2055 // FIXME: We would really like to be able to tablegen'erate this.
2056 bool AArch64AsmParser::
2057 validateInstruction(MCInst &Inst,
2058                     const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2059   switch (Inst.getOpcode()) {
2060   case AArch64::BFIwwii:
2061   case AArch64::BFIxxii:
2062   case AArch64::SBFIZwwii:
2063   case AArch64::SBFIZxxii:
2064   case AArch64::UBFIZwwii:
2065   case AArch64::UBFIZxxii:  {
2066     unsigned ImmOps = Inst.getNumOperands() - 2;
2067     int64_t ImmR = Inst.getOperand(ImmOps).getImm();
2068     int64_t ImmS = Inst.getOperand(ImmOps+1).getImm();
2069
2070     if (ImmR != 0 && ImmS >= ImmR) {
2071       return Error(Operands[4]->getStartLoc(),
2072                    "requested insert overflows register");
2073     }
2074     return false;
2075   }
2076   case AArch64::BFXILwwii:
2077   case AArch64::BFXILxxii:
2078   case AArch64::SBFXwwii:
2079   case AArch64::SBFXxxii:
2080   case AArch64::UBFXwwii:
2081   case AArch64::UBFXxxii: {
2082     unsigned ImmOps = Inst.getNumOperands() - 2;
2083     int64_t ImmR = Inst.getOperand(ImmOps).getImm();
2084     int64_t ImmS = Inst.getOperand(ImmOps+1).getImm();
2085     int64_t RegWidth = 0;
2086     switch (Inst.getOpcode()) {
2087     case AArch64::SBFXxxii: case AArch64::UBFXxxii: case AArch64::BFXILxxii:
2088       RegWidth = 64;
2089       break;
2090     case AArch64::SBFXwwii: case AArch64::UBFXwwii: case AArch64::BFXILwwii:
2091       RegWidth = 32;
2092       break;
2093     }
2094
2095     if (ImmS >= RegWidth || ImmS < ImmR) {
2096       return Error(Operands[4]->getStartLoc(),
2097                    "requested extract overflows register");
2098     }
2099     return false;
2100   }
2101   case AArch64::ICix: {
2102     int64_t ImmVal = Inst.getOperand(0).getImm();
2103     A64IC::ICValues ICOp = static_cast<A64IC::ICValues>(ImmVal);
2104     if (!A64IC::NeedsRegister(ICOp)) {
2105       return Error(Operands[1]->getStartLoc(),
2106                    "specified IC op does not use a register");
2107     }
2108     return false;
2109   }
2110   case AArch64::ICi: {
2111     int64_t ImmVal = Inst.getOperand(0).getImm();
2112     A64IC::ICValues ICOp = static_cast<A64IC::ICValues>(ImmVal);
2113     if (A64IC::NeedsRegister(ICOp)) {
2114       return Error(Operands[1]->getStartLoc(),
2115                    "specified IC op requires a register");
2116     }
2117     return false;
2118   }
2119   case AArch64::TLBIix: {
2120     int64_t ImmVal = Inst.getOperand(0).getImm();
2121     A64TLBI::TLBIValues TLBIOp = static_cast<A64TLBI::TLBIValues>(ImmVal);
2122     if (!A64TLBI::NeedsRegister(TLBIOp)) {
2123       return Error(Operands[1]->getStartLoc(),
2124                    "specified TLBI op does not use a register");
2125     }
2126     return false;
2127   }
2128   case AArch64::TLBIi: {
2129     int64_t ImmVal = Inst.getOperand(0).getImm();
2130     A64TLBI::TLBIValues TLBIOp = static_cast<A64TLBI::TLBIValues>(ImmVal);
2131     if (A64TLBI::NeedsRegister(TLBIOp)) {
2132       return Error(Operands[1]->getStartLoc(),
2133                    "specified TLBI op requires a register");
2134     }
2135     return false;
2136   }
2137   }
2138
2139   return false;
2140 }
2141
2142
2143 // Parses the instruction *together with* all operands, appending each parsed
2144 // operand to the "Operands" list
2145 bool AArch64AsmParser::ParseInstruction(ParseInstructionInfo &Info,
2146                                         StringRef Name, SMLoc NameLoc,
2147                                SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2148   size_t CondCodePos = Name.find('.');
2149
2150   StringRef Mnemonic = Name.substr(0, CondCodePos);
2151   Operands.push_back(AArch64Operand::CreateToken(Mnemonic, NameLoc));
2152
2153   if (CondCodePos != StringRef::npos) {
2154     // We have a condition code
2155     SMLoc S = SMLoc::getFromPointer(NameLoc.getPointer() + CondCodePos + 1);
2156     StringRef CondStr = Name.substr(CondCodePos + 1, StringRef::npos);
2157     A64CC::CondCodes Code;
2158
2159     Code = A64StringToCondCode(CondStr);
2160
2161     if (Code == A64CC::Invalid) {
2162       Error(S, "invalid condition code");
2163       Parser.eatToEndOfStatement();
2164       return true;
2165     }
2166
2167     SMLoc DotL = SMLoc::getFromPointer(NameLoc.getPointer() + CondCodePos);
2168
2169     Operands.push_back(AArch64Operand::CreateToken(".",  DotL));
2170     SMLoc E = SMLoc::getFromPointer(NameLoc.getPointer() + CondCodePos + 3);
2171     Operands.push_back(AArch64Operand::CreateCondCode(Code, S, E));
2172   }
2173
2174   // Now we parse the operands of this instruction
2175   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2176     // Read the first operand.
2177     if (ParseOperand(Operands, Mnemonic)) {
2178       Parser.eatToEndOfStatement();
2179       return true;
2180     }
2181
2182     while (getLexer().is(AsmToken::Comma)) {
2183       Parser.Lex();  // Eat the comma.
2184
2185       // Parse and remember the operand.
2186       if (ParseOperand(Operands, Mnemonic)) {
2187         Parser.eatToEndOfStatement();
2188         return true;
2189       }
2190
2191
2192       // After successfully parsing some operands there are two special cases to
2193       // consider (i.e. notional operands not separated by commas). Both are due
2194       // to memory specifiers:
2195       //  + An RBrac will end an address for load/store/prefetch
2196       //  + An '!' will indicate a pre-indexed operation.
2197       //
2198       // It's someone else's responsibility to make sure these tokens are sane
2199       // in the given context!
2200       if (Parser.getTok().is(AsmToken::RBrac)) {
2201         SMLoc Loc = Parser.getTok().getLoc();
2202         Operands.push_back(AArch64Operand::CreateToken("]", Loc));
2203         Parser.Lex();
2204       }
2205
2206       if (Parser.getTok().is(AsmToken::Exclaim)) {
2207         SMLoc Loc = Parser.getTok().getLoc();
2208         Operands.push_back(AArch64Operand::CreateToken("!", Loc));
2209         Parser.Lex();
2210       }
2211     }
2212   }
2213
2214   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2215     SMLoc Loc = getLexer().getLoc();
2216     Parser.eatToEndOfStatement();
2217     return Error(Loc, "expected comma before next operand");
2218   }
2219
2220   // Eat the EndOfStatement
2221   Parser.Lex();
2222
2223   return false;
2224 }
2225
2226 bool AArch64AsmParser::ParseDirective(AsmToken DirectiveID) {
2227   StringRef IDVal = DirectiveID.getIdentifier();
2228   if (IDVal == ".hword")
2229     return ParseDirectiveWord(2, DirectiveID.getLoc());
2230   else if (IDVal == ".word")
2231     return ParseDirectiveWord(4, DirectiveID.getLoc());
2232   else if (IDVal == ".xword")
2233     return ParseDirectiveWord(8, DirectiveID.getLoc());
2234   else if (IDVal == ".tlsdesccall")
2235     return ParseDirectiveTLSDescCall(DirectiveID.getLoc());
2236
2237   return true;
2238 }
2239
2240 /// parseDirectiveWord
2241 ///  ::= .word [ expression (, expression)* ]
2242 bool AArch64AsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
2243   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2244     for (;;) {
2245       const MCExpr *Value;
2246       if (getParser().parseExpression(Value))
2247         return true;
2248
2249       getParser().getStreamer().EmitValue(Value, Size);
2250
2251       if (getLexer().is(AsmToken::EndOfStatement))
2252         break;
2253
2254       // FIXME: Improve diagnostic.
2255       if (getLexer().isNot(AsmToken::Comma))
2256         return Error(L, "unexpected token in directive");
2257       Parser.Lex();
2258     }
2259   }
2260
2261   Parser.Lex();
2262   return false;
2263 }
2264
2265 // parseDirectiveTLSDescCall:
2266 //   ::= .tlsdesccall symbol
2267 bool AArch64AsmParser::ParseDirectiveTLSDescCall(SMLoc L) {
2268   StringRef Name;
2269   if (getParser().parseIdentifier(Name))
2270     return Error(L, "expected symbol after directive");
2271
2272   MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2273   const MCSymbolRefExpr *Expr = MCSymbolRefExpr::Create(Sym, getContext());
2274
2275   MCInst Inst;
2276   Inst.setOpcode(AArch64::TLSDESCCALL);
2277   Inst.addOperand(MCOperand::CreateExpr(Expr));
2278
2279   getParser().getStreamer().EmitInstruction(Inst);
2280   return false;
2281 }
2282
2283
2284 bool AArch64AsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
2285                                  SmallVectorImpl<MCParsedAsmOperand*> &Operands,
2286                                  MCStreamer &Out, unsigned &ErrorInfo,
2287                                  bool MatchingInlineAsm) {
2288   MCInst Inst;
2289   unsigned MatchResult;
2290   MatchResult = MatchInstructionImpl(Operands, Inst, ErrorInfo,
2291                                      MatchingInlineAsm);
2292
2293   if (ErrorInfo != ~0U && ErrorInfo >= Operands.size())
2294     return Error(IDLoc, "too few operands for instruction");
2295
2296   switch (MatchResult) {
2297   default: break;
2298   case Match_Success:
2299     if (validateInstruction(Inst, Operands))
2300       return true;
2301
2302     Out.EmitInstruction(Inst);
2303     return false;
2304   case Match_MissingFeature:
2305     Error(IDLoc, "instruction requires a CPU feature not currently enabled");
2306     return true;
2307   case Match_InvalidOperand: {
2308     SMLoc ErrorLoc = IDLoc;
2309     if (ErrorInfo != ~0U) {
2310       ErrorLoc = ((AArch64Operand*)Operands[ErrorInfo])->getStartLoc();
2311       if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
2312     }
2313
2314     return Error(ErrorLoc, "invalid operand for instruction");
2315   }
2316   case Match_MnemonicFail:
2317     return Error(IDLoc, "invalid instruction");
2318
2319   case Match_AddSubRegExtendSmall:
2320     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2321       "expected '[su]xt[bhw]' or 'lsl' with optional integer in range [0, 4]");
2322   case Match_AddSubRegExtendLarge:
2323     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2324       "expected 'sxtx' 'uxtx' or 'lsl' with optional integer in range [0, 4]");
2325   case Match_AddSubRegShift32:
2326     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2327        "expected 'lsl', 'lsr' or 'asr' with optional integer in range [0, 31]");
2328   case Match_AddSubRegShift64:
2329     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2330        "expected 'lsl', 'lsr' or 'asr' with optional integer in range [0, 63]");
2331   case Match_AddSubSecondSource:
2332       return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2333           "expected compatible register, symbol or integer in range [0, 4095]");
2334   case Match_CVTFixedPos32:
2335     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2336                  "expected integer in range [1, 32]");
2337   case Match_CVTFixedPos64:
2338     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2339                  "expected integer in range [1, 64]");
2340   case Match_CondCode:
2341     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2342                  "expected AArch64 condition code");
2343   case Match_FPImm:
2344     // Any situation which allows a nontrivial floating-point constant also
2345     // allows a register.
2346     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2347                  "expected compatible register or floating-point constant");
2348   case Match_FPZero:
2349     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2350                  "expected floating-point constant #0.0 or invalid register type");
2351   case Match_Label:
2352     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2353                  "expected label or encodable integer pc offset");
2354   case Match_Lane1:
2355     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2356                  "expected lane specifier '[1]'");
2357   case Match_LoadStoreExtend32_1:
2358     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2359                  "expected 'uxtw' or 'sxtw' with optional shift of #0");
2360   case Match_LoadStoreExtend32_2:
2361     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2362                  "expected 'uxtw' or 'sxtw' with optional shift of #0 or #1");
2363   case Match_LoadStoreExtend32_4:
2364     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2365                  "expected 'uxtw' or 'sxtw' with optional shift of #0 or #2");
2366   case Match_LoadStoreExtend32_8:
2367     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2368                  "expected 'uxtw' or 'sxtw' with optional shift of #0 or #3");
2369   case Match_LoadStoreExtend32_16:
2370     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2371                  "expected 'lsl' or 'sxtw' with optional shift of #0 or #4");
2372   case Match_LoadStoreExtend64_1:
2373     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2374                  "expected 'lsl' or 'sxtx' with optional shift of #0");
2375   case Match_LoadStoreExtend64_2:
2376     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2377                  "expected 'lsl' or 'sxtx' with optional shift of #0 or #1");
2378   case Match_LoadStoreExtend64_4:
2379     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2380                  "expected 'lsl' or 'sxtx' with optional shift of #0 or #2");
2381   case Match_LoadStoreExtend64_8:
2382     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2383                  "expected 'lsl' or 'sxtx' with optional shift of #0 or #3");
2384   case Match_LoadStoreExtend64_16:
2385     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2386                  "expected 'lsl' or 'sxtx' with optional shift of #0 or #4");
2387   case Match_LoadStoreSImm7_4:
2388     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2389                  "expected integer multiple of 4 in range [-256, 252]");
2390   case Match_LoadStoreSImm7_8:
2391     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2392                  "expected integer multiple of 8 in range [-512, 508]");
2393   case Match_LoadStoreSImm7_16:
2394     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2395                  "expected integer multiple of 16 in range [-1024, 1016]");
2396   case Match_LoadStoreSImm9:
2397     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2398                  "expected integer in range [-256, 255]");
2399   case Match_LoadStoreUImm12_1:
2400     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2401                  "expected symbolic reference or integer in range [0, 4095]");
2402   case Match_LoadStoreUImm12_2:
2403     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2404                  "expected symbolic reference or integer in range [0, 8190]");
2405   case Match_LoadStoreUImm12_4:
2406     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2407                  "expected symbolic reference or integer in range [0, 16380]");
2408   case Match_LoadStoreUImm12_8:
2409     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2410                  "expected symbolic reference or integer in range [0, 32760]");
2411   case Match_LoadStoreUImm12_16:
2412     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2413                  "expected symbolic reference or integer in range [0, 65520]");
2414   case Match_LogicalSecondSource:
2415     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2416                  "expected compatible register or logical immediate");
2417   case Match_MOVWUImm16:
2418     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2419                  "expected relocated symbol or integer in range [0, 65535]");
2420   case Match_MRS:
2421     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2422                  "expected readable system register");
2423   case Match_MSR:
2424     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2425                  "expected writable system register or pstate");
2426   case Match_NamedImm_at:
2427     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2428                 "expected symbolic 'at' operand: s1e[0-3][rw] or s12e[01][rw]");
2429   case Match_NamedImm_dbarrier:
2430     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2431              "expected integer in range [0, 15] or symbolic barrier operand");
2432   case Match_NamedImm_dc:
2433     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2434                  "expected symbolic 'dc' operand");
2435   case Match_NamedImm_ic:
2436     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2437                  "expected 'ic' operand: 'ialluis', 'iallu' or 'ivau'");
2438   case Match_NamedImm_isb:
2439     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2440                  "expected integer in range [0, 15] or 'sy'");
2441   case Match_NamedImm_prefetch:
2442     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2443                  "expected prefetch hint: p(ld|st|i)l[123](strm|keep)");
2444   case Match_NamedImm_tlbi:
2445     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2446                  "expected translation buffer invalidation operand");
2447   case Match_UImm16:
2448     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2449                  "expected integer in range [0, 65535]");
2450   case Match_UImm3:
2451     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2452                  "expected integer in range [0, 7]");
2453   case Match_UImm4:
2454     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2455                  "expected integer in range [0, 15]");
2456   case Match_UImm5:
2457     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2458                  "expected integer in range [0, 31]");
2459   case Match_UImm6:
2460     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2461                  "expected integer in range [0, 63]");
2462   case Match_UImm7:
2463     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2464                  "expected integer in range [0, 127]");
2465   case Match_Width32:
2466     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2467                  "expected integer in range [<lsb>, 31]");
2468   case Match_Width64:
2469     return Error(((AArch64Operand*)Operands[ErrorInfo])->getStartLoc(),
2470                  "expected integer in range [<lsb>, 63]");
2471   case Match_ShrImm8:
2472     return Error(((AArch64Operand *)Operands[ErrorInfo])->getStartLoc(),
2473                  "expected integer in range [1, 8]");
2474   case Match_ShrImm16:
2475     return Error(((AArch64Operand *)Operands[ErrorInfo])->getStartLoc(),
2476                  "expected integer in range [1, 16]");
2477   case Match_ShrImm32:
2478     return Error(((AArch64Operand *)Operands[ErrorInfo])->getStartLoc(),
2479                  "expected integer in range [1, 32]");
2480   case Match_ShrImm64:
2481     return Error(((AArch64Operand *)Operands[ErrorInfo])->getStartLoc(),
2482                  "expected integer in range [1, 64]");
2483   }
2484
2485   llvm_unreachable("Implement any new match types added!");
2486   return true;
2487 }
2488
2489 void AArch64Operand::print(raw_ostream &OS) const {
2490   switch (Kind) {
2491   case k_CondCode:
2492     OS << "<CondCode: " << CondCode.Code << ">";
2493     break;
2494   case k_FPImmediate:
2495     OS << "<fpimm: " << FPImm.Val << ">";
2496     break;
2497   case k_ImmWithLSL:
2498     OS << "<immwithlsl: imm=" << ImmWithLSL.Val
2499        << ", shift=" << ImmWithLSL.ShiftAmount << ">";
2500     break;
2501   case k_Immediate:
2502     getImm()->print(OS);
2503     break;
2504   case k_Register:
2505     OS << "<register " << getReg() << '>';
2506     break;
2507   case k_Token:
2508     OS << '\'' << getToken() << '\'';
2509     break;
2510   case k_ShiftExtend:
2511     OS << "<shift: type=" << ShiftExtend.ShiftType
2512        << ", amount=" << ShiftExtend.Amount << ">";
2513     break;
2514   case k_SysReg: {
2515     StringRef Name(SysReg.Data, SysReg.Length);
2516     OS << "<sysreg: " << Name << '>';
2517     break;
2518   }
2519   default:
2520     llvm_unreachable("No idea how to print this kind of operand");
2521     break;
2522   }
2523 }
2524
2525 void AArch64Operand::dump() const {
2526   print(errs());
2527 }
2528
2529
2530 /// Force static initialization.
2531 extern "C" void LLVMInitializeAArch64AsmParser() {
2532   RegisterMCAsmParser<AArch64AsmParser> X(TheAArch64Target);
2533 }
2534
2535 #define GET_REGISTER_MATCHER
2536 #define GET_MATCHER_IMPLEMENTATION
2537 #include "AArch64GenAsmMatcher.inc"