Fix transformation of add with pc argument to adr for non-immediate
[oota-llvm.git] / lib / Target / ARM / AsmParser / ARMAsmParser.cpp
1 //===-- ARMAsmParser.cpp - Parse ARM assembly to MCInst instructions ------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "ARMFPUName.h"
11 #include "ARMFeatures.h"
12 #include "MCTargetDesc/ARMAddressingModes.h"
13 #include "MCTargetDesc/ARMArchName.h"
14 #include "MCTargetDesc/ARMBaseInfo.h"
15 #include "MCTargetDesc/ARMMCExpr.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/StringSwitch.h"
20 #include "llvm/ADT/Twine.h"
21 #include "llvm/MC/MCAsmInfo.h"
22 #include "llvm/MC/MCAssembler.h"
23 #include "llvm/MC/MCContext.h"
24 #include "llvm/MC/MCDisassembler.h"
25 #include "llvm/MC/MCELFStreamer.h"
26 #include "llvm/MC/MCExpr.h"
27 #include "llvm/MC/MCInst.h"
28 #include "llvm/MC/MCInstrDesc.h"
29 #include "llvm/MC/MCInstrInfo.h"
30 #include "llvm/MC/MCObjectFileInfo.h"
31 #include "llvm/MC/MCParser/MCAsmLexer.h"
32 #include "llvm/MC/MCParser/MCAsmParser.h"
33 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
34 #include "llvm/MC/MCRegisterInfo.h"
35 #include "llvm/MC/MCSection.h"
36 #include "llvm/MC/MCStreamer.h"
37 #include "llvm/MC/MCSubtargetInfo.h"
38 #include "llvm/MC/MCSymbol.h"
39 #include "llvm/MC/MCTargetAsmParser.h"
40 #include "llvm/Support/ARMBuildAttributes.h"
41 #include "llvm/Support/ARMEHABI.h"
42 #include "llvm/Support/COFF.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/ELF.h"
45 #include "llvm/Support/MathExtras.h"
46 #include "llvm/Support/SourceMgr.h"
47 #include "llvm/Support/TargetRegistry.h"
48 #include "llvm/Support/raw_ostream.h"
49
50 using namespace llvm;
51
52 namespace {
53
54 class ARMOperand;
55
56 enum VectorLaneTy { NoLanes, AllLanes, IndexedLane };
57
58 class UnwindContext {
59   MCAsmParser &Parser;
60
61   typedef SmallVector<SMLoc, 4> Locs;
62
63   Locs FnStartLocs;
64   Locs CantUnwindLocs;
65   Locs PersonalityLocs;
66   Locs PersonalityIndexLocs;
67   Locs HandlerDataLocs;
68   int FPReg;
69
70 public:
71   UnwindContext(MCAsmParser &P) : Parser(P), FPReg(ARM::SP) {}
72
73   bool hasFnStart() const { return !FnStartLocs.empty(); }
74   bool cantUnwind() const { return !CantUnwindLocs.empty(); }
75   bool hasHandlerData() const { return !HandlerDataLocs.empty(); }
76   bool hasPersonality() const {
77     return !(PersonalityLocs.empty() && PersonalityIndexLocs.empty());
78   }
79
80   void recordFnStart(SMLoc L) { FnStartLocs.push_back(L); }
81   void recordCantUnwind(SMLoc L) { CantUnwindLocs.push_back(L); }
82   void recordPersonality(SMLoc L) { PersonalityLocs.push_back(L); }
83   void recordHandlerData(SMLoc L) { HandlerDataLocs.push_back(L); }
84   void recordPersonalityIndex(SMLoc L) { PersonalityIndexLocs.push_back(L); }
85
86   void saveFPReg(int Reg) { FPReg = Reg; }
87   int getFPReg() const { return FPReg; }
88
89   void emitFnStartLocNotes() const {
90     for (Locs::const_iterator FI = FnStartLocs.begin(), FE = FnStartLocs.end();
91          FI != FE; ++FI)
92       Parser.Note(*FI, ".fnstart was specified here");
93   }
94   void emitCantUnwindLocNotes() const {
95     for (Locs::const_iterator UI = CantUnwindLocs.begin(),
96                               UE = CantUnwindLocs.end(); UI != UE; ++UI)
97       Parser.Note(*UI, ".cantunwind was specified here");
98   }
99   void emitHandlerDataLocNotes() const {
100     for (Locs::const_iterator HI = HandlerDataLocs.begin(),
101                               HE = HandlerDataLocs.end(); HI != HE; ++HI)
102       Parser.Note(*HI, ".handlerdata was specified here");
103   }
104   void emitPersonalityLocNotes() const {
105     for (Locs::const_iterator PI = PersonalityLocs.begin(),
106                               PE = PersonalityLocs.end(),
107                               PII = PersonalityIndexLocs.begin(),
108                               PIE = PersonalityIndexLocs.end();
109          PI != PE || PII != PIE;) {
110       if (PI != PE && (PII == PIE || PI->getPointer() < PII->getPointer()))
111         Parser.Note(*PI++, ".personality was specified here");
112       else if (PII != PIE && (PI == PE || PII->getPointer() < PI->getPointer()))
113         Parser.Note(*PII++, ".personalityindex was specified here");
114       else
115         llvm_unreachable(".personality and .personalityindex cannot be "
116                          "at the same location");
117     }
118   }
119
120   void reset() {
121     FnStartLocs = Locs();
122     CantUnwindLocs = Locs();
123     PersonalityLocs = Locs();
124     HandlerDataLocs = Locs();
125     PersonalityIndexLocs = Locs();
126     FPReg = ARM::SP;
127   }
128 };
129
130 class ARMAsmParser : public MCTargetAsmParser {
131   MCSubtargetInfo &STI;
132   const MCInstrInfo &MII;
133   const MCRegisterInfo *MRI;
134   UnwindContext UC;
135
136   ARMTargetStreamer &getTargetStreamer() {
137     assert(getParser().getStreamer().getTargetStreamer() &&
138            "do not have a target streamer");
139     MCTargetStreamer &TS = *getParser().getStreamer().getTargetStreamer();
140     return static_cast<ARMTargetStreamer &>(TS);
141   }
142
143   // Map of register aliases registers via the .req directive.
144   StringMap<unsigned> RegisterReqs;
145
146   bool NextSymbolIsThumb;
147
148   struct {
149     ARMCC::CondCodes Cond;    // Condition for IT block.
150     unsigned Mask:4;          // Condition mask for instructions.
151                               // Starting at first 1 (from lsb).
152                               //   '1'  condition as indicated in IT.
153                               //   '0'  inverse of condition (else).
154                               // Count of instructions in IT block is
155                               // 4 - trailingzeroes(mask)
156
157     bool FirstCond;           // Explicit flag for when we're parsing the
158                               // First instruction in the IT block. It's
159                               // implied in the mask, so needs special
160                               // handling.
161
162     unsigned CurPosition;     // Current position in parsing of IT
163                               // block. In range [0,3]. Initialized
164                               // according to count of instructions in block.
165                               // ~0U if no active IT block.
166   } ITState;
167   bool inITBlock() { return ITState.CurPosition != ~0U;}
168   void forwardITPosition() {
169     if (!inITBlock()) return;
170     // Move to the next instruction in the IT block, if there is one. If not,
171     // mark the block as done.
172     unsigned TZ = countTrailingZeros(ITState.Mask);
173     if (++ITState.CurPosition == 5 - TZ)
174       ITState.CurPosition = ~0U; // Done with the IT block after this.
175   }
176
177   void Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges = None) {
178     return getParser().Note(L, Msg, Ranges);
179   }
180   bool Warning(SMLoc L, const Twine &Msg,
181                ArrayRef<SMRange> Ranges = None) {
182     return getParser().Warning(L, Msg, Ranges);
183   }
184   bool Error(SMLoc L, const Twine &Msg,
185              ArrayRef<SMRange> Ranges = None) {
186     return getParser().Error(L, Msg, Ranges);
187   }
188
189   int tryParseRegister();
190   bool tryParseRegisterWithWriteBack(OperandVector &);
191   int tryParseShiftRegister(OperandVector &);
192   bool parseRegisterList(OperandVector &);
193   bool parseMemory(OperandVector &);
194   bool parseOperand(OperandVector &, StringRef Mnemonic);
195   bool parsePrefix(ARMMCExpr::VariantKind &RefKind);
196   bool parseMemRegOffsetShift(ARM_AM::ShiftOpc &ShiftType,
197                               unsigned &ShiftAmount);
198   bool parseLiteralValues(unsigned Size, SMLoc L);
199   bool parseDirectiveThumb(SMLoc L);
200   bool parseDirectiveARM(SMLoc L);
201   bool parseDirectiveThumbFunc(SMLoc L);
202   bool parseDirectiveCode(SMLoc L);
203   bool parseDirectiveSyntax(SMLoc L);
204   bool parseDirectiveReq(StringRef Name, SMLoc L);
205   bool parseDirectiveUnreq(SMLoc L);
206   bool parseDirectiveArch(SMLoc L);
207   bool parseDirectiveEabiAttr(SMLoc L);
208   bool parseDirectiveCPU(SMLoc L);
209   bool parseDirectiveFPU(SMLoc L);
210   bool parseDirectiveFnStart(SMLoc L);
211   bool parseDirectiveFnEnd(SMLoc L);
212   bool parseDirectiveCantUnwind(SMLoc L);
213   bool parseDirectivePersonality(SMLoc L);
214   bool parseDirectiveHandlerData(SMLoc L);
215   bool parseDirectiveSetFP(SMLoc L);
216   bool parseDirectivePad(SMLoc L);
217   bool parseDirectiveRegSave(SMLoc L, bool IsVector);
218   bool parseDirectiveInst(SMLoc L, char Suffix = '\0');
219   bool parseDirectiveLtorg(SMLoc L);
220   bool parseDirectiveEven(SMLoc L);
221   bool parseDirectivePersonalityIndex(SMLoc L);
222   bool parseDirectiveUnwindRaw(SMLoc L);
223   bool parseDirectiveTLSDescSeq(SMLoc L);
224   bool parseDirectiveMovSP(SMLoc L);
225   bool parseDirectiveObjectArch(SMLoc L);
226   bool parseDirectiveArchExtension(SMLoc L);
227   bool parseDirectiveAlign(SMLoc L);
228   bool parseDirectiveThumbSet(SMLoc L);
229
230   StringRef splitMnemonic(StringRef Mnemonic, unsigned &PredicationCode,
231                           bool &CarrySetting, unsigned &ProcessorIMod,
232                           StringRef &ITMask);
233   void getMnemonicAcceptInfo(StringRef Mnemonic, StringRef FullInst,
234                              bool &CanAcceptCarrySet,
235                              bool &CanAcceptPredicationCode);
236
237   bool isThumb() const {
238     // FIXME: Can tablegen auto-generate this?
239     return (STI.getFeatureBits() & ARM::ModeThumb) != 0;
240   }
241   bool isThumbOne() const {
242     return isThumb() && (STI.getFeatureBits() & ARM::FeatureThumb2) == 0;
243   }
244   bool isThumbTwo() const {
245     return isThumb() && (STI.getFeatureBits() & ARM::FeatureThumb2);
246   }
247   bool hasThumb() const {
248     return STI.getFeatureBits() & ARM::HasV4TOps;
249   }
250   bool hasV6Ops() const {
251     return STI.getFeatureBits() & ARM::HasV6Ops;
252   }
253   bool hasV6MOps() const {
254     return STI.getFeatureBits() & ARM::HasV6MOps;
255   }
256   bool hasV7Ops() const {
257     return STI.getFeatureBits() & ARM::HasV7Ops;
258   }
259   bool hasV8Ops() const {
260     return STI.getFeatureBits() & ARM::HasV8Ops;
261   }
262   bool hasARM() const {
263     return !(STI.getFeatureBits() & ARM::FeatureNoARM);
264   }
265   bool hasThumb2DSP() const {
266     return STI.getFeatureBits() & ARM::FeatureDSPThumb2;
267   }
268   bool hasD16() const {
269     return STI.getFeatureBits() & ARM::FeatureD16;
270   }
271
272   void SwitchMode() {
273     uint64_t FB = ComputeAvailableFeatures(STI.ToggleFeature(ARM::ModeThumb));
274     setAvailableFeatures(FB);
275   }
276   bool isMClass() const {
277     return STI.getFeatureBits() & ARM::FeatureMClass;
278   }
279
280   /// @name Auto-generated Match Functions
281   /// {
282
283 #define GET_ASSEMBLER_HEADER
284 #include "ARMGenAsmMatcher.inc"
285
286   /// }
287
288   OperandMatchResultTy parseITCondCode(OperandVector &);
289   OperandMatchResultTy parseCoprocNumOperand(OperandVector &);
290   OperandMatchResultTy parseCoprocRegOperand(OperandVector &);
291   OperandMatchResultTy parseCoprocOptionOperand(OperandVector &);
292   OperandMatchResultTy parseMemBarrierOptOperand(OperandVector &);
293   OperandMatchResultTy parseInstSyncBarrierOptOperand(OperandVector &);
294   OperandMatchResultTy parseProcIFlagsOperand(OperandVector &);
295   OperandMatchResultTy parseMSRMaskOperand(OperandVector &);
296   OperandMatchResultTy parseBankedRegOperand(OperandVector &);
297   OperandMatchResultTy parsePKHImm(OperandVector &O, StringRef Op, int Low,
298                                    int High);
299   OperandMatchResultTy parsePKHLSLImm(OperandVector &O) {
300     return parsePKHImm(O, "lsl", 0, 31);
301   }
302   OperandMatchResultTy parsePKHASRImm(OperandVector &O) {
303     return parsePKHImm(O, "asr", 1, 32);
304   }
305   OperandMatchResultTy parseSetEndImm(OperandVector &);
306   OperandMatchResultTy parseShifterImm(OperandVector &);
307   OperandMatchResultTy parseRotImm(OperandVector &);
308   OperandMatchResultTy parseBitfield(OperandVector &);
309   OperandMatchResultTy parsePostIdxReg(OperandVector &);
310   OperandMatchResultTy parseAM3Offset(OperandVector &);
311   OperandMatchResultTy parseFPImm(OperandVector &);
312   OperandMatchResultTy parseVectorList(OperandVector &);
313   OperandMatchResultTy parseVectorLane(VectorLaneTy &LaneKind, unsigned &Index,
314                                        SMLoc &EndLoc);
315
316   // Asm Match Converter Methods
317   void cvtThumbMultiply(MCInst &Inst, const OperandVector &);
318   void cvtThumbBranches(MCInst &Inst, const OperandVector &);
319
320   bool validateInstruction(MCInst &Inst, const OperandVector &Ops);
321   bool processInstruction(MCInst &Inst, const OperandVector &Ops, MCStreamer &Out);
322   bool shouldOmitCCOutOperand(StringRef Mnemonic, OperandVector &Operands);
323   bool shouldOmitPredicateOperand(StringRef Mnemonic, OperandVector &Operands);
324
325 public:
326   enum ARMMatchResultTy {
327     Match_RequiresITBlock = FIRST_TARGET_MATCH_RESULT_TY,
328     Match_RequiresNotITBlock,
329     Match_RequiresV6,
330     Match_RequiresThumb2,
331 #define GET_OPERAND_DIAGNOSTIC_TYPES
332 #include "ARMGenAsmMatcher.inc"
333
334   };
335
336   ARMAsmParser(MCSubtargetInfo & _STI, MCAsmParser & _Parser,
337                const MCInstrInfo &MII, const MCTargetOptions &Options)
338       : MCTargetAsmParser(), STI(_STI), MII(MII), UC(_Parser) {
339     MCAsmParserExtension::Initialize(_Parser);
340
341     // Cache the MCRegisterInfo.
342     MRI = getContext().getRegisterInfo();
343
344     // Initialize the set of available features.
345     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
346
347     // Not in an ITBlock to start with.
348     ITState.CurPosition = ~0U;
349
350     NextSymbolIsThumb = false;
351   }
352
353   // Implementation of the MCTargetAsmParser interface:
354   bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) override;
355   bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
356                         SMLoc NameLoc, OperandVector &Operands) override;
357   bool ParseDirective(AsmToken DirectiveID) override;
358
359   unsigned validateTargetOperandClass(MCParsedAsmOperand &Op,
360                                       unsigned Kind) override;
361   unsigned checkTargetMatchPredicate(MCInst &Inst) override;
362
363   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
364                                OperandVector &Operands, MCStreamer &Out,
365                                uint64_t &ErrorInfo,
366                                bool MatchingInlineAsm) override;
367   void onLabelParsed(MCSymbol *Symbol) override;
368 };
369 } // end anonymous namespace
370
371 namespace {
372
373 /// ARMOperand - Instances of this class represent a parsed ARM machine
374 /// operand.
375 class ARMOperand : public MCParsedAsmOperand {
376   enum KindTy {
377     k_CondCode,
378     k_CCOut,
379     k_ITCondMask,
380     k_CoprocNum,
381     k_CoprocReg,
382     k_CoprocOption,
383     k_Immediate,
384     k_MemBarrierOpt,
385     k_InstSyncBarrierOpt,
386     k_Memory,
387     k_PostIndexRegister,
388     k_MSRMask,
389     k_BankedReg,
390     k_ProcIFlags,
391     k_VectorIndex,
392     k_Register,
393     k_RegisterList,
394     k_DPRRegisterList,
395     k_SPRRegisterList,
396     k_VectorList,
397     k_VectorListAllLanes,
398     k_VectorListIndexed,
399     k_ShiftedRegister,
400     k_ShiftedImmediate,
401     k_ShifterImmediate,
402     k_RotateImmediate,
403     k_BitfieldDescriptor,
404     k_Token
405   } Kind;
406
407   SMLoc StartLoc, EndLoc, AlignmentLoc;
408   SmallVector<unsigned, 8> Registers;
409
410   struct CCOp {
411     ARMCC::CondCodes Val;
412   };
413
414   struct CopOp {
415     unsigned Val;
416   };
417
418   struct CoprocOptionOp {
419     unsigned Val;
420   };
421
422   struct ITMaskOp {
423     unsigned Mask:4;
424   };
425
426   struct MBOptOp {
427     ARM_MB::MemBOpt Val;
428   };
429
430   struct ISBOptOp {
431     ARM_ISB::InstSyncBOpt Val;
432   };
433
434   struct IFlagsOp {
435     ARM_PROC::IFlags Val;
436   };
437
438   struct MMaskOp {
439     unsigned Val;
440   };
441
442   struct BankedRegOp {
443     unsigned Val;
444   };
445
446   struct TokOp {
447     const char *Data;
448     unsigned Length;
449   };
450
451   struct RegOp {
452     unsigned RegNum;
453   };
454
455   // A vector register list is a sequential list of 1 to 4 registers.
456   struct VectorListOp {
457     unsigned RegNum;
458     unsigned Count;
459     unsigned LaneIndex;
460     bool isDoubleSpaced;
461   };
462
463   struct VectorIndexOp {
464     unsigned Val;
465   };
466
467   struct ImmOp {
468     const MCExpr *Val;
469   };
470
471   /// Combined record for all forms of ARM address expressions.
472   struct MemoryOp {
473     unsigned BaseRegNum;
474     // Offset is in OffsetReg or OffsetImm. If both are zero, no offset
475     // was specified.
476     const MCConstantExpr *OffsetImm;  // Offset immediate value
477     unsigned OffsetRegNum;    // Offset register num, when OffsetImm == NULL
478     ARM_AM::ShiftOpc ShiftType; // Shift type for OffsetReg
479     unsigned ShiftImm;        // shift for OffsetReg.
480     unsigned Alignment;       // 0 = no alignment specified
481     // n = alignment in bytes (2, 4, 8, 16, or 32)
482     unsigned isNegative : 1;  // Negated OffsetReg? (~'U' bit)
483   };
484
485   struct PostIdxRegOp {
486     unsigned RegNum;
487     bool isAdd;
488     ARM_AM::ShiftOpc ShiftTy;
489     unsigned ShiftImm;
490   };
491
492   struct ShifterImmOp {
493     bool isASR;
494     unsigned Imm;
495   };
496
497   struct RegShiftedRegOp {
498     ARM_AM::ShiftOpc ShiftTy;
499     unsigned SrcReg;
500     unsigned ShiftReg;
501     unsigned ShiftImm;
502   };
503
504   struct RegShiftedImmOp {
505     ARM_AM::ShiftOpc ShiftTy;
506     unsigned SrcReg;
507     unsigned ShiftImm;
508   };
509
510   struct RotImmOp {
511     unsigned Imm;
512   };
513
514   struct BitfieldOp {
515     unsigned LSB;
516     unsigned Width;
517   };
518
519   union {
520     struct CCOp CC;
521     struct CopOp Cop;
522     struct CoprocOptionOp CoprocOption;
523     struct MBOptOp MBOpt;
524     struct ISBOptOp ISBOpt;
525     struct ITMaskOp ITMask;
526     struct IFlagsOp IFlags;
527     struct MMaskOp MMask;
528     struct BankedRegOp BankedReg;
529     struct TokOp Tok;
530     struct RegOp Reg;
531     struct VectorListOp VectorList;
532     struct VectorIndexOp VectorIndex;
533     struct ImmOp Imm;
534     struct MemoryOp Memory;
535     struct PostIdxRegOp PostIdxReg;
536     struct ShifterImmOp ShifterImm;
537     struct RegShiftedRegOp RegShiftedReg;
538     struct RegShiftedImmOp RegShiftedImm;
539     struct RotImmOp RotImm;
540     struct BitfieldOp Bitfield;
541   };
542
543 public:
544   ARMOperand(KindTy K) : MCParsedAsmOperand(), Kind(K) {}
545   ARMOperand(const ARMOperand &o) : MCParsedAsmOperand() {
546     Kind = o.Kind;
547     StartLoc = o.StartLoc;
548     EndLoc = o.EndLoc;
549     switch (Kind) {
550     case k_CondCode:
551       CC = o.CC;
552       break;
553     case k_ITCondMask:
554       ITMask = o.ITMask;
555       break;
556     case k_Token:
557       Tok = o.Tok;
558       break;
559     case k_CCOut:
560     case k_Register:
561       Reg = o.Reg;
562       break;
563     case k_RegisterList:
564     case k_DPRRegisterList:
565     case k_SPRRegisterList:
566       Registers = o.Registers;
567       break;
568     case k_VectorList:
569     case k_VectorListAllLanes:
570     case k_VectorListIndexed:
571       VectorList = o.VectorList;
572       break;
573     case k_CoprocNum:
574     case k_CoprocReg:
575       Cop = o.Cop;
576       break;
577     case k_CoprocOption:
578       CoprocOption = o.CoprocOption;
579       break;
580     case k_Immediate:
581       Imm = o.Imm;
582       break;
583     case k_MemBarrierOpt:
584       MBOpt = o.MBOpt;
585       break;
586     case k_InstSyncBarrierOpt:
587       ISBOpt = o.ISBOpt;
588     case k_Memory:
589       Memory = o.Memory;
590       break;
591     case k_PostIndexRegister:
592       PostIdxReg = o.PostIdxReg;
593       break;
594     case k_MSRMask:
595       MMask = o.MMask;
596       break;
597     case k_BankedReg:
598       BankedReg = o.BankedReg;
599       break;
600     case k_ProcIFlags:
601       IFlags = o.IFlags;
602       break;
603     case k_ShifterImmediate:
604       ShifterImm = o.ShifterImm;
605       break;
606     case k_ShiftedRegister:
607       RegShiftedReg = o.RegShiftedReg;
608       break;
609     case k_ShiftedImmediate:
610       RegShiftedImm = o.RegShiftedImm;
611       break;
612     case k_RotateImmediate:
613       RotImm = o.RotImm;
614       break;
615     case k_BitfieldDescriptor:
616       Bitfield = o.Bitfield;
617       break;
618     case k_VectorIndex:
619       VectorIndex = o.VectorIndex;
620       break;
621     }
622   }
623
624   /// getStartLoc - Get the location of the first token of this operand.
625   SMLoc getStartLoc() const override { return StartLoc; }
626   /// getEndLoc - Get the location of the last token of this operand.
627   SMLoc getEndLoc() const override { return EndLoc; }
628   /// getLocRange - Get the range between the first and last token of this
629   /// operand.
630   SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
631
632   /// getAlignmentLoc - Get the location of the Alignment token of this operand.
633   SMLoc getAlignmentLoc() const {
634     assert(Kind == k_Memory && "Invalid access!");
635     return AlignmentLoc;
636   }
637
638   ARMCC::CondCodes getCondCode() const {
639     assert(Kind == k_CondCode && "Invalid access!");
640     return CC.Val;
641   }
642
643   unsigned getCoproc() const {
644     assert((Kind == k_CoprocNum || Kind == k_CoprocReg) && "Invalid access!");
645     return Cop.Val;
646   }
647
648   StringRef getToken() const {
649     assert(Kind == k_Token && "Invalid access!");
650     return StringRef(Tok.Data, Tok.Length);
651   }
652
653   unsigned getReg() const override {
654     assert((Kind == k_Register || Kind == k_CCOut) && "Invalid access!");
655     return Reg.RegNum;
656   }
657
658   const SmallVectorImpl<unsigned> &getRegList() const {
659     assert((Kind == k_RegisterList || Kind == k_DPRRegisterList ||
660             Kind == k_SPRRegisterList) && "Invalid access!");
661     return Registers;
662   }
663
664   const MCExpr *getImm() const {
665     assert(isImm() && "Invalid access!");
666     return Imm.Val;
667   }
668
669   unsigned getVectorIndex() const {
670     assert(Kind == k_VectorIndex && "Invalid access!");
671     return VectorIndex.Val;
672   }
673
674   ARM_MB::MemBOpt getMemBarrierOpt() const {
675     assert(Kind == k_MemBarrierOpt && "Invalid access!");
676     return MBOpt.Val;
677   }
678
679   ARM_ISB::InstSyncBOpt getInstSyncBarrierOpt() const {
680     assert(Kind == k_InstSyncBarrierOpt && "Invalid access!");
681     return ISBOpt.Val;
682   }
683
684   ARM_PROC::IFlags getProcIFlags() const {
685     assert(Kind == k_ProcIFlags && "Invalid access!");
686     return IFlags.Val;
687   }
688
689   unsigned getMSRMask() const {
690     assert(Kind == k_MSRMask && "Invalid access!");
691     return MMask.Val;
692   }
693
694   unsigned getBankedReg() const {
695     assert(Kind == k_BankedReg && "Invalid access!");
696     return BankedReg.Val;
697   }
698
699   bool isCoprocNum() const { return Kind == k_CoprocNum; }
700   bool isCoprocReg() const { return Kind == k_CoprocReg; }
701   bool isCoprocOption() const { return Kind == k_CoprocOption; }
702   bool isCondCode() const { return Kind == k_CondCode; }
703   bool isCCOut() const { return Kind == k_CCOut; }
704   bool isITMask() const { return Kind == k_ITCondMask; }
705   bool isITCondCode() const { return Kind == k_CondCode; }
706   bool isImm() const override { return Kind == k_Immediate; }
707   // checks whether this operand is an unsigned offset which fits is a field
708   // of specified width and scaled by a specific number of bits
709   template<unsigned width, unsigned scale>
710   bool isUnsignedOffset() const {
711     if (!isImm()) return false;
712     if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
713     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
714       int64_t Val = CE->getValue();
715       int64_t Align = 1LL << scale;
716       int64_t Max = Align * ((1LL << width) - 1);
717       return ((Val % Align) == 0) && (Val >= 0) && (Val <= Max);
718     }
719     return false;
720   }
721   // checks whether this operand is an signed offset which fits is a field
722   // of specified width and scaled by a specific number of bits
723   template<unsigned width, unsigned scale>
724   bool isSignedOffset() const {
725     if (!isImm()) return false;
726     if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
727     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
728       int64_t Val = CE->getValue();
729       int64_t Align = 1LL << scale;
730       int64_t Max = Align * ((1LL << (width-1)) - 1);
731       int64_t Min = -Align * (1LL << (width-1));
732       return ((Val % Align) == 0) && (Val >= Min) && (Val <= Max);
733     }
734     return false;
735   }
736
737   // checks whether this operand is a memory operand computed as an offset
738   // applied to PC. the offset may have 8 bits of magnitude and is represented
739   // with two bits of shift. textually it may be either [pc, #imm], #imm or 
740   // relocable expression...
741   bool isThumbMemPC() const {
742     int64_t Val = 0;
743     if (isImm()) {
744       if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
745       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val);
746       if (!CE) return false;
747       Val = CE->getValue();
748     }
749     else if (isMem()) {
750       if(!Memory.OffsetImm || Memory.OffsetRegNum) return false;
751       if(Memory.BaseRegNum != ARM::PC) return false;
752       Val = Memory.OffsetImm->getValue();
753     }
754     else return false;
755     return ((Val % 4) == 0) && (Val >= 0) && (Val <= 1020);
756   }
757   bool isFPImm() const {
758     if (!isImm()) return false;
759     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
760     if (!CE) return false;
761     int Val = ARM_AM::getFP32Imm(APInt(32, CE->getValue()));
762     return Val != -1;
763   }
764   bool isFBits16() const {
765     if (!isImm()) return false;
766     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
767     if (!CE) return false;
768     int64_t Value = CE->getValue();
769     return Value >= 0 && Value <= 16;
770   }
771   bool isFBits32() const {
772     if (!isImm()) return false;
773     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
774     if (!CE) return false;
775     int64_t Value = CE->getValue();
776     return Value >= 1 && Value <= 32;
777   }
778   bool isImm8s4() const {
779     if (!isImm()) return false;
780     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
781     if (!CE) return false;
782     int64_t Value = CE->getValue();
783     return ((Value & 3) == 0) && Value >= -1020 && Value <= 1020;
784   }
785   bool isImm0_1020s4() const {
786     if (!isImm()) return false;
787     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
788     if (!CE) return false;
789     int64_t Value = CE->getValue();
790     return ((Value & 3) == 0) && Value >= 0 && Value <= 1020;
791   }
792   bool isImm0_508s4() const {
793     if (!isImm()) return false;
794     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
795     if (!CE) return false;
796     int64_t Value = CE->getValue();
797     return ((Value & 3) == 0) && Value >= 0 && Value <= 508;
798   }
799   bool isImm0_508s4Neg() const {
800     if (!isImm()) return false;
801     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
802     if (!CE) return false;
803     int64_t Value = -CE->getValue();
804     // explicitly exclude zero. we want that to use the normal 0_508 version.
805     return ((Value & 3) == 0) && Value > 0 && Value <= 508;
806   }
807   bool isImm0_239() const {
808     if (!isImm()) return false;
809     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
810     if (!CE) return false;
811     int64_t Value = CE->getValue();
812     return Value >= 0 && Value < 240;
813   }
814   bool isImm0_255() const {
815     if (!isImm()) return false;
816     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
817     if (!CE) return false;
818     int64_t Value = CE->getValue();
819     return Value >= 0 && Value < 256;
820   }
821   bool isImm0_4095() const {
822     if (!isImm()) return false;
823     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
824     if (!CE) return false;
825     int64_t Value = CE->getValue();
826     return Value >= 0 && Value < 4096;
827   }
828   bool isImm0_4095Neg() const {
829     if (!isImm()) return false;
830     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
831     if (!CE) return false;
832     int64_t Value = -CE->getValue();
833     return Value > 0 && Value < 4096;
834   }
835   bool isImm0_1() const {
836     if (!isImm()) return false;
837     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
838     if (!CE) return false;
839     int64_t Value = CE->getValue();
840     return Value >= 0 && Value < 2;
841   }
842   bool isImm0_3() const {
843     if (!isImm()) return false;
844     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
845     if (!CE) return false;
846     int64_t Value = CE->getValue();
847     return Value >= 0 && Value < 4;
848   }
849   bool isImm0_7() const {
850     if (!isImm()) return false;
851     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
852     if (!CE) return false;
853     int64_t Value = CE->getValue();
854     return Value >= 0 && Value < 8;
855   }
856   bool isImm0_15() const {
857     if (!isImm()) return false;
858     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
859     if (!CE) return false;
860     int64_t Value = CE->getValue();
861     return Value >= 0 && Value < 16;
862   }
863   bool isImm0_31() const {
864     if (!isImm()) return false;
865     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
866     if (!CE) return false;
867     int64_t Value = CE->getValue();
868     return Value >= 0 && Value < 32;
869   }
870   bool isImm0_63() const {
871     if (!isImm()) return false;
872     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
873     if (!CE) return false;
874     int64_t Value = CE->getValue();
875     return Value >= 0 && Value < 64;
876   }
877   bool isImm8() const {
878     if (!isImm()) return false;
879     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
880     if (!CE) return false;
881     int64_t Value = CE->getValue();
882     return Value == 8;
883   }
884   bool isImm16() const {
885     if (!isImm()) return false;
886     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
887     if (!CE) return false;
888     int64_t Value = CE->getValue();
889     return Value == 16;
890   }
891   bool isImm32() const {
892     if (!isImm()) return false;
893     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
894     if (!CE) return false;
895     int64_t Value = CE->getValue();
896     return Value == 32;
897   }
898   bool isShrImm8() const {
899     if (!isImm()) return false;
900     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
901     if (!CE) return false;
902     int64_t Value = CE->getValue();
903     return Value > 0 && Value <= 8;
904   }
905   bool isShrImm16() const {
906     if (!isImm()) return false;
907     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
908     if (!CE) return false;
909     int64_t Value = CE->getValue();
910     return Value > 0 && Value <= 16;
911   }
912   bool isShrImm32() const {
913     if (!isImm()) return false;
914     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
915     if (!CE) return false;
916     int64_t Value = CE->getValue();
917     return Value > 0 && Value <= 32;
918   }
919   bool isShrImm64() const {
920     if (!isImm()) return false;
921     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
922     if (!CE) return false;
923     int64_t Value = CE->getValue();
924     return Value > 0 && Value <= 64;
925   }
926   bool isImm1_7() const {
927     if (!isImm()) return false;
928     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
929     if (!CE) return false;
930     int64_t Value = CE->getValue();
931     return Value > 0 && Value < 8;
932   }
933   bool isImm1_15() const {
934     if (!isImm()) return false;
935     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
936     if (!CE) return false;
937     int64_t Value = CE->getValue();
938     return Value > 0 && Value < 16;
939   }
940   bool isImm1_31() const {
941     if (!isImm()) return false;
942     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
943     if (!CE) return false;
944     int64_t Value = CE->getValue();
945     return Value > 0 && Value < 32;
946   }
947   bool isImm1_16() const {
948     if (!isImm()) return false;
949     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
950     if (!CE) return false;
951     int64_t Value = CE->getValue();
952     return Value > 0 && Value < 17;
953   }
954   bool isImm1_32() const {
955     if (!isImm()) return false;
956     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
957     if (!CE) return false;
958     int64_t Value = CE->getValue();
959     return Value > 0 && Value < 33;
960   }
961   bool isImm0_32() const {
962     if (!isImm()) return false;
963     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
964     if (!CE) return false;
965     int64_t Value = CE->getValue();
966     return Value >= 0 && Value < 33;
967   }
968   bool isImm0_65535() const {
969     if (!isImm()) return false;
970     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
971     if (!CE) return false;
972     int64_t Value = CE->getValue();
973     return Value >= 0 && Value < 65536;
974   }
975   bool isImm256_65535Expr() const {
976     if (!isImm()) return false;
977     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
978     // If it's not a constant expression, it'll generate a fixup and be
979     // handled later.
980     if (!CE) return true;
981     int64_t Value = CE->getValue();
982     return Value >= 256 && Value < 65536;
983   }
984   bool isImm0_65535Expr() const {
985     if (!isImm()) return false;
986     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
987     // If it's not a constant expression, it'll generate a fixup and be
988     // handled later.
989     if (!CE) return true;
990     int64_t Value = CE->getValue();
991     return Value >= 0 && Value < 65536;
992   }
993   bool isImm24bit() const {
994     if (!isImm()) return false;
995     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
996     if (!CE) return false;
997     int64_t Value = CE->getValue();
998     return Value >= 0 && Value <= 0xffffff;
999   }
1000   bool isImmThumbSR() const {
1001     if (!isImm()) return false;
1002     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1003     if (!CE) return false;
1004     int64_t Value = CE->getValue();
1005     return Value > 0 && Value < 33;
1006   }
1007   bool isPKHLSLImm() const {
1008     if (!isImm()) return false;
1009     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1010     if (!CE) return false;
1011     int64_t Value = CE->getValue();
1012     return Value >= 0 && Value < 32;
1013   }
1014   bool isPKHASRImm() const {
1015     if (!isImm()) return false;
1016     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1017     if (!CE) return false;
1018     int64_t Value = CE->getValue();
1019     return Value > 0 && Value <= 32;
1020   }
1021   bool isAdrLabel() const {
1022     // If we have an immediate that's not a constant, treat it as a label
1023     // reference needing a fixup. If it is a constant, but it can't fit 
1024     // into shift immediate encoding, we reject it.
1025     if (isImm() && !isa<MCConstantExpr>(getImm())) return true;
1026     else return (isARMSOImm() || isARMSOImmNeg());
1027   }
1028   bool isARMSOImm() const {
1029     if (!isImm()) return false;
1030     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1031     if (!CE) return false;
1032     int64_t Value = CE->getValue();
1033     return ARM_AM::getSOImmVal(Value) != -1;
1034   }
1035   bool isARMSOImmNot() const {
1036     if (!isImm()) return false;
1037     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1038     if (!CE) return false;
1039     int64_t Value = CE->getValue();
1040     return ARM_AM::getSOImmVal(~Value) != -1;
1041   }
1042   bool isARMSOImmNeg() const {
1043     if (!isImm()) return false;
1044     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1045     if (!CE) return false;
1046     int64_t Value = CE->getValue();
1047     // Only use this when not representable as a plain so_imm.
1048     return ARM_AM::getSOImmVal(Value) == -1 &&
1049       ARM_AM::getSOImmVal(-Value) != -1;
1050   }
1051   bool isT2SOImm() const {
1052     if (!isImm()) return false;
1053     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1054     if (!CE) return false;
1055     int64_t Value = CE->getValue();
1056     return ARM_AM::getT2SOImmVal(Value) != -1;
1057   }
1058   bool isT2SOImmNot() const {
1059     if (!isImm()) return false;
1060     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1061     if (!CE) return false;
1062     int64_t Value = CE->getValue();
1063     return ARM_AM::getT2SOImmVal(Value) == -1 &&
1064       ARM_AM::getT2SOImmVal(~Value) != -1;
1065   }
1066   bool isT2SOImmNeg() const {
1067     if (!isImm()) return false;
1068     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1069     if (!CE) return false;
1070     int64_t Value = CE->getValue();
1071     // Only use this when not representable as a plain so_imm.
1072     return ARM_AM::getT2SOImmVal(Value) == -1 &&
1073       ARM_AM::getT2SOImmVal(-Value) != -1;
1074   }
1075   bool isSetEndImm() const {
1076     if (!isImm()) return false;
1077     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1078     if (!CE) return false;
1079     int64_t Value = CE->getValue();
1080     return Value == 1 || Value == 0;
1081   }
1082   bool isReg() const override { return Kind == k_Register; }
1083   bool isRegList() const { return Kind == k_RegisterList; }
1084   bool isDPRRegList() const { return Kind == k_DPRRegisterList; }
1085   bool isSPRRegList() const { return Kind == k_SPRRegisterList; }
1086   bool isToken() const override { return Kind == k_Token; }
1087   bool isMemBarrierOpt() const { return Kind == k_MemBarrierOpt; }
1088   bool isInstSyncBarrierOpt() const { return Kind == k_InstSyncBarrierOpt; }
1089   bool isMem() const override { return Kind == k_Memory; }
1090   bool isShifterImm() const { return Kind == k_ShifterImmediate; }
1091   bool isRegShiftedReg() const { return Kind == k_ShiftedRegister; }
1092   bool isRegShiftedImm() const { return Kind == k_ShiftedImmediate; }
1093   bool isRotImm() const { return Kind == k_RotateImmediate; }
1094   bool isBitfield() const { return Kind == k_BitfieldDescriptor; }
1095   bool isPostIdxRegShifted() const { return Kind == k_PostIndexRegister; }
1096   bool isPostIdxReg() const {
1097     return Kind == k_PostIndexRegister && PostIdxReg.ShiftTy ==ARM_AM::no_shift;
1098   }
1099   bool isMemNoOffset(bool alignOK = false, unsigned Alignment = 0) const {
1100     if (!isMem())
1101       return false;
1102     // No offset of any kind.
1103     return Memory.OffsetRegNum == 0 && Memory.OffsetImm == nullptr &&
1104      (alignOK || Memory.Alignment == Alignment);
1105   }
1106   bool isMemPCRelImm12() const {
1107     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1108       return false;
1109     // Base register must be PC.
1110     if (Memory.BaseRegNum != ARM::PC)
1111       return false;
1112     // Immediate offset in range [-4095, 4095].
1113     if (!Memory.OffsetImm) return true;
1114     int64_t Val = Memory.OffsetImm->getValue();
1115     return (Val > -4096 && Val < 4096) || (Val == INT32_MIN);
1116   }
1117   bool isAlignedMemory() const {
1118     return isMemNoOffset(true);
1119   }
1120   bool isAlignedMemoryNone() const {
1121     return isMemNoOffset(false, 0);
1122   }
1123   bool isDupAlignedMemoryNone() const {
1124     return isMemNoOffset(false, 0);
1125   }
1126   bool isAlignedMemory16() const {
1127     if (isMemNoOffset(false, 2)) // alignment in bytes for 16-bits is 2.
1128       return true;
1129     return isMemNoOffset(false, 0);
1130   }
1131   bool isDupAlignedMemory16() const {
1132     if (isMemNoOffset(false, 2)) // alignment in bytes for 16-bits is 2.
1133       return true;
1134     return isMemNoOffset(false, 0);
1135   }
1136   bool isAlignedMemory32() const {
1137     if (isMemNoOffset(false, 4)) // alignment in bytes for 32-bits is 4.
1138       return true;
1139     return isMemNoOffset(false, 0);
1140   }
1141   bool isDupAlignedMemory32() const {
1142     if (isMemNoOffset(false, 4)) // alignment in bytes for 32-bits is 4.
1143       return true;
1144     return isMemNoOffset(false, 0);
1145   }
1146   bool isAlignedMemory64() const {
1147     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1148       return true;
1149     return isMemNoOffset(false, 0);
1150   }
1151   bool isDupAlignedMemory64() const {
1152     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1153       return true;
1154     return isMemNoOffset(false, 0);
1155   }
1156   bool isAlignedMemory64or128() const {
1157     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1158       return true;
1159     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1160       return true;
1161     return isMemNoOffset(false, 0);
1162   }
1163   bool isDupAlignedMemory64or128() const {
1164     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1165       return true;
1166     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1167       return true;
1168     return isMemNoOffset(false, 0);
1169   }
1170   bool isAlignedMemory64or128or256() const {
1171     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1172       return true;
1173     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1174       return true;
1175     if (isMemNoOffset(false, 32)) // alignment in bytes for 256-bits is 32.
1176       return true;
1177     return isMemNoOffset(false, 0);
1178   }
1179   bool isAddrMode2() const {
1180     if (!isMem() || Memory.Alignment != 0) return false;
1181     // Check for register offset.
1182     if (Memory.OffsetRegNum) return true;
1183     // Immediate offset in range [-4095, 4095].
1184     if (!Memory.OffsetImm) return true;
1185     int64_t Val = Memory.OffsetImm->getValue();
1186     return Val > -4096 && Val < 4096;
1187   }
1188   bool isAM2OffsetImm() const {
1189     if (!isImm()) return false;
1190     // Immediate offset in range [-4095, 4095].
1191     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1192     if (!CE) return false;
1193     int64_t Val = CE->getValue();
1194     return (Val == INT32_MIN) || (Val > -4096 && Val < 4096);
1195   }
1196   bool isAddrMode3() const {
1197     // If we have an immediate that's not a constant, treat it as a label
1198     // reference needing a fixup. If it is a constant, it's something else
1199     // and we reject it.
1200     if (isImm() && !isa<MCConstantExpr>(getImm()))
1201       return true;
1202     if (!isMem() || Memory.Alignment != 0) return false;
1203     // No shifts are legal for AM3.
1204     if (Memory.ShiftType != ARM_AM::no_shift) return false;
1205     // Check for register offset.
1206     if (Memory.OffsetRegNum) return true;
1207     // Immediate offset in range [-255, 255].
1208     if (!Memory.OffsetImm) return true;
1209     int64_t Val = Memory.OffsetImm->getValue();
1210     // The #-0 offset is encoded as INT32_MIN, and we have to check 
1211     // for this too.
1212     return (Val > -256 && Val < 256) || Val == INT32_MIN;
1213   }
1214   bool isAM3Offset() const {
1215     if (Kind != k_Immediate && Kind != k_PostIndexRegister)
1216       return false;
1217     if (Kind == k_PostIndexRegister)
1218       return PostIdxReg.ShiftTy == ARM_AM::no_shift;
1219     // Immediate offset in range [-255, 255].
1220     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1221     if (!CE) return false;
1222     int64_t Val = CE->getValue();
1223     // Special case, #-0 is INT32_MIN.
1224     return (Val > -256 && Val < 256) || Val == INT32_MIN;
1225   }
1226   bool isAddrMode5() const {
1227     // If we have an immediate that's not a constant, treat it as a label
1228     // reference needing a fixup. If it is a constant, it's something else
1229     // and we reject it.
1230     if (isImm() && !isa<MCConstantExpr>(getImm()))
1231       return true;
1232     if (!isMem() || Memory.Alignment != 0) return false;
1233     // Check for register offset.
1234     if (Memory.OffsetRegNum) return false;
1235     // Immediate offset in range [-1020, 1020] and a multiple of 4.
1236     if (!Memory.OffsetImm) return true;
1237     int64_t Val = Memory.OffsetImm->getValue();
1238     return (Val >= -1020 && Val <= 1020 && ((Val & 3) == 0)) ||
1239       Val == INT32_MIN;
1240   }
1241   bool isMemTBB() const {
1242     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1243         Memory.ShiftType != ARM_AM::no_shift || Memory.Alignment != 0)
1244       return false;
1245     return true;
1246   }
1247   bool isMemTBH() const {
1248     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1249         Memory.ShiftType != ARM_AM::lsl || Memory.ShiftImm != 1 ||
1250         Memory.Alignment != 0 )
1251       return false;
1252     return true;
1253   }
1254   bool isMemRegOffset() const {
1255     if (!isMem() || !Memory.OffsetRegNum || Memory.Alignment != 0)
1256       return false;
1257     return true;
1258   }
1259   bool isT2MemRegOffset() const {
1260     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1261         Memory.Alignment != 0)
1262       return false;
1263     // Only lsl #{0, 1, 2, 3} allowed.
1264     if (Memory.ShiftType == ARM_AM::no_shift)
1265       return true;
1266     if (Memory.ShiftType != ARM_AM::lsl || Memory.ShiftImm > 3)
1267       return false;
1268     return true;
1269   }
1270   bool isMemThumbRR() const {
1271     // Thumb reg+reg addressing is simple. Just two registers, a base and
1272     // an offset. No shifts, negations or any other complicating factors.
1273     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1274         Memory.ShiftType != ARM_AM::no_shift || Memory.Alignment != 0)
1275       return false;
1276     return isARMLowRegister(Memory.BaseRegNum) &&
1277       (!Memory.OffsetRegNum || isARMLowRegister(Memory.OffsetRegNum));
1278   }
1279   bool isMemThumbRIs4() const {
1280     if (!isMem() || Memory.OffsetRegNum != 0 ||
1281         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1282       return false;
1283     // Immediate offset, multiple of 4 in range [0, 124].
1284     if (!Memory.OffsetImm) return true;
1285     int64_t Val = Memory.OffsetImm->getValue();
1286     return Val >= 0 && Val <= 124 && (Val % 4) == 0;
1287   }
1288   bool isMemThumbRIs2() const {
1289     if (!isMem() || Memory.OffsetRegNum != 0 ||
1290         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1291       return false;
1292     // Immediate offset, multiple of 4 in range [0, 62].
1293     if (!Memory.OffsetImm) return true;
1294     int64_t Val = Memory.OffsetImm->getValue();
1295     return Val >= 0 && Val <= 62 && (Val % 2) == 0;
1296   }
1297   bool isMemThumbRIs1() const {
1298     if (!isMem() || Memory.OffsetRegNum != 0 ||
1299         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1300       return false;
1301     // Immediate offset in range [0, 31].
1302     if (!Memory.OffsetImm) return true;
1303     int64_t Val = Memory.OffsetImm->getValue();
1304     return Val >= 0 && Val <= 31;
1305   }
1306   bool isMemThumbSPI() const {
1307     if (!isMem() || Memory.OffsetRegNum != 0 ||
1308         Memory.BaseRegNum != ARM::SP || Memory.Alignment != 0)
1309       return false;
1310     // Immediate offset, multiple of 4 in range [0, 1020].
1311     if (!Memory.OffsetImm) return true;
1312     int64_t Val = Memory.OffsetImm->getValue();
1313     return Val >= 0 && Val <= 1020 && (Val % 4) == 0;
1314   }
1315   bool isMemImm8s4Offset() const {
1316     // If we have an immediate that's not a constant, treat it as a label
1317     // reference needing a fixup. If it is a constant, it's something else
1318     // and we reject it.
1319     if (isImm() && !isa<MCConstantExpr>(getImm()))
1320       return true;
1321     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1322       return false;
1323     // Immediate offset a multiple of 4 in range [-1020, 1020].
1324     if (!Memory.OffsetImm) return true;
1325     int64_t Val = Memory.OffsetImm->getValue();
1326     // Special case, #-0 is INT32_MIN.
1327     return (Val >= -1020 && Val <= 1020 && (Val & 3) == 0) || Val == INT32_MIN;
1328   }
1329   bool isMemImm0_1020s4Offset() const {
1330     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1331       return false;
1332     // Immediate offset a multiple of 4 in range [0, 1020].
1333     if (!Memory.OffsetImm) return true;
1334     int64_t Val = Memory.OffsetImm->getValue();
1335     return Val >= 0 && Val <= 1020 && (Val & 3) == 0;
1336   }
1337   bool isMemImm8Offset() const {
1338     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1339       return false;
1340     // Base reg of PC isn't allowed for these encodings.
1341     if (Memory.BaseRegNum == ARM::PC) return false;
1342     // Immediate offset in range [-255, 255].
1343     if (!Memory.OffsetImm) return true;
1344     int64_t Val = Memory.OffsetImm->getValue();
1345     return (Val == INT32_MIN) || (Val > -256 && Val < 256);
1346   }
1347   bool isMemPosImm8Offset() const {
1348     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1349       return false;
1350     // Immediate offset in range [0, 255].
1351     if (!Memory.OffsetImm) return true;
1352     int64_t Val = Memory.OffsetImm->getValue();
1353     return Val >= 0 && Val < 256;
1354   }
1355   bool isMemNegImm8Offset() const {
1356     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1357       return false;
1358     // Base reg of PC isn't allowed for these encodings.
1359     if (Memory.BaseRegNum == ARM::PC) return false;
1360     // Immediate offset in range [-255, -1].
1361     if (!Memory.OffsetImm) return false;
1362     int64_t Val = Memory.OffsetImm->getValue();
1363     return (Val == INT32_MIN) || (Val > -256 && Val < 0);
1364   }
1365   bool isMemUImm12Offset() const {
1366     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1367       return false;
1368     // Immediate offset in range [0, 4095].
1369     if (!Memory.OffsetImm) return true;
1370     int64_t Val = Memory.OffsetImm->getValue();
1371     return (Val >= 0 && Val < 4096);
1372   }
1373   bool isMemImm12Offset() const {
1374     // If we have an immediate that's not a constant, treat it as a label
1375     // reference needing a fixup. If it is a constant, it's something else
1376     // and we reject it.
1377     if (isImm() && !isa<MCConstantExpr>(getImm()))
1378       return true;
1379
1380     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1381       return false;
1382     // Immediate offset in range [-4095, 4095].
1383     if (!Memory.OffsetImm) return true;
1384     int64_t Val = Memory.OffsetImm->getValue();
1385     return (Val > -4096 && Val < 4096) || (Val == INT32_MIN);
1386   }
1387   bool isPostIdxImm8() const {
1388     if (!isImm()) return false;
1389     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1390     if (!CE) return false;
1391     int64_t Val = CE->getValue();
1392     return (Val > -256 && Val < 256) || (Val == INT32_MIN);
1393   }
1394   bool isPostIdxImm8s4() const {
1395     if (!isImm()) return false;
1396     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1397     if (!CE) return false;
1398     int64_t Val = CE->getValue();
1399     return ((Val & 3) == 0 && Val >= -1020 && Val <= 1020) ||
1400       (Val == INT32_MIN);
1401   }
1402
1403   bool isMSRMask() const { return Kind == k_MSRMask; }
1404   bool isBankedReg() const { return Kind == k_BankedReg; }
1405   bool isProcIFlags() const { return Kind == k_ProcIFlags; }
1406
1407   // NEON operands.
1408   bool isSingleSpacedVectorList() const {
1409     return Kind == k_VectorList && !VectorList.isDoubleSpaced;
1410   }
1411   bool isDoubleSpacedVectorList() const {
1412     return Kind == k_VectorList && VectorList.isDoubleSpaced;
1413   }
1414   bool isVecListOneD() const {
1415     if (!isSingleSpacedVectorList()) return false;
1416     return VectorList.Count == 1;
1417   }
1418
1419   bool isVecListDPair() const {
1420     if (!isSingleSpacedVectorList()) return false;
1421     return (ARMMCRegisterClasses[ARM::DPairRegClassID]
1422               .contains(VectorList.RegNum));
1423   }
1424
1425   bool isVecListThreeD() const {
1426     if (!isSingleSpacedVectorList()) return false;
1427     return VectorList.Count == 3;
1428   }
1429
1430   bool isVecListFourD() const {
1431     if (!isSingleSpacedVectorList()) return false;
1432     return VectorList.Count == 4;
1433   }
1434
1435   bool isVecListDPairSpaced() const {
1436     if (Kind != k_VectorList) return false;
1437     if (isSingleSpacedVectorList()) return false;
1438     return (ARMMCRegisterClasses[ARM::DPairSpcRegClassID]
1439               .contains(VectorList.RegNum));
1440   }
1441
1442   bool isVecListThreeQ() const {
1443     if (!isDoubleSpacedVectorList()) return false;
1444     return VectorList.Count == 3;
1445   }
1446
1447   bool isVecListFourQ() const {
1448     if (!isDoubleSpacedVectorList()) return false;
1449     return VectorList.Count == 4;
1450   }
1451
1452   bool isSingleSpacedVectorAllLanes() const {
1453     return Kind == k_VectorListAllLanes && !VectorList.isDoubleSpaced;
1454   }
1455   bool isDoubleSpacedVectorAllLanes() const {
1456     return Kind == k_VectorListAllLanes && VectorList.isDoubleSpaced;
1457   }
1458   bool isVecListOneDAllLanes() const {
1459     if (!isSingleSpacedVectorAllLanes()) return false;
1460     return VectorList.Count == 1;
1461   }
1462
1463   bool isVecListDPairAllLanes() const {
1464     if (!isSingleSpacedVectorAllLanes()) return false;
1465     return (ARMMCRegisterClasses[ARM::DPairRegClassID]
1466               .contains(VectorList.RegNum));
1467   }
1468
1469   bool isVecListDPairSpacedAllLanes() const {
1470     if (!isDoubleSpacedVectorAllLanes()) return false;
1471     return VectorList.Count == 2;
1472   }
1473
1474   bool isVecListThreeDAllLanes() const {
1475     if (!isSingleSpacedVectorAllLanes()) return false;
1476     return VectorList.Count == 3;
1477   }
1478
1479   bool isVecListThreeQAllLanes() const {
1480     if (!isDoubleSpacedVectorAllLanes()) return false;
1481     return VectorList.Count == 3;
1482   }
1483
1484   bool isVecListFourDAllLanes() const {
1485     if (!isSingleSpacedVectorAllLanes()) return false;
1486     return VectorList.Count == 4;
1487   }
1488
1489   bool isVecListFourQAllLanes() const {
1490     if (!isDoubleSpacedVectorAllLanes()) return false;
1491     return VectorList.Count == 4;
1492   }
1493
1494   bool isSingleSpacedVectorIndexed() const {
1495     return Kind == k_VectorListIndexed && !VectorList.isDoubleSpaced;
1496   }
1497   bool isDoubleSpacedVectorIndexed() const {
1498     return Kind == k_VectorListIndexed && VectorList.isDoubleSpaced;
1499   }
1500   bool isVecListOneDByteIndexed() const {
1501     if (!isSingleSpacedVectorIndexed()) return false;
1502     return VectorList.Count == 1 && VectorList.LaneIndex <= 7;
1503   }
1504
1505   bool isVecListOneDHWordIndexed() const {
1506     if (!isSingleSpacedVectorIndexed()) return false;
1507     return VectorList.Count == 1 && VectorList.LaneIndex <= 3;
1508   }
1509
1510   bool isVecListOneDWordIndexed() const {
1511     if (!isSingleSpacedVectorIndexed()) return false;
1512     return VectorList.Count == 1 && VectorList.LaneIndex <= 1;
1513   }
1514
1515   bool isVecListTwoDByteIndexed() const {
1516     if (!isSingleSpacedVectorIndexed()) return false;
1517     return VectorList.Count == 2 && VectorList.LaneIndex <= 7;
1518   }
1519
1520   bool isVecListTwoDHWordIndexed() const {
1521     if (!isSingleSpacedVectorIndexed()) return false;
1522     return VectorList.Count == 2 && VectorList.LaneIndex <= 3;
1523   }
1524
1525   bool isVecListTwoQWordIndexed() const {
1526     if (!isDoubleSpacedVectorIndexed()) return false;
1527     return VectorList.Count == 2 && VectorList.LaneIndex <= 1;
1528   }
1529
1530   bool isVecListTwoQHWordIndexed() const {
1531     if (!isDoubleSpacedVectorIndexed()) return false;
1532     return VectorList.Count == 2 && VectorList.LaneIndex <= 3;
1533   }
1534
1535   bool isVecListTwoDWordIndexed() const {
1536     if (!isSingleSpacedVectorIndexed()) return false;
1537     return VectorList.Count == 2 && VectorList.LaneIndex <= 1;
1538   }
1539
1540   bool isVecListThreeDByteIndexed() const {
1541     if (!isSingleSpacedVectorIndexed()) return false;
1542     return VectorList.Count == 3 && VectorList.LaneIndex <= 7;
1543   }
1544
1545   bool isVecListThreeDHWordIndexed() const {
1546     if (!isSingleSpacedVectorIndexed()) return false;
1547     return VectorList.Count == 3 && VectorList.LaneIndex <= 3;
1548   }
1549
1550   bool isVecListThreeQWordIndexed() const {
1551     if (!isDoubleSpacedVectorIndexed()) return false;
1552     return VectorList.Count == 3 && VectorList.LaneIndex <= 1;
1553   }
1554
1555   bool isVecListThreeQHWordIndexed() const {
1556     if (!isDoubleSpacedVectorIndexed()) return false;
1557     return VectorList.Count == 3 && VectorList.LaneIndex <= 3;
1558   }
1559
1560   bool isVecListThreeDWordIndexed() const {
1561     if (!isSingleSpacedVectorIndexed()) return false;
1562     return VectorList.Count == 3 && VectorList.LaneIndex <= 1;
1563   }
1564
1565   bool isVecListFourDByteIndexed() const {
1566     if (!isSingleSpacedVectorIndexed()) return false;
1567     return VectorList.Count == 4 && VectorList.LaneIndex <= 7;
1568   }
1569
1570   bool isVecListFourDHWordIndexed() const {
1571     if (!isSingleSpacedVectorIndexed()) return false;
1572     return VectorList.Count == 4 && VectorList.LaneIndex <= 3;
1573   }
1574
1575   bool isVecListFourQWordIndexed() const {
1576     if (!isDoubleSpacedVectorIndexed()) return false;
1577     return VectorList.Count == 4 && VectorList.LaneIndex <= 1;
1578   }
1579
1580   bool isVecListFourQHWordIndexed() const {
1581     if (!isDoubleSpacedVectorIndexed()) return false;
1582     return VectorList.Count == 4 && VectorList.LaneIndex <= 3;
1583   }
1584
1585   bool isVecListFourDWordIndexed() const {
1586     if (!isSingleSpacedVectorIndexed()) return false;
1587     return VectorList.Count == 4 && VectorList.LaneIndex <= 1;
1588   }
1589
1590   bool isVectorIndex8() const {
1591     if (Kind != k_VectorIndex) return false;
1592     return VectorIndex.Val < 8;
1593   }
1594   bool isVectorIndex16() const {
1595     if (Kind != k_VectorIndex) return false;
1596     return VectorIndex.Val < 4;
1597   }
1598   bool isVectorIndex32() const {
1599     if (Kind != k_VectorIndex) return false;
1600     return VectorIndex.Val < 2;
1601   }
1602
1603   bool isNEONi8splat() const {
1604     if (!isImm()) return false;
1605     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1606     // Must be a constant.
1607     if (!CE) return false;
1608     int64_t Value = CE->getValue();
1609     // i8 value splatted across 8 bytes. The immediate is just the 8 byte
1610     // value.
1611     return Value >= 0 && Value < 256;
1612   }
1613
1614   bool isNEONi16splat() const {
1615     if (isNEONByteReplicate(2))
1616       return false; // Leave that for bytes replication and forbid by default.
1617     if (!isImm())
1618       return false;
1619     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1620     // Must be a constant.
1621     if (!CE) return false;
1622     unsigned Value = CE->getValue();
1623     return ARM_AM::isNEONi16splat(Value);
1624   }
1625
1626   bool isNEONi16splatNot() const {
1627     if (!isImm())
1628       return false;
1629     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1630     // Must be a constant.
1631     if (!CE) return false;
1632     unsigned Value = CE->getValue();
1633     return ARM_AM::isNEONi16splat(~Value & 0xffff);
1634   }
1635
1636   bool isNEONi32splat() const {
1637     if (isNEONByteReplicate(4))
1638       return false; // Leave that for bytes replication and forbid by default.
1639     if (!isImm())
1640       return false;
1641     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1642     // Must be a constant.
1643     if (!CE) return false;
1644     unsigned Value = CE->getValue();
1645     return ARM_AM::isNEONi32splat(Value);
1646   }
1647
1648   bool isNEONi32splatNot() const {
1649     if (!isImm())
1650       return false;
1651     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1652     // Must be a constant.
1653     if (!CE) return false;
1654     unsigned Value = CE->getValue();
1655     return ARM_AM::isNEONi32splat(~Value);
1656   }
1657
1658   bool isNEONByteReplicate(unsigned NumBytes) const {
1659     if (!isImm())
1660       return false;
1661     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1662     // Must be a constant.
1663     if (!CE)
1664       return false;
1665     int64_t Value = CE->getValue();
1666     if (!Value)
1667       return false; // Don't bother with zero.
1668
1669     unsigned char B = Value & 0xff;
1670     for (unsigned i = 1; i < NumBytes; ++i) {
1671       Value >>= 8;
1672       if ((Value & 0xff) != B)
1673         return false;
1674     }
1675     return true;
1676   }
1677   bool isNEONi16ByteReplicate() const { return isNEONByteReplicate(2); }
1678   bool isNEONi32ByteReplicate() const { return isNEONByteReplicate(4); }
1679   bool isNEONi32vmov() const {
1680     if (isNEONByteReplicate(4))
1681       return false; // Let it to be classified as byte-replicate case.
1682     if (!isImm())
1683       return false;
1684     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1685     // Must be a constant.
1686     if (!CE)
1687       return false;
1688     int64_t Value = CE->getValue();
1689     // i32 value with set bits only in one byte X000, 0X00, 00X0, or 000X,
1690     // for VMOV/VMVN only, 00Xf or 0Xff are also accepted.
1691     // FIXME: This is probably wrong and a copy and paste from previous example
1692     return (Value >= 0 && Value < 256) ||
1693       (Value >= 0x0100 && Value <= 0xff00) ||
1694       (Value >= 0x010000 && Value <= 0xff0000) ||
1695       (Value >= 0x01000000 && Value <= 0xff000000) ||
1696       (Value >= 0x01ff && Value <= 0xffff && (Value & 0xff) == 0xff) ||
1697       (Value >= 0x01ffff && Value <= 0xffffff && (Value & 0xffff) == 0xffff);
1698   }
1699   bool isNEONi32vmovNeg() const {
1700     if (!isImm()) return false;
1701     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1702     // Must be a constant.
1703     if (!CE) return false;
1704     int64_t Value = ~CE->getValue();
1705     // i32 value with set bits only in one byte X000, 0X00, 00X0, or 000X,
1706     // for VMOV/VMVN only, 00Xf or 0Xff are also accepted.
1707     // FIXME: This is probably wrong and a copy and paste from previous example
1708     return (Value >= 0 && Value < 256) ||
1709       (Value >= 0x0100 && Value <= 0xff00) ||
1710       (Value >= 0x010000 && Value <= 0xff0000) ||
1711       (Value >= 0x01000000 && Value <= 0xff000000) ||
1712       (Value >= 0x01ff && Value <= 0xffff && (Value & 0xff) == 0xff) ||
1713       (Value >= 0x01ffff && Value <= 0xffffff && (Value & 0xffff) == 0xffff);
1714   }
1715
1716   bool isNEONi64splat() const {
1717     if (!isImm()) return false;
1718     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1719     // Must be a constant.
1720     if (!CE) return false;
1721     uint64_t Value = CE->getValue();
1722     // i64 value with each byte being either 0 or 0xff.
1723     for (unsigned i = 0; i < 8; ++i)
1724       if ((Value & 0xff) != 0 && (Value & 0xff) != 0xff) return false;
1725     return true;
1726   }
1727
1728   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
1729     // Add as immediates when possible.  Null MCExpr = 0.
1730     if (!Expr)
1731       Inst.addOperand(MCOperand::CreateImm(0));
1732     else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
1733       Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
1734     else
1735       Inst.addOperand(MCOperand::CreateExpr(Expr));
1736   }
1737
1738   void addCondCodeOperands(MCInst &Inst, unsigned N) const {
1739     assert(N == 2 && "Invalid number of operands!");
1740     Inst.addOperand(MCOperand::CreateImm(unsigned(getCondCode())));
1741     unsigned RegNum = getCondCode() == ARMCC::AL ? 0: ARM::CPSR;
1742     Inst.addOperand(MCOperand::CreateReg(RegNum));
1743   }
1744
1745   void addCoprocNumOperands(MCInst &Inst, unsigned N) const {
1746     assert(N == 1 && "Invalid number of operands!");
1747     Inst.addOperand(MCOperand::CreateImm(getCoproc()));
1748   }
1749
1750   void addCoprocRegOperands(MCInst &Inst, unsigned N) const {
1751     assert(N == 1 && "Invalid number of operands!");
1752     Inst.addOperand(MCOperand::CreateImm(getCoproc()));
1753   }
1754
1755   void addCoprocOptionOperands(MCInst &Inst, unsigned N) const {
1756     assert(N == 1 && "Invalid number of operands!");
1757     Inst.addOperand(MCOperand::CreateImm(CoprocOption.Val));
1758   }
1759
1760   void addITMaskOperands(MCInst &Inst, unsigned N) const {
1761     assert(N == 1 && "Invalid number of operands!");
1762     Inst.addOperand(MCOperand::CreateImm(ITMask.Mask));
1763   }
1764
1765   void addITCondCodeOperands(MCInst &Inst, unsigned N) const {
1766     assert(N == 1 && "Invalid number of operands!");
1767     Inst.addOperand(MCOperand::CreateImm(unsigned(getCondCode())));
1768   }
1769
1770   void addCCOutOperands(MCInst &Inst, unsigned N) const {
1771     assert(N == 1 && "Invalid number of operands!");
1772     Inst.addOperand(MCOperand::CreateReg(getReg()));
1773   }
1774
1775   void addRegOperands(MCInst &Inst, unsigned N) const {
1776     assert(N == 1 && "Invalid number of operands!");
1777     Inst.addOperand(MCOperand::CreateReg(getReg()));
1778   }
1779
1780   void addRegShiftedRegOperands(MCInst &Inst, unsigned N) const {
1781     assert(N == 3 && "Invalid number of operands!");
1782     assert(isRegShiftedReg() &&
1783            "addRegShiftedRegOperands() on non-RegShiftedReg!");
1784     Inst.addOperand(MCOperand::CreateReg(RegShiftedReg.SrcReg));
1785     Inst.addOperand(MCOperand::CreateReg(RegShiftedReg.ShiftReg));
1786     Inst.addOperand(MCOperand::CreateImm(
1787       ARM_AM::getSORegOpc(RegShiftedReg.ShiftTy, RegShiftedReg.ShiftImm)));
1788   }
1789
1790   void addRegShiftedImmOperands(MCInst &Inst, unsigned N) const {
1791     assert(N == 2 && "Invalid number of operands!");
1792     assert(isRegShiftedImm() &&
1793            "addRegShiftedImmOperands() on non-RegShiftedImm!");
1794     Inst.addOperand(MCOperand::CreateReg(RegShiftedImm.SrcReg));
1795     // Shift of #32 is encoded as 0 where permitted
1796     unsigned Imm = (RegShiftedImm.ShiftImm == 32 ? 0 : RegShiftedImm.ShiftImm);
1797     Inst.addOperand(MCOperand::CreateImm(
1798       ARM_AM::getSORegOpc(RegShiftedImm.ShiftTy, Imm)));
1799   }
1800
1801   void addShifterImmOperands(MCInst &Inst, unsigned N) const {
1802     assert(N == 1 && "Invalid number of operands!");
1803     Inst.addOperand(MCOperand::CreateImm((ShifterImm.isASR << 5) |
1804                                          ShifterImm.Imm));
1805   }
1806
1807   void addRegListOperands(MCInst &Inst, unsigned N) const {
1808     assert(N == 1 && "Invalid number of operands!");
1809     const SmallVectorImpl<unsigned> &RegList = getRegList();
1810     for (SmallVectorImpl<unsigned>::const_iterator
1811            I = RegList.begin(), E = RegList.end(); I != E; ++I)
1812       Inst.addOperand(MCOperand::CreateReg(*I));
1813   }
1814
1815   void addDPRRegListOperands(MCInst &Inst, unsigned N) const {
1816     addRegListOperands(Inst, N);
1817   }
1818
1819   void addSPRRegListOperands(MCInst &Inst, unsigned N) const {
1820     addRegListOperands(Inst, N);
1821   }
1822
1823   void addRotImmOperands(MCInst &Inst, unsigned N) const {
1824     assert(N == 1 && "Invalid number of operands!");
1825     // Encoded as val>>3. The printer handles display as 8, 16, 24.
1826     Inst.addOperand(MCOperand::CreateImm(RotImm.Imm >> 3));
1827   }
1828
1829   void addBitfieldOperands(MCInst &Inst, unsigned N) const {
1830     assert(N == 1 && "Invalid number of operands!");
1831     // Munge the lsb/width into a bitfield mask.
1832     unsigned lsb = Bitfield.LSB;
1833     unsigned width = Bitfield.Width;
1834     // Make a 32-bit mask w/ the referenced bits clear and all other bits set.
1835     uint32_t Mask = ~(((uint32_t)0xffffffff >> lsb) << (32 - width) >>
1836                       (32 - (lsb + width)));
1837     Inst.addOperand(MCOperand::CreateImm(Mask));
1838   }
1839
1840   void addImmOperands(MCInst &Inst, unsigned N) const {
1841     assert(N == 1 && "Invalid number of operands!");
1842     addExpr(Inst, getImm());
1843   }
1844
1845   void addFBits16Operands(MCInst &Inst, unsigned N) const {
1846     assert(N == 1 && "Invalid number of operands!");
1847     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1848     Inst.addOperand(MCOperand::CreateImm(16 - CE->getValue()));
1849   }
1850
1851   void addFBits32Operands(MCInst &Inst, unsigned N) const {
1852     assert(N == 1 && "Invalid number of operands!");
1853     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1854     Inst.addOperand(MCOperand::CreateImm(32 - CE->getValue()));
1855   }
1856
1857   void addFPImmOperands(MCInst &Inst, unsigned N) const {
1858     assert(N == 1 && "Invalid number of operands!");
1859     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1860     int Val = ARM_AM::getFP32Imm(APInt(32, CE->getValue()));
1861     Inst.addOperand(MCOperand::CreateImm(Val));
1862   }
1863
1864   void addImm8s4Operands(MCInst &Inst, unsigned N) const {
1865     assert(N == 1 && "Invalid number of operands!");
1866     // FIXME: We really want to scale the value here, but the LDRD/STRD
1867     // instruction don't encode operands that way yet.
1868     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1869     Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
1870   }
1871
1872   void addImm0_1020s4Operands(MCInst &Inst, unsigned N) const {
1873     assert(N == 1 && "Invalid number of operands!");
1874     // The immediate is scaled by four in the encoding and is stored
1875     // in the MCInst as such. Lop off the low two bits here.
1876     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1877     Inst.addOperand(MCOperand::CreateImm(CE->getValue() / 4));
1878   }
1879
1880   void addImm0_508s4NegOperands(MCInst &Inst, unsigned N) const {
1881     assert(N == 1 && "Invalid number of operands!");
1882     // The immediate is scaled by four in the encoding and is stored
1883     // in the MCInst as such. Lop off the low two bits here.
1884     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1885     Inst.addOperand(MCOperand::CreateImm(-(CE->getValue() / 4)));
1886   }
1887
1888   void addImm0_508s4Operands(MCInst &Inst, unsigned N) const {
1889     assert(N == 1 && "Invalid number of operands!");
1890     // The immediate is scaled by four in the encoding and is stored
1891     // in the MCInst as such. Lop off the low two bits here.
1892     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1893     Inst.addOperand(MCOperand::CreateImm(CE->getValue() / 4));
1894   }
1895
1896   void addImm1_16Operands(MCInst &Inst, unsigned N) const {
1897     assert(N == 1 && "Invalid number of operands!");
1898     // The constant encodes as the immediate-1, and we store in the instruction
1899     // the bits as encoded, so subtract off one here.
1900     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1901     Inst.addOperand(MCOperand::CreateImm(CE->getValue() - 1));
1902   }
1903
1904   void addImm1_32Operands(MCInst &Inst, unsigned N) const {
1905     assert(N == 1 && "Invalid number of operands!");
1906     // The constant encodes as the immediate-1, and we store in the instruction
1907     // the bits as encoded, so subtract off one here.
1908     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1909     Inst.addOperand(MCOperand::CreateImm(CE->getValue() - 1));
1910   }
1911
1912   void addImmThumbSROperands(MCInst &Inst, unsigned N) const {
1913     assert(N == 1 && "Invalid number of operands!");
1914     // The constant encodes as the immediate, except for 32, which encodes as
1915     // zero.
1916     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1917     unsigned Imm = CE->getValue();
1918     Inst.addOperand(MCOperand::CreateImm((Imm == 32 ? 0 : Imm)));
1919   }
1920
1921   void addPKHASRImmOperands(MCInst &Inst, unsigned N) const {
1922     assert(N == 1 && "Invalid number of operands!");
1923     // An ASR value of 32 encodes as 0, so that's how we want to add it to
1924     // the instruction as well.
1925     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1926     int Val = CE->getValue();
1927     Inst.addOperand(MCOperand::CreateImm(Val == 32 ? 0 : Val));
1928   }
1929
1930   void addT2SOImmNotOperands(MCInst &Inst, unsigned N) const {
1931     assert(N == 1 && "Invalid number of operands!");
1932     // The operand is actually a t2_so_imm, but we have its bitwise
1933     // negation in the assembly source, so twiddle it here.
1934     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1935     Inst.addOperand(MCOperand::CreateImm(~CE->getValue()));
1936   }
1937
1938   void addT2SOImmNegOperands(MCInst &Inst, unsigned N) const {
1939     assert(N == 1 && "Invalid number of operands!");
1940     // The operand is actually a t2_so_imm, but we have its
1941     // negation in the assembly source, so twiddle it here.
1942     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1943     Inst.addOperand(MCOperand::CreateImm(-CE->getValue()));
1944   }
1945
1946   void addImm0_4095NegOperands(MCInst &Inst, unsigned N) const {
1947     assert(N == 1 && "Invalid number of operands!");
1948     // The operand is actually an imm0_4095, but we have its
1949     // negation in the assembly source, so twiddle it here.
1950     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1951     Inst.addOperand(MCOperand::CreateImm(-CE->getValue()));
1952   }
1953
1954   void addUnsignedOffset_b8s2Operands(MCInst &Inst, unsigned N) const {
1955     if(const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm())) {
1956       Inst.addOperand(MCOperand::CreateImm(CE->getValue() >> 2));
1957       return;
1958     }
1959
1960     const MCSymbolRefExpr *SR = dyn_cast<MCSymbolRefExpr>(Imm.Val);
1961     assert(SR && "Unknown value type!");
1962     Inst.addOperand(MCOperand::CreateExpr(SR));
1963   }
1964
1965   void addThumbMemPCOperands(MCInst &Inst, unsigned N) const {
1966     assert(N == 1 && "Invalid number of operands!");
1967     if (isImm()) {
1968       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1969       if (CE) {
1970         Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
1971         return;
1972       }
1973
1974       const MCSymbolRefExpr *SR = dyn_cast<MCSymbolRefExpr>(Imm.Val);
1975       assert(SR && "Unknown value type!");
1976       Inst.addOperand(MCOperand::CreateExpr(SR));
1977       return;
1978     }
1979
1980     assert(isMem()  && "Unknown value type!");
1981     assert(isa<MCConstantExpr>(Memory.OffsetImm) && "Unknown value type!");
1982     Inst.addOperand(MCOperand::CreateImm(Memory.OffsetImm->getValue()));
1983   }
1984
1985   void addARMSOImmNotOperands(MCInst &Inst, unsigned N) const {
1986     assert(N == 1 && "Invalid number of operands!");
1987     // The operand is actually a so_imm, but we have its bitwise
1988     // negation in the assembly source, so twiddle it here.
1989     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1990     Inst.addOperand(MCOperand::CreateImm(~CE->getValue()));
1991   }
1992
1993   void addARMSOImmNegOperands(MCInst &Inst, unsigned N) const {
1994     assert(N == 1 && "Invalid number of operands!");
1995     // The operand is actually a so_imm, but we have its
1996     // negation in the assembly source, so twiddle it here.
1997     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1998     Inst.addOperand(MCOperand::CreateImm(-CE->getValue()));
1999   }
2000
2001   void addMemBarrierOptOperands(MCInst &Inst, unsigned N) const {
2002     assert(N == 1 && "Invalid number of operands!");
2003     Inst.addOperand(MCOperand::CreateImm(unsigned(getMemBarrierOpt())));
2004   }
2005
2006   void addInstSyncBarrierOptOperands(MCInst &Inst, unsigned N) const {
2007     assert(N == 1 && "Invalid number of operands!");
2008     Inst.addOperand(MCOperand::CreateImm(unsigned(getInstSyncBarrierOpt())));
2009   }
2010
2011   void addMemNoOffsetOperands(MCInst &Inst, unsigned N) const {
2012     assert(N == 1 && "Invalid number of operands!");
2013     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
2014   }
2015
2016   void addMemPCRelImm12Operands(MCInst &Inst, unsigned N) const {
2017     assert(N == 1 && "Invalid number of operands!");
2018     int32_t Imm = Memory.OffsetImm->getValue();
2019     Inst.addOperand(MCOperand::CreateImm(Imm));
2020   }
2021
2022   void addAdrLabelOperands(MCInst &Inst, unsigned N) const {
2023     assert(N == 1 && "Invalid number of operands!");
2024     assert(isImm() && "Not an immediate!");
2025
2026     // If we have an immediate that's not a constant, treat it as a label
2027     // reference needing a fixup. 
2028     if (!isa<MCConstantExpr>(getImm())) {
2029       Inst.addOperand(MCOperand::CreateExpr(getImm()));
2030       return;
2031     }
2032
2033     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2034     int Val = CE->getValue();
2035     Inst.addOperand(MCOperand::CreateImm(Val));
2036   }
2037
2038   void addAlignedMemoryOperands(MCInst &Inst, unsigned N) const {
2039     assert(N == 2 && "Invalid number of operands!");
2040     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
2041     Inst.addOperand(MCOperand::CreateImm(Memory.Alignment));
2042   }
2043
2044   void addDupAlignedMemoryNoneOperands(MCInst &Inst, unsigned N) const {
2045     addAlignedMemoryOperands(Inst, N);
2046   }
2047
2048   void addAlignedMemoryNoneOperands(MCInst &Inst, unsigned N) const {
2049     addAlignedMemoryOperands(Inst, N);
2050   }
2051
2052   void addAlignedMemory16Operands(MCInst &Inst, unsigned N) const {
2053     addAlignedMemoryOperands(Inst, N);
2054   }
2055
2056   void addDupAlignedMemory16Operands(MCInst &Inst, unsigned N) const {
2057     addAlignedMemoryOperands(Inst, N);
2058   }
2059
2060   void addAlignedMemory32Operands(MCInst &Inst, unsigned N) const {
2061     addAlignedMemoryOperands(Inst, N);
2062   }
2063
2064   void addDupAlignedMemory32Operands(MCInst &Inst, unsigned N) const {
2065     addAlignedMemoryOperands(Inst, N);
2066   }
2067
2068   void addAlignedMemory64Operands(MCInst &Inst, unsigned N) const {
2069     addAlignedMemoryOperands(Inst, N);
2070   }
2071
2072   void addDupAlignedMemory64Operands(MCInst &Inst, unsigned N) const {
2073     addAlignedMemoryOperands(Inst, N);
2074   }
2075
2076   void addAlignedMemory64or128Operands(MCInst &Inst, unsigned N) const {
2077     addAlignedMemoryOperands(Inst, N);
2078   }
2079
2080   void addDupAlignedMemory64or128Operands(MCInst &Inst, unsigned N) const {
2081     addAlignedMemoryOperands(Inst, N);
2082   }
2083
2084   void addAlignedMemory64or128or256Operands(MCInst &Inst, unsigned N) const {
2085     addAlignedMemoryOperands(Inst, N);
2086   }
2087
2088   void addAddrMode2Operands(MCInst &Inst, unsigned N) const {
2089     assert(N == 3 && "Invalid number of operands!");
2090     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2091     if (!Memory.OffsetRegNum) {
2092       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2093       // Special case for #-0
2094       if (Val == INT32_MIN) Val = 0;
2095       if (Val < 0) Val = -Val;
2096       Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
2097     } else {
2098       // For register offset, we encode the shift type and negation flag
2099       // here.
2100       Val = ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
2101                               Memory.ShiftImm, Memory.ShiftType);
2102     }
2103     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
2104     Inst.addOperand(MCOperand::CreateReg(Memory.OffsetRegNum));
2105     Inst.addOperand(MCOperand::CreateImm(Val));
2106   }
2107
2108   void addAM2OffsetImmOperands(MCInst &Inst, unsigned N) const {
2109     assert(N == 2 && "Invalid number of operands!");
2110     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2111     assert(CE && "non-constant AM2OffsetImm operand!");
2112     int32_t Val = CE->getValue();
2113     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2114     // Special case for #-0
2115     if (Val == INT32_MIN) Val = 0;
2116     if (Val < 0) Val = -Val;
2117     Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
2118     Inst.addOperand(MCOperand::CreateReg(0));
2119     Inst.addOperand(MCOperand::CreateImm(Val));
2120   }
2121
2122   void addAddrMode3Operands(MCInst &Inst, unsigned N) const {
2123     assert(N == 3 && "Invalid number of operands!");
2124     // If we have an immediate that's not a constant, treat it as a label
2125     // reference needing a fixup. If it is a constant, it's something else
2126     // and we reject it.
2127     if (isImm()) {
2128       Inst.addOperand(MCOperand::CreateExpr(getImm()));
2129       Inst.addOperand(MCOperand::CreateReg(0));
2130       Inst.addOperand(MCOperand::CreateImm(0));
2131       return;
2132     }
2133
2134     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2135     if (!Memory.OffsetRegNum) {
2136       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2137       // Special case for #-0
2138       if (Val == INT32_MIN) Val = 0;
2139       if (Val < 0) Val = -Val;
2140       Val = ARM_AM::getAM3Opc(AddSub, Val);
2141     } else {
2142       // For register offset, we encode the shift type and negation flag
2143       // here.
2144       Val = ARM_AM::getAM3Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add, 0);
2145     }
2146     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
2147     Inst.addOperand(MCOperand::CreateReg(Memory.OffsetRegNum));
2148     Inst.addOperand(MCOperand::CreateImm(Val));
2149   }
2150
2151   void addAM3OffsetOperands(MCInst &Inst, unsigned N) const {
2152     assert(N == 2 && "Invalid number of operands!");
2153     if (Kind == k_PostIndexRegister) {
2154       int32_t Val =
2155         ARM_AM::getAM3Opc(PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub, 0);
2156       Inst.addOperand(MCOperand::CreateReg(PostIdxReg.RegNum));
2157       Inst.addOperand(MCOperand::CreateImm(Val));
2158       return;
2159     }
2160
2161     // Constant offset.
2162     const MCConstantExpr *CE = static_cast<const MCConstantExpr*>(getImm());
2163     int32_t Val = CE->getValue();
2164     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2165     // Special case for #-0
2166     if (Val == INT32_MIN) Val = 0;
2167     if (Val < 0) Val = -Val;
2168     Val = ARM_AM::getAM3Opc(AddSub, Val);
2169     Inst.addOperand(MCOperand::CreateReg(0));
2170     Inst.addOperand(MCOperand::CreateImm(Val));
2171   }
2172
2173   void addAddrMode5Operands(MCInst &Inst, unsigned N) const {
2174     assert(N == 2 && "Invalid number of operands!");
2175     // If we have an immediate that's not a constant, treat it as a label
2176     // reference needing a fixup. If it is a constant, it's something else
2177     // and we reject it.
2178     if (isImm()) {
2179       Inst.addOperand(MCOperand::CreateExpr(getImm()));
2180       Inst.addOperand(MCOperand::CreateImm(0));
2181       return;
2182     }
2183
2184     // The lower two bits are always zero and as such are not encoded.
2185     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 4 : 0;
2186     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2187     // Special case for #-0
2188     if (Val == INT32_MIN) Val = 0;
2189     if (Val < 0) Val = -Val;
2190     Val = ARM_AM::getAM5Opc(AddSub, Val);
2191     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
2192     Inst.addOperand(MCOperand::CreateImm(Val));
2193   }
2194
2195   void addMemImm8s4OffsetOperands(MCInst &Inst, unsigned N) const {
2196     assert(N == 2 && "Invalid number of operands!");
2197     // If we have an immediate that's not a constant, treat it as a label
2198     // reference needing a fixup. If it is a constant, it's something else
2199     // and we reject it.
2200     if (isImm()) {
2201       Inst.addOperand(MCOperand::CreateExpr(getImm()));
2202       Inst.addOperand(MCOperand::CreateImm(0));
2203       return;
2204     }
2205
2206     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2207     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
2208     Inst.addOperand(MCOperand::CreateImm(Val));
2209   }
2210
2211   void addMemImm0_1020s4OffsetOperands(MCInst &Inst, unsigned N) const {
2212     assert(N == 2 && "Invalid number of operands!");
2213     // The lower two bits are always zero and as such are not encoded.
2214     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 4 : 0;
2215     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
2216     Inst.addOperand(MCOperand::CreateImm(Val));
2217   }
2218
2219   void addMemImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2220     assert(N == 2 && "Invalid number of operands!");
2221     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2222     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
2223     Inst.addOperand(MCOperand::CreateImm(Val));
2224   }
2225
2226   void addMemPosImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2227     addMemImm8OffsetOperands(Inst, N);
2228   }
2229
2230   void addMemNegImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2231     addMemImm8OffsetOperands(Inst, N);
2232   }
2233
2234   void addMemUImm12OffsetOperands(MCInst &Inst, unsigned N) const {
2235     assert(N == 2 && "Invalid number of operands!");
2236     // If this is an immediate, it's a label reference.
2237     if (isImm()) {
2238       addExpr(Inst, getImm());
2239       Inst.addOperand(MCOperand::CreateImm(0));
2240       return;
2241     }
2242
2243     // Otherwise, it's a normal memory reg+offset.
2244     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2245     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
2246     Inst.addOperand(MCOperand::CreateImm(Val));
2247   }
2248
2249   void addMemImm12OffsetOperands(MCInst &Inst, unsigned N) const {
2250     assert(N == 2 && "Invalid number of operands!");
2251     // If this is an immediate, it's a label reference.
2252     if (isImm()) {
2253       addExpr(Inst, getImm());
2254       Inst.addOperand(MCOperand::CreateImm(0));
2255       return;
2256     }
2257
2258     // Otherwise, it's a normal memory reg+offset.
2259     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2260     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
2261     Inst.addOperand(MCOperand::CreateImm(Val));
2262   }
2263
2264   void addMemTBBOperands(MCInst &Inst, unsigned N) const {
2265     assert(N == 2 && "Invalid number of operands!");
2266     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
2267     Inst.addOperand(MCOperand::CreateReg(Memory.OffsetRegNum));
2268   }
2269
2270   void addMemTBHOperands(MCInst &Inst, unsigned N) const {
2271     assert(N == 2 && "Invalid number of operands!");
2272     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
2273     Inst.addOperand(MCOperand::CreateReg(Memory.OffsetRegNum));
2274   }
2275
2276   void addMemRegOffsetOperands(MCInst &Inst, unsigned N) const {
2277     assert(N == 3 && "Invalid number of operands!");
2278     unsigned Val =
2279       ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
2280                         Memory.ShiftImm, Memory.ShiftType);
2281     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
2282     Inst.addOperand(MCOperand::CreateReg(Memory.OffsetRegNum));
2283     Inst.addOperand(MCOperand::CreateImm(Val));
2284   }
2285
2286   void addT2MemRegOffsetOperands(MCInst &Inst, unsigned N) const {
2287     assert(N == 3 && "Invalid number of operands!");
2288     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
2289     Inst.addOperand(MCOperand::CreateReg(Memory.OffsetRegNum));
2290     Inst.addOperand(MCOperand::CreateImm(Memory.ShiftImm));
2291   }
2292
2293   void addMemThumbRROperands(MCInst &Inst, unsigned N) const {
2294     assert(N == 2 && "Invalid number of operands!");
2295     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
2296     Inst.addOperand(MCOperand::CreateReg(Memory.OffsetRegNum));
2297   }
2298
2299   void addMemThumbRIs4Operands(MCInst &Inst, unsigned N) const {
2300     assert(N == 2 && "Invalid number of operands!");
2301     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 4) : 0;
2302     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
2303     Inst.addOperand(MCOperand::CreateImm(Val));
2304   }
2305
2306   void addMemThumbRIs2Operands(MCInst &Inst, unsigned N) const {
2307     assert(N == 2 && "Invalid number of operands!");
2308     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 2) : 0;
2309     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
2310     Inst.addOperand(MCOperand::CreateImm(Val));
2311   }
2312
2313   void addMemThumbRIs1Operands(MCInst &Inst, unsigned N) const {
2314     assert(N == 2 && "Invalid number of operands!");
2315     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue()) : 0;
2316     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
2317     Inst.addOperand(MCOperand::CreateImm(Val));
2318   }
2319
2320   void addMemThumbSPIOperands(MCInst &Inst, unsigned N) const {
2321     assert(N == 2 && "Invalid number of operands!");
2322     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 4) : 0;
2323     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
2324     Inst.addOperand(MCOperand::CreateImm(Val));
2325   }
2326
2327   void addPostIdxImm8Operands(MCInst &Inst, unsigned N) const {
2328     assert(N == 1 && "Invalid number of operands!");
2329     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2330     assert(CE && "non-constant post-idx-imm8 operand!");
2331     int Imm = CE->getValue();
2332     bool isAdd = Imm >= 0;
2333     if (Imm == INT32_MIN) Imm = 0;
2334     Imm = (Imm < 0 ? -Imm : Imm) | (int)isAdd << 8;
2335     Inst.addOperand(MCOperand::CreateImm(Imm));
2336   }
2337
2338   void addPostIdxImm8s4Operands(MCInst &Inst, unsigned N) const {
2339     assert(N == 1 && "Invalid number of operands!");
2340     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2341     assert(CE && "non-constant post-idx-imm8s4 operand!");
2342     int Imm = CE->getValue();
2343     bool isAdd = Imm >= 0;
2344     if (Imm == INT32_MIN) Imm = 0;
2345     // Immediate is scaled by 4.
2346     Imm = ((Imm < 0 ? -Imm : Imm) / 4) | (int)isAdd << 8;
2347     Inst.addOperand(MCOperand::CreateImm(Imm));
2348   }
2349
2350   void addPostIdxRegOperands(MCInst &Inst, unsigned N) const {
2351     assert(N == 2 && "Invalid number of operands!");
2352     Inst.addOperand(MCOperand::CreateReg(PostIdxReg.RegNum));
2353     Inst.addOperand(MCOperand::CreateImm(PostIdxReg.isAdd));
2354   }
2355
2356   void addPostIdxRegShiftedOperands(MCInst &Inst, unsigned N) const {
2357     assert(N == 2 && "Invalid number of operands!");
2358     Inst.addOperand(MCOperand::CreateReg(PostIdxReg.RegNum));
2359     // The sign, shift type, and shift amount are encoded in a single operand
2360     // using the AM2 encoding helpers.
2361     ARM_AM::AddrOpc opc = PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub;
2362     unsigned Imm = ARM_AM::getAM2Opc(opc, PostIdxReg.ShiftImm,
2363                                      PostIdxReg.ShiftTy);
2364     Inst.addOperand(MCOperand::CreateImm(Imm));
2365   }
2366
2367   void addMSRMaskOperands(MCInst &Inst, unsigned N) const {
2368     assert(N == 1 && "Invalid number of operands!");
2369     Inst.addOperand(MCOperand::CreateImm(unsigned(getMSRMask())));
2370   }
2371
2372   void addBankedRegOperands(MCInst &Inst, unsigned N) const {
2373     assert(N == 1 && "Invalid number of operands!");
2374     Inst.addOperand(MCOperand::CreateImm(unsigned(getBankedReg())));
2375   }
2376
2377   void addProcIFlagsOperands(MCInst &Inst, unsigned N) const {
2378     assert(N == 1 && "Invalid number of operands!");
2379     Inst.addOperand(MCOperand::CreateImm(unsigned(getProcIFlags())));
2380   }
2381
2382   void addVecListOperands(MCInst &Inst, unsigned N) const {
2383     assert(N == 1 && "Invalid number of operands!");
2384     Inst.addOperand(MCOperand::CreateReg(VectorList.RegNum));
2385   }
2386
2387   void addVecListIndexedOperands(MCInst &Inst, unsigned N) const {
2388     assert(N == 2 && "Invalid number of operands!");
2389     Inst.addOperand(MCOperand::CreateReg(VectorList.RegNum));
2390     Inst.addOperand(MCOperand::CreateImm(VectorList.LaneIndex));
2391   }
2392
2393   void addVectorIndex8Operands(MCInst &Inst, unsigned N) const {
2394     assert(N == 1 && "Invalid number of operands!");
2395     Inst.addOperand(MCOperand::CreateImm(getVectorIndex()));
2396   }
2397
2398   void addVectorIndex16Operands(MCInst &Inst, unsigned N) const {
2399     assert(N == 1 && "Invalid number of operands!");
2400     Inst.addOperand(MCOperand::CreateImm(getVectorIndex()));
2401   }
2402
2403   void addVectorIndex32Operands(MCInst &Inst, unsigned N) const {
2404     assert(N == 1 && "Invalid number of operands!");
2405     Inst.addOperand(MCOperand::CreateImm(getVectorIndex()));
2406   }
2407
2408   void addNEONi8splatOperands(MCInst &Inst, unsigned N) const {
2409     assert(N == 1 && "Invalid number of operands!");
2410     // The immediate encodes the type of constant as well as the value.
2411     // Mask in that this is an i8 splat.
2412     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2413     Inst.addOperand(MCOperand::CreateImm(CE->getValue() | 0xe00));
2414   }
2415
2416   void addNEONi16splatOperands(MCInst &Inst, unsigned N) const {
2417     assert(N == 1 && "Invalid number of operands!");
2418     // The immediate encodes the type of constant as well as the value.
2419     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2420     unsigned Value = CE->getValue();
2421     Value = ARM_AM::encodeNEONi16splat(Value);
2422     Inst.addOperand(MCOperand::CreateImm(Value));
2423   }
2424
2425   void addNEONi16splatNotOperands(MCInst &Inst, unsigned N) const {
2426     assert(N == 1 && "Invalid number of operands!");
2427     // The immediate encodes the type of constant as well as the value.
2428     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2429     unsigned Value = CE->getValue();
2430     Value = ARM_AM::encodeNEONi16splat(~Value & 0xffff);
2431     Inst.addOperand(MCOperand::CreateImm(Value));
2432   }
2433
2434   void addNEONi32splatOperands(MCInst &Inst, unsigned N) const {
2435     assert(N == 1 && "Invalid number of operands!");
2436     // The immediate encodes the type of constant as well as the value.
2437     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2438     unsigned Value = CE->getValue();
2439     Value = ARM_AM::encodeNEONi32splat(Value);
2440     Inst.addOperand(MCOperand::CreateImm(Value));
2441   }
2442
2443   void addNEONi32splatNotOperands(MCInst &Inst, unsigned N) const {
2444     assert(N == 1 && "Invalid number of operands!");
2445     // The immediate encodes the type of constant as well as the value.
2446     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2447     unsigned Value = CE->getValue();
2448     Value = ARM_AM::encodeNEONi32splat(~Value);
2449     Inst.addOperand(MCOperand::CreateImm(Value));
2450   }
2451
2452   void addNEONinvByteReplicateOperands(MCInst &Inst, unsigned N) const {
2453     assert(N == 1 && "Invalid number of operands!");
2454     // The immediate encodes the type of constant as well as the value.
2455     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2456     unsigned Value = CE->getValue();
2457     assert((Inst.getOpcode() == ARM::VMOVv8i8 ||
2458             Inst.getOpcode() == ARM::VMOVv16i8) &&
2459            "All vmvn instructions that wants to replicate non-zero byte "
2460            "always must be replaced with VMOVv8i8 or VMOVv16i8.");
2461     unsigned B = ((~Value) & 0xff);
2462     B |= 0xe00; // cmode = 0b1110
2463     Inst.addOperand(MCOperand::CreateImm(B));
2464   }
2465   void addNEONi32vmovOperands(MCInst &Inst, unsigned N) const {
2466     assert(N == 1 && "Invalid number of operands!");
2467     // The immediate encodes the type of constant as well as the value.
2468     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2469     unsigned Value = CE->getValue();
2470     if (Value >= 256 && Value <= 0xffff)
2471       Value = (Value >> 8) | ((Value & 0xff) ? 0xc00 : 0x200);
2472     else if (Value > 0xffff && Value <= 0xffffff)
2473       Value = (Value >> 16) | ((Value & 0xff) ? 0xd00 : 0x400);
2474     else if (Value > 0xffffff)
2475       Value = (Value >> 24) | 0x600;
2476     Inst.addOperand(MCOperand::CreateImm(Value));
2477   }
2478
2479   void addNEONvmovByteReplicateOperands(MCInst &Inst, unsigned N) const {
2480     assert(N == 1 && "Invalid number of operands!");
2481     // The immediate encodes the type of constant as well as the value.
2482     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2483     unsigned Value = CE->getValue();
2484     assert((Inst.getOpcode() == ARM::VMOVv8i8 ||
2485             Inst.getOpcode() == ARM::VMOVv16i8) &&
2486            "All instructions that wants to replicate non-zero byte "
2487            "always must be replaced with VMOVv8i8 or VMOVv16i8.");
2488     unsigned B = Value & 0xff;
2489     B |= 0xe00; // cmode = 0b1110
2490     Inst.addOperand(MCOperand::CreateImm(B));
2491   }
2492   void addNEONi32vmovNegOperands(MCInst &Inst, unsigned N) const {
2493     assert(N == 1 && "Invalid number of operands!");
2494     // The immediate encodes the type of constant as well as the value.
2495     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2496     unsigned Value = ~CE->getValue();
2497     if (Value >= 256 && Value <= 0xffff)
2498       Value = (Value >> 8) | ((Value & 0xff) ? 0xc00 : 0x200);
2499     else if (Value > 0xffff && Value <= 0xffffff)
2500       Value = (Value >> 16) | ((Value & 0xff) ? 0xd00 : 0x400);
2501     else if (Value > 0xffffff)
2502       Value = (Value >> 24) | 0x600;
2503     Inst.addOperand(MCOperand::CreateImm(Value));
2504   }
2505
2506   void addNEONi64splatOperands(MCInst &Inst, unsigned N) const {
2507     assert(N == 1 && "Invalid number of operands!");
2508     // The immediate encodes the type of constant as well as the value.
2509     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2510     uint64_t Value = CE->getValue();
2511     unsigned Imm = 0;
2512     for (unsigned i = 0; i < 8; ++i, Value >>= 8) {
2513       Imm |= (Value & 1) << i;
2514     }
2515     Inst.addOperand(MCOperand::CreateImm(Imm | 0x1e00));
2516   }
2517
2518   void print(raw_ostream &OS) const override;
2519
2520   static std::unique_ptr<ARMOperand> CreateITMask(unsigned Mask, SMLoc S) {
2521     auto Op = make_unique<ARMOperand>(k_ITCondMask);
2522     Op->ITMask.Mask = Mask;
2523     Op->StartLoc = S;
2524     Op->EndLoc = S;
2525     return Op;
2526   }
2527
2528   static std::unique_ptr<ARMOperand> CreateCondCode(ARMCC::CondCodes CC,
2529                                                     SMLoc S) {
2530     auto Op = make_unique<ARMOperand>(k_CondCode);
2531     Op->CC.Val = CC;
2532     Op->StartLoc = S;
2533     Op->EndLoc = S;
2534     return Op;
2535   }
2536
2537   static std::unique_ptr<ARMOperand> CreateCoprocNum(unsigned CopVal, SMLoc S) {
2538     auto Op = make_unique<ARMOperand>(k_CoprocNum);
2539     Op->Cop.Val = CopVal;
2540     Op->StartLoc = S;
2541     Op->EndLoc = S;
2542     return Op;
2543   }
2544
2545   static std::unique_ptr<ARMOperand> CreateCoprocReg(unsigned CopVal, SMLoc S) {
2546     auto Op = make_unique<ARMOperand>(k_CoprocReg);
2547     Op->Cop.Val = CopVal;
2548     Op->StartLoc = S;
2549     Op->EndLoc = S;
2550     return Op;
2551   }
2552
2553   static std::unique_ptr<ARMOperand> CreateCoprocOption(unsigned Val, SMLoc S,
2554                                                         SMLoc E) {
2555     auto Op = make_unique<ARMOperand>(k_CoprocOption);
2556     Op->Cop.Val = Val;
2557     Op->StartLoc = S;
2558     Op->EndLoc = E;
2559     return Op;
2560   }
2561
2562   static std::unique_ptr<ARMOperand> CreateCCOut(unsigned RegNum, SMLoc S) {
2563     auto Op = make_unique<ARMOperand>(k_CCOut);
2564     Op->Reg.RegNum = RegNum;
2565     Op->StartLoc = S;
2566     Op->EndLoc = S;
2567     return Op;
2568   }
2569
2570   static std::unique_ptr<ARMOperand> CreateToken(StringRef Str, SMLoc S) {
2571     auto Op = make_unique<ARMOperand>(k_Token);
2572     Op->Tok.Data = Str.data();
2573     Op->Tok.Length = Str.size();
2574     Op->StartLoc = S;
2575     Op->EndLoc = S;
2576     return Op;
2577   }
2578
2579   static std::unique_ptr<ARMOperand> CreateReg(unsigned RegNum, SMLoc S,
2580                                                SMLoc E) {
2581     auto Op = make_unique<ARMOperand>(k_Register);
2582     Op->Reg.RegNum = RegNum;
2583     Op->StartLoc = S;
2584     Op->EndLoc = E;
2585     return Op;
2586   }
2587
2588   static std::unique_ptr<ARMOperand>
2589   CreateShiftedRegister(ARM_AM::ShiftOpc ShTy, unsigned SrcReg,
2590                         unsigned ShiftReg, unsigned ShiftImm, SMLoc S,
2591                         SMLoc E) {
2592     auto Op = make_unique<ARMOperand>(k_ShiftedRegister);
2593     Op->RegShiftedReg.ShiftTy = ShTy;
2594     Op->RegShiftedReg.SrcReg = SrcReg;
2595     Op->RegShiftedReg.ShiftReg = ShiftReg;
2596     Op->RegShiftedReg.ShiftImm = ShiftImm;
2597     Op->StartLoc = S;
2598     Op->EndLoc = E;
2599     return Op;
2600   }
2601
2602   static std::unique_ptr<ARMOperand>
2603   CreateShiftedImmediate(ARM_AM::ShiftOpc ShTy, unsigned SrcReg,
2604                          unsigned ShiftImm, SMLoc S, SMLoc E) {
2605     auto Op = make_unique<ARMOperand>(k_ShiftedImmediate);
2606     Op->RegShiftedImm.ShiftTy = ShTy;
2607     Op->RegShiftedImm.SrcReg = SrcReg;
2608     Op->RegShiftedImm.ShiftImm = ShiftImm;
2609     Op->StartLoc = S;
2610     Op->EndLoc = E;
2611     return Op;
2612   }
2613
2614   static std::unique_ptr<ARMOperand> CreateShifterImm(bool isASR, unsigned Imm,
2615                                                       SMLoc S, SMLoc E) {
2616     auto Op = make_unique<ARMOperand>(k_ShifterImmediate);
2617     Op->ShifterImm.isASR = isASR;
2618     Op->ShifterImm.Imm = Imm;
2619     Op->StartLoc = S;
2620     Op->EndLoc = E;
2621     return Op;
2622   }
2623
2624   static std::unique_ptr<ARMOperand> CreateRotImm(unsigned Imm, SMLoc S,
2625                                                   SMLoc E) {
2626     auto Op = make_unique<ARMOperand>(k_RotateImmediate);
2627     Op->RotImm.Imm = Imm;
2628     Op->StartLoc = S;
2629     Op->EndLoc = E;
2630     return Op;
2631   }
2632
2633   static std::unique_ptr<ARMOperand>
2634   CreateBitfield(unsigned LSB, unsigned Width, SMLoc S, SMLoc E) {
2635     auto Op = make_unique<ARMOperand>(k_BitfieldDescriptor);
2636     Op->Bitfield.LSB = LSB;
2637     Op->Bitfield.Width = Width;
2638     Op->StartLoc = S;
2639     Op->EndLoc = E;
2640     return Op;
2641   }
2642
2643   static std::unique_ptr<ARMOperand>
2644   CreateRegList(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
2645                 SMLoc StartLoc, SMLoc EndLoc) {
2646     assert (Regs.size() > 0 && "RegList contains no registers?");
2647     KindTy Kind = k_RegisterList;
2648
2649     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Regs.front().second))
2650       Kind = k_DPRRegisterList;
2651     else if (ARMMCRegisterClasses[ARM::SPRRegClassID].
2652              contains(Regs.front().second))
2653       Kind = k_SPRRegisterList;
2654
2655     // Sort based on the register encoding values.
2656     array_pod_sort(Regs.begin(), Regs.end());
2657
2658     auto Op = make_unique<ARMOperand>(Kind);
2659     for (SmallVectorImpl<std::pair<unsigned, unsigned> >::const_iterator
2660            I = Regs.begin(), E = Regs.end(); I != E; ++I)
2661       Op->Registers.push_back(I->second);
2662     Op->StartLoc = StartLoc;
2663     Op->EndLoc = EndLoc;
2664     return Op;
2665   }
2666
2667   static std::unique_ptr<ARMOperand> CreateVectorList(unsigned RegNum,
2668                                                       unsigned Count,
2669                                                       bool isDoubleSpaced,
2670                                                       SMLoc S, SMLoc E) {
2671     auto Op = make_unique<ARMOperand>(k_VectorList);
2672     Op->VectorList.RegNum = RegNum;
2673     Op->VectorList.Count = Count;
2674     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
2675     Op->StartLoc = S;
2676     Op->EndLoc = E;
2677     return Op;
2678   }
2679
2680   static std::unique_ptr<ARMOperand>
2681   CreateVectorListAllLanes(unsigned RegNum, unsigned Count, bool isDoubleSpaced,
2682                            SMLoc S, SMLoc E) {
2683     auto Op = make_unique<ARMOperand>(k_VectorListAllLanes);
2684     Op->VectorList.RegNum = RegNum;
2685     Op->VectorList.Count = Count;
2686     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
2687     Op->StartLoc = S;
2688     Op->EndLoc = E;
2689     return Op;
2690   }
2691
2692   static std::unique_ptr<ARMOperand>
2693   CreateVectorListIndexed(unsigned RegNum, unsigned Count, unsigned Index,
2694                           bool isDoubleSpaced, SMLoc S, SMLoc E) {
2695     auto Op = make_unique<ARMOperand>(k_VectorListIndexed);
2696     Op->VectorList.RegNum = RegNum;
2697     Op->VectorList.Count = Count;
2698     Op->VectorList.LaneIndex = Index;
2699     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
2700     Op->StartLoc = S;
2701     Op->EndLoc = E;
2702     return Op;
2703   }
2704
2705   static std::unique_ptr<ARMOperand>
2706   CreateVectorIndex(unsigned Idx, SMLoc S, SMLoc E, MCContext &Ctx) {
2707     auto Op = make_unique<ARMOperand>(k_VectorIndex);
2708     Op->VectorIndex.Val = Idx;
2709     Op->StartLoc = S;
2710     Op->EndLoc = E;
2711     return Op;
2712   }
2713
2714   static std::unique_ptr<ARMOperand> CreateImm(const MCExpr *Val, SMLoc S,
2715                                                SMLoc E) {
2716     auto Op = make_unique<ARMOperand>(k_Immediate);
2717     Op->Imm.Val = Val;
2718     Op->StartLoc = S;
2719     Op->EndLoc = E;
2720     return Op;
2721   }
2722
2723   static std::unique_ptr<ARMOperand>
2724   CreateMem(unsigned BaseRegNum, const MCConstantExpr *OffsetImm,
2725             unsigned OffsetRegNum, ARM_AM::ShiftOpc ShiftType,
2726             unsigned ShiftImm, unsigned Alignment, bool isNegative, SMLoc S,
2727             SMLoc E, SMLoc AlignmentLoc = SMLoc()) {
2728     auto Op = make_unique<ARMOperand>(k_Memory);
2729     Op->Memory.BaseRegNum = BaseRegNum;
2730     Op->Memory.OffsetImm = OffsetImm;
2731     Op->Memory.OffsetRegNum = OffsetRegNum;
2732     Op->Memory.ShiftType = ShiftType;
2733     Op->Memory.ShiftImm = ShiftImm;
2734     Op->Memory.Alignment = Alignment;
2735     Op->Memory.isNegative = isNegative;
2736     Op->StartLoc = S;
2737     Op->EndLoc = E;
2738     Op->AlignmentLoc = AlignmentLoc;
2739     return Op;
2740   }
2741
2742   static std::unique_ptr<ARMOperand>
2743   CreatePostIdxReg(unsigned RegNum, bool isAdd, ARM_AM::ShiftOpc ShiftTy,
2744                    unsigned ShiftImm, SMLoc S, SMLoc E) {
2745     auto Op = make_unique<ARMOperand>(k_PostIndexRegister);
2746     Op->PostIdxReg.RegNum = RegNum;
2747     Op->PostIdxReg.isAdd = isAdd;
2748     Op->PostIdxReg.ShiftTy = ShiftTy;
2749     Op->PostIdxReg.ShiftImm = ShiftImm;
2750     Op->StartLoc = S;
2751     Op->EndLoc = E;
2752     return Op;
2753   }
2754
2755   static std::unique_ptr<ARMOperand> CreateMemBarrierOpt(ARM_MB::MemBOpt Opt,
2756                                                          SMLoc S) {
2757     auto Op = make_unique<ARMOperand>(k_MemBarrierOpt);
2758     Op->MBOpt.Val = Opt;
2759     Op->StartLoc = S;
2760     Op->EndLoc = S;
2761     return Op;
2762   }
2763
2764   static std::unique_ptr<ARMOperand>
2765   CreateInstSyncBarrierOpt(ARM_ISB::InstSyncBOpt Opt, SMLoc S) {
2766     auto Op = make_unique<ARMOperand>(k_InstSyncBarrierOpt);
2767     Op->ISBOpt.Val = Opt;
2768     Op->StartLoc = S;
2769     Op->EndLoc = S;
2770     return Op;
2771   }
2772
2773   static std::unique_ptr<ARMOperand> CreateProcIFlags(ARM_PROC::IFlags IFlags,
2774                                                       SMLoc S) {
2775     auto Op = make_unique<ARMOperand>(k_ProcIFlags);
2776     Op->IFlags.Val = IFlags;
2777     Op->StartLoc = S;
2778     Op->EndLoc = S;
2779     return Op;
2780   }
2781
2782   static std::unique_ptr<ARMOperand> CreateMSRMask(unsigned MMask, SMLoc S) {
2783     auto Op = make_unique<ARMOperand>(k_MSRMask);
2784     Op->MMask.Val = MMask;
2785     Op->StartLoc = S;
2786     Op->EndLoc = S;
2787     return Op;
2788   }
2789
2790   static std::unique_ptr<ARMOperand> CreateBankedReg(unsigned Reg, SMLoc S) {
2791     auto Op = make_unique<ARMOperand>(k_BankedReg);
2792     Op->BankedReg.Val = Reg;
2793     Op->StartLoc = S;
2794     Op->EndLoc = S;
2795     return Op;
2796   }
2797 };
2798
2799 } // end anonymous namespace.
2800
2801 void ARMOperand::print(raw_ostream &OS) const {
2802   switch (Kind) {
2803   case k_CondCode:
2804     OS << "<ARMCC::" << ARMCondCodeToString(getCondCode()) << ">";
2805     break;
2806   case k_CCOut:
2807     OS << "<ccout " << getReg() << ">";
2808     break;
2809   case k_ITCondMask: {
2810     static const char *const MaskStr[] = {
2811       "()", "(t)", "(e)", "(tt)", "(et)", "(te)", "(ee)", "(ttt)", "(ett)",
2812       "(tet)", "(eet)", "(tte)", "(ete)", "(tee)", "(eee)"
2813     };
2814     assert((ITMask.Mask & 0xf) == ITMask.Mask);
2815     OS << "<it-mask " << MaskStr[ITMask.Mask] << ">";
2816     break;
2817   }
2818   case k_CoprocNum:
2819     OS << "<coprocessor number: " << getCoproc() << ">";
2820     break;
2821   case k_CoprocReg:
2822     OS << "<coprocessor register: " << getCoproc() << ">";
2823     break;
2824   case k_CoprocOption:
2825     OS << "<coprocessor option: " << CoprocOption.Val << ">";
2826     break;
2827   case k_MSRMask:
2828     OS << "<mask: " << getMSRMask() << ">";
2829     break;
2830   case k_BankedReg:
2831     OS << "<banked reg: " << getBankedReg() << ">";
2832     break;
2833   case k_Immediate:
2834     getImm()->print(OS);
2835     break;
2836   case k_MemBarrierOpt:
2837     OS << "<ARM_MB::" << MemBOptToString(getMemBarrierOpt(), false) << ">";
2838     break;
2839   case k_InstSyncBarrierOpt:
2840     OS << "<ARM_ISB::" << InstSyncBOptToString(getInstSyncBarrierOpt()) << ">";
2841     break;
2842   case k_Memory:
2843     OS << "<memory "
2844        << " base:" << Memory.BaseRegNum;
2845     OS << ">";
2846     break;
2847   case k_PostIndexRegister:
2848     OS << "post-idx register " << (PostIdxReg.isAdd ? "" : "-")
2849        << PostIdxReg.RegNum;
2850     if (PostIdxReg.ShiftTy != ARM_AM::no_shift)
2851       OS << ARM_AM::getShiftOpcStr(PostIdxReg.ShiftTy) << " "
2852          << PostIdxReg.ShiftImm;
2853     OS << ">";
2854     break;
2855   case k_ProcIFlags: {
2856     OS << "<ARM_PROC::";
2857     unsigned IFlags = getProcIFlags();
2858     for (int i=2; i >= 0; --i)
2859       if (IFlags & (1 << i))
2860         OS << ARM_PROC::IFlagsToString(1 << i);
2861     OS << ">";
2862     break;
2863   }
2864   case k_Register:
2865     OS << "<register " << getReg() << ">";
2866     break;
2867   case k_ShifterImmediate:
2868     OS << "<shift " << (ShifterImm.isASR ? "asr" : "lsl")
2869        << " #" << ShifterImm.Imm << ">";
2870     break;
2871   case k_ShiftedRegister:
2872     OS << "<so_reg_reg "
2873        << RegShiftedReg.SrcReg << " "
2874        << ARM_AM::getShiftOpcStr(RegShiftedReg.ShiftTy)
2875        << " " << RegShiftedReg.ShiftReg << ">";
2876     break;
2877   case k_ShiftedImmediate:
2878     OS << "<so_reg_imm "
2879        << RegShiftedImm.SrcReg << " "
2880        << ARM_AM::getShiftOpcStr(RegShiftedImm.ShiftTy)
2881        << " #" << RegShiftedImm.ShiftImm << ">";
2882     break;
2883   case k_RotateImmediate:
2884     OS << "<ror " << " #" << (RotImm.Imm * 8) << ">";
2885     break;
2886   case k_BitfieldDescriptor:
2887     OS << "<bitfield " << "lsb: " << Bitfield.LSB
2888        << ", width: " << Bitfield.Width << ">";
2889     break;
2890   case k_RegisterList:
2891   case k_DPRRegisterList:
2892   case k_SPRRegisterList: {
2893     OS << "<register_list ";
2894
2895     const SmallVectorImpl<unsigned> &RegList = getRegList();
2896     for (SmallVectorImpl<unsigned>::const_iterator
2897            I = RegList.begin(), E = RegList.end(); I != E; ) {
2898       OS << *I;
2899       if (++I < E) OS << ", ";
2900     }
2901
2902     OS << ">";
2903     break;
2904   }
2905   case k_VectorList:
2906     OS << "<vector_list " << VectorList.Count << " * "
2907        << VectorList.RegNum << ">";
2908     break;
2909   case k_VectorListAllLanes:
2910     OS << "<vector_list(all lanes) " << VectorList.Count << " * "
2911        << VectorList.RegNum << ">";
2912     break;
2913   case k_VectorListIndexed:
2914     OS << "<vector_list(lane " << VectorList.LaneIndex << ") "
2915        << VectorList.Count << " * " << VectorList.RegNum << ">";
2916     break;
2917   case k_Token:
2918     OS << "'" << getToken() << "'";
2919     break;
2920   case k_VectorIndex:
2921     OS << "<vectorindex " << getVectorIndex() << ">";
2922     break;
2923   }
2924 }
2925
2926 /// @name Auto-generated Match Functions
2927 /// {
2928
2929 static unsigned MatchRegisterName(StringRef Name);
2930
2931 /// }
2932
2933 bool ARMAsmParser::ParseRegister(unsigned &RegNo,
2934                                  SMLoc &StartLoc, SMLoc &EndLoc) {
2935   const AsmToken &Tok = getParser().getTok();
2936   StartLoc = Tok.getLoc();
2937   EndLoc = Tok.getEndLoc();
2938   RegNo = tryParseRegister();
2939
2940   return (RegNo == (unsigned)-1);
2941 }
2942
2943 /// Try to parse a register name.  The token must be an Identifier when called,
2944 /// and if it is a register name the token is eaten and the register number is
2945 /// returned.  Otherwise return -1.
2946 ///
2947 int ARMAsmParser::tryParseRegister() {
2948   MCAsmParser &Parser = getParser();
2949   const AsmToken &Tok = Parser.getTok();
2950   if (Tok.isNot(AsmToken::Identifier)) return -1;
2951
2952   std::string lowerCase = Tok.getString().lower();
2953   unsigned RegNum = MatchRegisterName(lowerCase);
2954   if (!RegNum) {
2955     RegNum = StringSwitch<unsigned>(lowerCase)
2956       .Case("r13", ARM::SP)
2957       .Case("r14", ARM::LR)
2958       .Case("r15", ARM::PC)
2959       .Case("ip", ARM::R12)
2960       // Additional register name aliases for 'gas' compatibility.
2961       .Case("a1", ARM::R0)
2962       .Case("a2", ARM::R1)
2963       .Case("a3", ARM::R2)
2964       .Case("a4", ARM::R3)
2965       .Case("v1", ARM::R4)
2966       .Case("v2", ARM::R5)
2967       .Case("v3", ARM::R6)
2968       .Case("v4", ARM::R7)
2969       .Case("v5", ARM::R8)
2970       .Case("v6", ARM::R9)
2971       .Case("v7", ARM::R10)
2972       .Case("v8", ARM::R11)
2973       .Case("sb", ARM::R9)
2974       .Case("sl", ARM::R10)
2975       .Case("fp", ARM::R11)
2976       .Default(0);
2977   }
2978   if (!RegNum) {
2979     // Check for aliases registered via .req. Canonicalize to lower case.
2980     // That's more consistent since register names are case insensitive, and
2981     // it's how the original entry was passed in from MC/MCParser/AsmParser.
2982     StringMap<unsigned>::const_iterator Entry = RegisterReqs.find(lowerCase);
2983     // If no match, return failure.
2984     if (Entry == RegisterReqs.end())
2985       return -1;
2986     Parser.Lex(); // Eat identifier token.
2987     return Entry->getValue();
2988   }
2989
2990   // Some FPUs only have 16 D registers, so D16-D31 are invalid
2991   if (hasD16() && RegNum >= ARM::D16 && RegNum <= ARM::D31)
2992     return -1;
2993
2994   Parser.Lex(); // Eat identifier token.
2995
2996   return RegNum;
2997 }
2998
2999 // Try to parse a shifter  (e.g., "lsl <amt>"). On success, return 0.
3000 // If a recoverable error occurs, return 1. If an irrecoverable error
3001 // occurs, return -1. An irrecoverable error is one where tokens have been
3002 // consumed in the process of trying to parse the shifter (i.e., when it is
3003 // indeed a shifter operand, but malformed).
3004 int ARMAsmParser::tryParseShiftRegister(OperandVector &Operands) {
3005   MCAsmParser &Parser = getParser();
3006   SMLoc S = Parser.getTok().getLoc();
3007   const AsmToken &Tok = Parser.getTok();
3008   if (Tok.isNot(AsmToken::Identifier))
3009     return -1; 
3010
3011   std::string lowerCase = Tok.getString().lower();
3012   ARM_AM::ShiftOpc ShiftTy = StringSwitch<ARM_AM::ShiftOpc>(lowerCase)
3013       .Case("asl", ARM_AM::lsl)
3014       .Case("lsl", ARM_AM::lsl)
3015       .Case("lsr", ARM_AM::lsr)
3016       .Case("asr", ARM_AM::asr)
3017       .Case("ror", ARM_AM::ror)
3018       .Case("rrx", ARM_AM::rrx)
3019       .Default(ARM_AM::no_shift);
3020
3021   if (ShiftTy == ARM_AM::no_shift)
3022     return 1;
3023
3024   Parser.Lex(); // Eat the operator.
3025
3026   // The source register for the shift has already been added to the
3027   // operand list, so we need to pop it off and combine it into the shifted
3028   // register operand instead.
3029   std::unique_ptr<ARMOperand> PrevOp(
3030       (ARMOperand *)Operands.pop_back_val().release());
3031   if (!PrevOp->isReg())
3032     return Error(PrevOp->getStartLoc(), "shift must be of a register");
3033   int SrcReg = PrevOp->getReg();
3034
3035   SMLoc EndLoc;
3036   int64_t Imm = 0;
3037   int ShiftReg = 0;
3038   if (ShiftTy == ARM_AM::rrx) {
3039     // RRX Doesn't have an explicit shift amount. The encoder expects
3040     // the shift register to be the same as the source register. Seems odd,
3041     // but OK.
3042     ShiftReg = SrcReg;
3043   } else {
3044     // Figure out if this is shifted by a constant or a register (for non-RRX).
3045     if (Parser.getTok().is(AsmToken::Hash) ||
3046         Parser.getTok().is(AsmToken::Dollar)) {
3047       Parser.Lex(); // Eat hash.
3048       SMLoc ImmLoc = Parser.getTok().getLoc();
3049       const MCExpr *ShiftExpr = nullptr;
3050       if (getParser().parseExpression(ShiftExpr, EndLoc)) {
3051         Error(ImmLoc, "invalid immediate shift value");
3052         return -1;
3053       }
3054       // The expression must be evaluatable as an immediate.
3055       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftExpr);
3056       if (!CE) {
3057         Error(ImmLoc, "invalid immediate shift value");
3058         return -1;
3059       }
3060       // Range check the immediate.
3061       // lsl, ror: 0 <= imm <= 31
3062       // lsr, asr: 0 <= imm <= 32
3063       Imm = CE->getValue();
3064       if (Imm < 0 ||
3065           ((ShiftTy == ARM_AM::lsl || ShiftTy == ARM_AM::ror) && Imm > 31) ||
3066           ((ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr) && Imm > 32)) {
3067         Error(ImmLoc, "immediate shift value out of range");
3068         return -1;
3069       }
3070       // shift by zero is a nop. Always send it through as lsl.
3071       // ('as' compatibility)
3072       if (Imm == 0)
3073         ShiftTy = ARM_AM::lsl;
3074     } else if (Parser.getTok().is(AsmToken::Identifier)) {
3075       SMLoc L = Parser.getTok().getLoc();
3076       EndLoc = Parser.getTok().getEndLoc();
3077       ShiftReg = tryParseRegister();
3078       if (ShiftReg == -1) {
3079         Error(L, "expected immediate or register in shift operand");
3080         return -1;
3081       }
3082     } else {
3083       Error(Parser.getTok().getLoc(),
3084             "expected immediate or register in shift operand");
3085       return -1;
3086     }
3087   }
3088
3089   if (ShiftReg && ShiftTy != ARM_AM::rrx)
3090     Operands.push_back(ARMOperand::CreateShiftedRegister(ShiftTy, SrcReg,
3091                                                          ShiftReg, Imm,
3092                                                          S, EndLoc));
3093   else
3094     Operands.push_back(ARMOperand::CreateShiftedImmediate(ShiftTy, SrcReg, Imm,
3095                                                           S, EndLoc));
3096
3097   return 0;
3098 }
3099
3100
3101 /// Try to parse a register name.  The token must be an Identifier when called.
3102 /// If it's a register, an AsmOperand is created. Another AsmOperand is created
3103 /// if there is a "writeback". 'true' if it's not a register.
3104 ///
3105 /// TODO this is likely to change to allow different register types and or to
3106 /// parse for a specific register type.
3107 bool ARMAsmParser::tryParseRegisterWithWriteBack(OperandVector &Operands) {
3108   MCAsmParser &Parser = getParser();
3109   const AsmToken &RegTok = Parser.getTok();
3110   int RegNo = tryParseRegister();
3111   if (RegNo == -1)
3112     return true;
3113
3114   Operands.push_back(ARMOperand::CreateReg(RegNo, RegTok.getLoc(),
3115                                            RegTok.getEndLoc()));
3116
3117   const AsmToken &ExclaimTok = Parser.getTok();
3118   if (ExclaimTok.is(AsmToken::Exclaim)) {
3119     Operands.push_back(ARMOperand::CreateToken(ExclaimTok.getString(),
3120                                                ExclaimTok.getLoc()));
3121     Parser.Lex(); // Eat exclaim token
3122     return false;
3123   }
3124
3125   // Also check for an index operand. This is only legal for vector registers,
3126   // but that'll get caught OK in operand matching, so we don't need to
3127   // explicitly filter everything else out here.
3128   if (Parser.getTok().is(AsmToken::LBrac)) {
3129     SMLoc SIdx = Parser.getTok().getLoc();
3130     Parser.Lex(); // Eat left bracket token.
3131
3132     const MCExpr *ImmVal;
3133     if (getParser().parseExpression(ImmVal))
3134       return true;
3135     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(ImmVal);
3136     if (!MCE)
3137       return TokError("immediate value expected for vector index");
3138
3139     if (Parser.getTok().isNot(AsmToken::RBrac))
3140       return Error(Parser.getTok().getLoc(), "']' expected");
3141
3142     SMLoc E = Parser.getTok().getEndLoc();
3143     Parser.Lex(); // Eat right bracket token.
3144
3145     Operands.push_back(ARMOperand::CreateVectorIndex(MCE->getValue(),
3146                                                      SIdx, E,
3147                                                      getContext()));
3148   }
3149
3150   return false;
3151 }
3152
3153 /// MatchCoprocessorOperandName - Try to parse an coprocessor related
3154 /// instruction with a symbolic operand name.
3155 /// We accept "crN" syntax for GAS compatibility.
3156 /// <operand-name> ::= <prefix><number>
3157 /// If CoprocOp is 'c', then:
3158 ///   <prefix> ::= c | cr
3159 /// If CoprocOp is 'p', then :
3160 ///   <prefix> ::= p
3161 /// <number> ::= integer in range [0, 15]
3162 static int MatchCoprocessorOperandName(StringRef Name, char CoprocOp) {
3163   // Use the same layout as the tablegen'erated register name matcher. Ugly,
3164   // but efficient.
3165   if (Name.size() < 2 || Name[0] != CoprocOp)
3166     return -1;
3167   Name = (Name[1] == 'r') ? Name.drop_front(2) : Name.drop_front();
3168
3169   switch (Name.size()) {
3170   default: return -1;
3171   case 1:
3172     switch (Name[0]) {
3173     default:  return -1;
3174     case '0': return 0;
3175     case '1': return 1;
3176     case '2': return 2;
3177     case '3': return 3;
3178     case '4': return 4;
3179     case '5': return 5;
3180     case '6': return 6;
3181     case '7': return 7;
3182     case '8': return 8;
3183     case '9': return 9;
3184     }
3185   case 2:
3186     if (Name[0] != '1')
3187       return -1;
3188     switch (Name[1]) {
3189     default:  return -1;
3190     // CP10 and CP11 are VFP/NEON and so vector instructions should be used.
3191     // However, old cores (v5/v6) did use them in that way.
3192     case '0': return 10;
3193     case '1': return 11;
3194     case '2': return 12;
3195     case '3': return 13;
3196     case '4': return 14;
3197     case '5': return 15;
3198     }
3199   }
3200 }
3201
3202 /// parseITCondCode - Try to parse a condition code for an IT instruction.
3203 ARMAsmParser::OperandMatchResultTy
3204 ARMAsmParser::parseITCondCode(OperandVector &Operands) {
3205   MCAsmParser &Parser = getParser();
3206   SMLoc S = Parser.getTok().getLoc();
3207   const AsmToken &Tok = Parser.getTok();
3208   if (!Tok.is(AsmToken::Identifier))
3209     return MatchOperand_NoMatch;
3210   unsigned CC = StringSwitch<unsigned>(Tok.getString().lower())
3211     .Case("eq", ARMCC::EQ)
3212     .Case("ne", ARMCC::NE)
3213     .Case("hs", ARMCC::HS)
3214     .Case("cs", ARMCC::HS)
3215     .Case("lo", ARMCC::LO)
3216     .Case("cc", ARMCC::LO)
3217     .Case("mi", ARMCC::MI)
3218     .Case("pl", ARMCC::PL)
3219     .Case("vs", ARMCC::VS)
3220     .Case("vc", ARMCC::VC)
3221     .Case("hi", ARMCC::HI)
3222     .Case("ls", ARMCC::LS)
3223     .Case("ge", ARMCC::GE)
3224     .Case("lt", ARMCC::LT)
3225     .Case("gt", ARMCC::GT)
3226     .Case("le", ARMCC::LE)
3227     .Case("al", ARMCC::AL)
3228     .Default(~0U);
3229   if (CC == ~0U)
3230     return MatchOperand_NoMatch;
3231   Parser.Lex(); // Eat the token.
3232
3233   Operands.push_back(ARMOperand::CreateCondCode(ARMCC::CondCodes(CC), S));
3234
3235   return MatchOperand_Success;
3236 }
3237
3238 /// parseCoprocNumOperand - Try to parse an coprocessor number operand. The
3239 /// token must be an Identifier when called, and if it is a coprocessor
3240 /// number, the token is eaten and the operand is added to the operand list.
3241 ARMAsmParser::OperandMatchResultTy
3242 ARMAsmParser::parseCoprocNumOperand(OperandVector &Operands) {
3243   MCAsmParser &Parser = getParser();
3244   SMLoc S = Parser.getTok().getLoc();
3245   const AsmToken &Tok = Parser.getTok();
3246   if (Tok.isNot(AsmToken::Identifier))
3247     return MatchOperand_NoMatch;
3248
3249   int Num = MatchCoprocessorOperandName(Tok.getString(), 'p');
3250   if (Num == -1)
3251     return MatchOperand_NoMatch;
3252   // ARMv7 and v8 don't allow cp10/cp11 due to VFP/NEON specific instructions
3253   if ((hasV7Ops() || hasV8Ops()) && (Num == 10 || Num == 11))
3254     return MatchOperand_NoMatch;
3255
3256   Parser.Lex(); // Eat identifier token.
3257   Operands.push_back(ARMOperand::CreateCoprocNum(Num, S));
3258   return MatchOperand_Success;
3259 }
3260
3261 /// parseCoprocRegOperand - Try to parse an coprocessor register operand. The
3262 /// token must be an Identifier when called, and if it is a coprocessor
3263 /// number, the token is eaten and the operand is added to the operand list.
3264 ARMAsmParser::OperandMatchResultTy
3265 ARMAsmParser::parseCoprocRegOperand(OperandVector &Operands) {
3266   MCAsmParser &Parser = getParser();
3267   SMLoc S = Parser.getTok().getLoc();
3268   const AsmToken &Tok = Parser.getTok();
3269   if (Tok.isNot(AsmToken::Identifier))
3270     return MatchOperand_NoMatch;
3271
3272   int Reg = MatchCoprocessorOperandName(Tok.getString(), 'c');
3273   if (Reg == -1)
3274     return MatchOperand_NoMatch;
3275
3276   Parser.Lex(); // Eat identifier token.
3277   Operands.push_back(ARMOperand::CreateCoprocReg(Reg, S));
3278   return MatchOperand_Success;
3279 }
3280
3281 /// parseCoprocOptionOperand - Try to parse an coprocessor option operand.
3282 /// coproc_option : '{' imm0_255 '}'
3283 ARMAsmParser::OperandMatchResultTy
3284 ARMAsmParser::parseCoprocOptionOperand(OperandVector &Operands) {
3285   MCAsmParser &Parser = getParser();
3286   SMLoc S = Parser.getTok().getLoc();
3287
3288   // If this isn't a '{', this isn't a coprocessor immediate operand.
3289   if (Parser.getTok().isNot(AsmToken::LCurly))
3290     return MatchOperand_NoMatch;
3291   Parser.Lex(); // Eat the '{'
3292
3293   const MCExpr *Expr;
3294   SMLoc Loc = Parser.getTok().getLoc();
3295   if (getParser().parseExpression(Expr)) {
3296     Error(Loc, "illegal expression");
3297     return MatchOperand_ParseFail;
3298   }
3299   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
3300   if (!CE || CE->getValue() < 0 || CE->getValue() > 255) {
3301     Error(Loc, "coprocessor option must be an immediate in range [0, 255]");
3302     return MatchOperand_ParseFail;
3303   }
3304   int Val = CE->getValue();
3305
3306   // Check for and consume the closing '}'
3307   if (Parser.getTok().isNot(AsmToken::RCurly))
3308     return MatchOperand_ParseFail;
3309   SMLoc E = Parser.getTok().getEndLoc();
3310   Parser.Lex(); // Eat the '}'
3311
3312   Operands.push_back(ARMOperand::CreateCoprocOption(Val, S, E));
3313   return MatchOperand_Success;
3314 }
3315
3316 // For register list parsing, we need to map from raw GPR register numbering
3317 // to the enumeration values. The enumeration values aren't sorted by
3318 // register number due to our using "sp", "lr" and "pc" as canonical names.
3319 static unsigned getNextRegister(unsigned Reg) {
3320   // If this is a GPR, we need to do it manually, otherwise we can rely
3321   // on the sort ordering of the enumeration since the other reg-classes
3322   // are sane.
3323   if (!ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
3324     return Reg + 1;
3325   switch(Reg) {
3326   default: llvm_unreachable("Invalid GPR number!");
3327   case ARM::R0:  return ARM::R1;  case ARM::R1:  return ARM::R2;
3328   case ARM::R2:  return ARM::R3;  case ARM::R3:  return ARM::R4;
3329   case ARM::R4:  return ARM::R5;  case ARM::R5:  return ARM::R6;
3330   case ARM::R6:  return ARM::R7;  case ARM::R7:  return ARM::R8;
3331   case ARM::R8:  return ARM::R9;  case ARM::R9:  return ARM::R10;
3332   case ARM::R10: return ARM::R11; case ARM::R11: return ARM::R12;
3333   case ARM::R12: return ARM::SP;  case ARM::SP:  return ARM::LR;
3334   case ARM::LR:  return ARM::PC;  case ARM::PC:  return ARM::R0;
3335   }
3336 }
3337
3338 // Return the low-subreg of a given Q register.
3339 static unsigned getDRegFromQReg(unsigned QReg) {
3340   switch (QReg) {
3341   default: llvm_unreachable("expected a Q register!");
3342   case ARM::Q0:  return ARM::D0;
3343   case ARM::Q1:  return ARM::D2;
3344   case ARM::Q2:  return ARM::D4;
3345   case ARM::Q3:  return ARM::D6;
3346   case ARM::Q4:  return ARM::D8;
3347   case ARM::Q5:  return ARM::D10;
3348   case ARM::Q6:  return ARM::D12;
3349   case ARM::Q7:  return ARM::D14;
3350   case ARM::Q8:  return ARM::D16;
3351   case ARM::Q9:  return ARM::D18;
3352   case ARM::Q10: return ARM::D20;
3353   case ARM::Q11: return ARM::D22;
3354   case ARM::Q12: return ARM::D24;
3355   case ARM::Q13: return ARM::D26;
3356   case ARM::Q14: return ARM::D28;
3357   case ARM::Q15: return ARM::D30;
3358   }
3359 }
3360
3361 /// Parse a register list.
3362 bool ARMAsmParser::parseRegisterList(OperandVector &Operands) {
3363   MCAsmParser &Parser = getParser();
3364   assert(Parser.getTok().is(AsmToken::LCurly) &&
3365          "Token is not a Left Curly Brace");
3366   SMLoc S = Parser.getTok().getLoc();
3367   Parser.Lex(); // Eat '{' token.
3368   SMLoc RegLoc = Parser.getTok().getLoc();
3369
3370   // Check the first register in the list to see what register class
3371   // this is a list of.
3372   int Reg = tryParseRegister();
3373   if (Reg == -1)
3374     return Error(RegLoc, "register expected");
3375
3376   // The reglist instructions have at most 16 registers, so reserve
3377   // space for that many.
3378   int EReg = 0;
3379   SmallVector<std::pair<unsigned, unsigned>, 16> Registers;
3380
3381   // Allow Q regs and just interpret them as the two D sub-registers.
3382   if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3383     Reg = getDRegFromQReg(Reg);
3384     EReg = MRI->getEncodingValue(Reg);
3385     Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3386     ++Reg;
3387   }
3388   const MCRegisterClass *RC;
3389   if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
3390     RC = &ARMMCRegisterClasses[ARM::GPRRegClassID];
3391   else if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg))
3392     RC = &ARMMCRegisterClasses[ARM::DPRRegClassID];
3393   else if (ARMMCRegisterClasses[ARM::SPRRegClassID].contains(Reg))
3394     RC = &ARMMCRegisterClasses[ARM::SPRRegClassID];
3395   else
3396     return Error(RegLoc, "invalid register in register list");
3397
3398   // Store the register.
3399   EReg = MRI->getEncodingValue(Reg);
3400   Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3401
3402   // This starts immediately after the first register token in the list,
3403   // so we can see either a comma or a minus (range separator) as a legal
3404   // next token.
3405   while (Parser.getTok().is(AsmToken::Comma) ||
3406          Parser.getTok().is(AsmToken::Minus)) {
3407     if (Parser.getTok().is(AsmToken::Minus)) {
3408       Parser.Lex(); // Eat the minus.
3409       SMLoc AfterMinusLoc = Parser.getTok().getLoc();
3410       int EndReg = tryParseRegister();
3411       if (EndReg == -1)
3412         return Error(AfterMinusLoc, "register expected");
3413       // Allow Q regs and just interpret them as the two D sub-registers.
3414       if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(EndReg))
3415         EndReg = getDRegFromQReg(EndReg) + 1;
3416       // If the register is the same as the start reg, there's nothing
3417       // more to do.
3418       if (Reg == EndReg)
3419         continue;
3420       // The register must be in the same register class as the first.
3421       if (!RC->contains(EndReg))
3422         return Error(AfterMinusLoc, "invalid register in register list");
3423       // Ranges must go from low to high.
3424       if (MRI->getEncodingValue(Reg) > MRI->getEncodingValue(EndReg))
3425         return Error(AfterMinusLoc, "bad range in register list");
3426
3427       // Add all the registers in the range to the register list.
3428       while (Reg != EndReg) {
3429         Reg = getNextRegister(Reg);
3430         EReg = MRI->getEncodingValue(Reg);
3431         Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3432       }
3433       continue;
3434     }
3435     Parser.Lex(); // Eat the comma.
3436     RegLoc = Parser.getTok().getLoc();
3437     int OldReg = Reg;
3438     const AsmToken RegTok = Parser.getTok();
3439     Reg = tryParseRegister();
3440     if (Reg == -1)
3441       return Error(RegLoc, "register expected");
3442     // Allow Q regs and just interpret them as the two D sub-registers.
3443     bool isQReg = false;
3444     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3445       Reg = getDRegFromQReg(Reg);
3446       isQReg = true;
3447     }
3448     // The register must be in the same register class as the first.
3449     if (!RC->contains(Reg))
3450       return Error(RegLoc, "invalid register in register list");
3451     // List must be monotonically increasing.
3452     if (MRI->getEncodingValue(Reg) < MRI->getEncodingValue(OldReg)) {
3453       if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
3454         Warning(RegLoc, "register list not in ascending order");
3455       else
3456         return Error(RegLoc, "register list not in ascending order");
3457     }
3458     if (MRI->getEncodingValue(Reg) == MRI->getEncodingValue(OldReg)) {
3459       Warning(RegLoc, "duplicated register (" + RegTok.getString() +
3460               ") in register list");
3461       continue;
3462     }
3463     // VFP register lists must also be contiguous.
3464     if (RC != &ARMMCRegisterClasses[ARM::GPRRegClassID] &&
3465         Reg != OldReg + 1)
3466       return Error(RegLoc, "non-contiguous register range");
3467     EReg = MRI->getEncodingValue(Reg);
3468     Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3469     if (isQReg) {
3470       EReg = MRI->getEncodingValue(++Reg);
3471       Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3472     }
3473   }
3474
3475   if (Parser.getTok().isNot(AsmToken::RCurly))
3476     return Error(Parser.getTok().getLoc(), "'}' expected");
3477   SMLoc E = Parser.getTok().getEndLoc();
3478   Parser.Lex(); // Eat '}' token.
3479
3480   // Push the register list operand.
3481   Operands.push_back(ARMOperand::CreateRegList(Registers, S, E));
3482
3483   // The ARM system instruction variants for LDM/STM have a '^' token here.
3484   if (Parser.getTok().is(AsmToken::Caret)) {
3485     Operands.push_back(ARMOperand::CreateToken("^",Parser.getTok().getLoc()));
3486     Parser.Lex(); // Eat '^' token.
3487   }
3488
3489   return false;
3490 }
3491
3492 // Helper function to parse the lane index for vector lists.
3493 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
3494 parseVectorLane(VectorLaneTy &LaneKind, unsigned &Index, SMLoc &EndLoc) {
3495   MCAsmParser &Parser = getParser();
3496   Index = 0; // Always return a defined index value.
3497   if (Parser.getTok().is(AsmToken::LBrac)) {
3498     Parser.Lex(); // Eat the '['.
3499     if (Parser.getTok().is(AsmToken::RBrac)) {
3500       // "Dn[]" is the 'all lanes' syntax.
3501       LaneKind = AllLanes;
3502       EndLoc = Parser.getTok().getEndLoc();
3503       Parser.Lex(); // Eat the ']'.
3504       return MatchOperand_Success;
3505     }
3506
3507     // There's an optional '#' token here. Normally there wouldn't be, but
3508     // inline assemble puts one in, and it's friendly to accept that.
3509     if (Parser.getTok().is(AsmToken::Hash))
3510       Parser.Lex(); // Eat '#' or '$'.
3511
3512     const MCExpr *LaneIndex;
3513     SMLoc Loc = Parser.getTok().getLoc();
3514     if (getParser().parseExpression(LaneIndex)) {
3515       Error(Loc, "illegal expression");
3516       return MatchOperand_ParseFail;
3517     }
3518     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LaneIndex);
3519     if (!CE) {
3520       Error(Loc, "lane index must be empty or an integer");
3521       return MatchOperand_ParseFail;
3522     }
3523     if (Parser.getTok().isNot(AsmToken::RBrac)) {
3524       Error(Parser.getTok().getLoc(), "']' expected");
3525       return MatchOperand_ParseFail;
3526     }
3527     EndLoc = Parser.getTok().getEndLoc();
3528     Parser.Lex(); // Eat the ']'.
3529     int64_t Val = CE->getValue();
3530
3531     // FIXME: Make this range check context sensitive for .8, .16, .32.
3532     if (Val < 0 || Val > 7) {
3533       Error(Parser.getTok().getLoc(), "lane index out of range");
3534       return MatchOperand_ParseFail;
3535     }
3536     Index = Val;
3537     LaneKind = IndexedLane;
3538     return MatchOperand_Success;
3539   }
3540   LaneKind = NoLanes;
3541   return MatchOperand_Success;
3542 }
3543
3544 // parse a vector register list
3545 ARMAsmParser::OperandMatchResultTy
3546 ARMAsmParser::parseVectorList(OperandVector &Operands) {
3547   MCAsmParser &Parser = getParser();
3548   VectorLaneTy LaneKind;
3549   unsigned LaneIndex;
3550   SMLoc S = Parser.getTok().getLoc();
3551   // As an extension (to match gas), support a plain D register or Q register
3552   // (without encosing curly braces) as a single or double entry list,
3553   // respectively.
3554   if (Parser.getTok().is(AsmToken::Identifier)) {
3555     SMLoc E = Parser.getTok().getEndLoc();
3556     int Reg = tryParseRegister();
3557     if (Reg == -1)
3558       return MatchOperand_NoMatch;
3559     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg)) {
3560       OperandMatchResultTy Res = parseVectorLane(LaneKind, LaneIndex, E);
3561       if (Res != MatchOperand_Success)
3562         return Res;
3563       switch (LaneKind) {
3564       case NoLanes:
3565         Operands.push_back(ARMOperand::CreateVectorList(Reg, 1, false, S, E));
3566         break;
3567       case AllLanes:
3568         Operands.push_back(ARMOperand::CreateVectorListAllLanes(Reg, 1, false,
3569                                                                 S, E));
3570         break;
3571       case IndexedLane:
3572         Operands.push_back(ARMOperand::CreateVectorListIndexed(Reg, 1,
3573                                                                LaneIndex,
3574                                                                false, S, E));
3575         break;
3576       }
3577       return MatchOperand_Success;
3578     }
3579     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3580       Reg = getDRegFromQReg(Reg);
3581       OperandMatchResultTy Res = parseVectorLane(LaneKind, LaneIndex, E);
3582       if (Res != MatchOperand_Success)
3583         return Res;
3584       switch (LaneKind) {
3585       case NoLanes:
3586         Reg = MRI->getMatchingSuperReg(Reg, ARM::dsub_0,
3587                                    &ARMMCRegisterClasses[ARM::DPairRegClassID]);
3588         Operands.push_back(ARMOperand::CreateVectorList(Reg, 2, false, S, E));
3589         break;
3590       case AllLanes:
3591         Reg = MRI->getMatchingSuperReg(Reg, ARM::dsub_0,
3592                                    &ARMMCRegisterClasses[ARM::DPairRegClassID]);
3593         Operands.push_back(ARMOperand::CreateVectorListAllLanes(Reg, 2, false,
3594                                                                 S, E));
3595         break;
3596       case IndexedLane:
3597         Operands.push_back(ARMOperand::CreateVectorListIndexed(Reg, 2,
3598                                                                LaneIndex,
3599                                                                false, S, E));
3600         break;
3601       }
3602       return MatchOperand_Success;
3603     }
3604     Error(S, "vector register expected");
3605     return MatchOperand_ParseFail;
3606   }
3607
3608   if (Parser.getTok().isNot(AsmToken::LCurly))
3609     return MatchOperand_NoMatch;
3610
3611   Parser.Lex(); // Eat '{' token.
3612   SMLoc RegLoc = Parser.getTok().getLoc();
3613
3614   int Reg = tryParseRegister();
3615   if (Reg == -1) {
3616     Error(RegLoc, "register expected");
3617     return MatchOperand_ParseFail;
3618   }
3619   unsigned Count = 1;
3620   int Spacing = 0;
3621   unsigned FirstReg = Reg;
3622   // The list is of D registers, but we also allow Q regs and just interpret
3623   // them as the two D sub-registers.
3624   if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3625     FirstReg = Reg = getDRegFromQReg(Reg);
3626     Spacing = 1; // double-spacing requires explicit D registers, otherwise
3627                  // it's ambiguous with four-register single spaced.
3628     ++Reg;
3629     ++Count;
3630   }
3631
3632   SMLoc E;
3633   if (parseVectorLane(LaneKind, LaneIndex, E) != MatchOperand_Success)
3634     return MatchOperand_ParseFail;
3635
3636   while (Parser.getTok().is(AsmToken::Comma) ||
3637          Parser.getTok().is(AsmToken::Minus)) {
3638     if (Parser.getTok().is(AsmToken::Minus)) {
3639       if (!Spacing)
3640         Spacing = 1; // Register range implies a single spaced list.
3641       else if (Spacing == 2) {
3642         Error(Parser.getTok().getLoc(),
3643               "sequential registers in double spaced list");
3644         return MatchOperand_ParseFail;
3645       }
3646       Parser.Lex(); // Eat the minus.
3647       SMLoc AfterMinusLoc = Parser.getTok().getLoc();
3648       int EndReg = tryParseRegister();
3649       if (EndReg == -1) {
3650         Error(AfterMinusLoc, "register expected");
3651         return MatchOperand_ParseFail;
3652       }
3653       // Allow Q regs and just interpret them as the two D sub-registers.
3654       if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(EndReg))
3655         EndReg = getDRegFromQReg(EndReg) + 1;
3656       // If the register is the same as the start reg, there's nothing
3657       // more to do.
3658       if (Reg == EndReg)
3659         continue;
3660       // The register must be in the same register class as the first.
3661       if (!ARMMCRegisterClasses[ARM::DPRRegClassID].contains(EndReg)) {
3662         Error(AfterMinusLoc, "invalid register in register list");
3663         return MatchOperand_ParseFail;
3664       }
3665       // Ranges must go from low to high.
3666       if (Reg > EndReg) {
3667         Error(AfterMinusLoc, "bad range in register list");
3668         return MatchOperand_ParseFail;
3669       }
3670       // Parse the lane specifier if present.
3671       VectorLaneTy NextLaneKind;
3672       unsigned NextLaneIndex;
3673       if (parseVectorLane(NextLaneKind, NextLaneIndex, E) !=
3674           MatchOperand_Success)
3675         return MatchOperand_ParseFail;
3676       if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
3677         Error(AfterMinusLoc, "mismatched lane index in register list");
3678         return MatchOperand_ParseFail;
3679       }
3680
3681       // Add all the registers in the range to the register list.
3682       Count += EndReg - Reg;
3683       Reg = EndReg;
3684       continue;
3685     }
3686     Parser.Lex(); // Eat the comma.
3687     RegLoc = Parser.getTok().getLoc();
3688     int OldReg = Reg;
3689     Reg = tryParseRegister();
3690     if (Reg == -1) {
3691       Error(RegLoc, "register expected");
3692       return MatchOperand_ParseFail;
3693     }
3694     // vector register lists must be contiguous.
3695     // It's OK to use the enumeration values directly here rather, as the
3696     // VFP register classes have the enum sorted properly.
3697     //
3698     // The list is of D registers, but we also allow Q regs and just interpret
3699     // them as the two D sub-registers.
3700     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3701       if (!Spacing)
3702         Spacing = 1; // Register range implies a single spaced list.
3703       else if (Spacing == 2) {
3704         Error(RegLoc,
3705               "invalid register in double-spaced list (must be 'D' register')");
3706         return MatchOperand_ParseFail;
3707       }
3708       Reg = getDRegFromQReg(Reg);
3709       if (Reg != OldReg + 1) {
3710         Error(RegLoc, "non-contiguous register range");
3711         return MatchOperand_ParseFail;
3712       }
3713       ++Reg;
3714       Count += 2;
3715       // Parse the lane specifier if present.
3716       VectorLaneTy NextLaneKind;
3717       unsigned NextLaneIndex;
3718       SMLoc LaneLoc = Parser.getTok().getLoc();
3719       if (parseVectorLane(NextLaneKind, NextLaneIndex, E) !=
3720           MatchOperand_Success)
3721         return MatchOperand_ParseFail;
3722       if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
3723         Error(LaneLoc, "mismatched lane index in register list");
3724         return MatchOperand_ParseFail;
3725       }
3726       continue;
3727     }
3728     // Normal D register.
3729     // Figure out the register spacing (single or double) of the list if
3730     // we don't know it already.
3731     if (!Spacing)
3732       Spacing = 1 + (Reg == OldReg + 2);
3733
3734     // Just check that it's contiguous and keep going.
3735     if (Reg != OldReg + Spacing) {
3736       Error(RegLoc, "non-contiguous register range");
3737       return MatchOperand_ParseFail;
3738     }
3739     ++Count;
3740     // Parse the lane specifier if present.
3741     VectorLaneTy NextLaneKind;
3742     unsigned NextLaneIndex;
3743     SMLoc EndLoc = Parser.getTok().getLoc();
3744     if (parseVectorLane(NextLaneKind, NextLaneIndex, E) != MatchOperand_Success)
3745       return MatchOperand_ParseFail;
3746     if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
3747       Error(EndLoc, "mismatched lane index in register list");
3748       return MatchOperand_ParseFail;
3749     }
3750   }
3751
3752   if (Parser.getTok().isNot(AsmToken::RCurly)) {
3753     Error(Parser.getTok().getLoc(), "'}' expected");
3754     return MatchOperand_ParseFail;
3755   }
3756   E = Parser.getTok().getEndLoc();
3757   Parser.Lex(); // Eat '}' token.
3758
3759   switch (LaneKind) {
3760   case NoLanes:
3761     // Two-register operands have been converted to the
3762     // composite register classes.
3763     if (Count == 2) {
3764       const MCRegisterClass *RC = (Spacing == 1) ?
3765         &ARMMCRegisterClasses[ARM::DPairRegClassID] :
3766         &ARMMCRegisterClasses[ARM::DPairSpcRegClassID];
3767       FirstReg = MRI->getMatchingSuperReg(FirstReg, ARM::dsub_0, RC);
3768     }
3769
3770     Operands.push_back(ARMOperand::CreateVectorList(FirstReg, Count,
3771                                                     (Spacing == 2), S, E));
3772     break;
3773   case AllLanes:
3774     // Two-register operands have been converted to the
3775     // composite register classes.
3776     if (Count == 2) {
3777       const MCRegisterClass *RC = (Spacing == 1) ?
3778         &ARMMCRegisterClasses[ARM::DPairRegClassID] :
3779         &ARMMCRegisterClasses[ARM::DPairSpcRegClassID];
3780       FirstReg = MRI->getMatchingSuperReg(FirstReg, ARM::dsub_0, RC);
3781     }
3782     Operands.push_back(ARMOperand::CreateVectorListAllLanes(FirstReg, Count,
3783                                                             (Spacing == 2),
3784                                                             S, E));
3785     break;
3786   case IndexedLane:
3787     Operands.push_back(ARMOperand::CreateVectorListIndexed(FirstReg, Count,
3788                                                            LaneIndex,
3789                                                            (Spacing == 2),
3790                                                            S, E));
3791     break;
3792   }
3793   return MatchOperand_Success;
3794 }
3795
3796 /// parseMemBarrierOptOperand - Try to parse DSB/DMB data barrier options.
3797 ARMAsmParser::OperandMatchResultTy
3798 ARMAsmParser::parseMemBarrierOptOperand(OperandVector &Operands) {
3799   MCAsmParser &Parser = getParser();
3800   SMLoc S = Parser.getTok().getLoc();
3801   const AsmToken &Tok = Parser.getTok();
3802   unsigned Opt;
3803
3804   if (Tok.is(AsmToken::Identifier)) {
3805     StringRef OptStr = Tok.getString();
3806
3807     Opt = StringSwitch<unsigned>(OptStr.slice(0, OptStr.size()).lower())
3808       .Case("sy",    ARM_MB::SY)
3809       .Case("st",    ARM_MB::ST)
3810       .Case("ld",    ARM_MB::LD)
3811       .Case("sh",    ARM_MB::ISH)
3812       .Case("ish",   ARM_MB::ISH)
3813       .Case("shst",  ARM_MB::ISHST)
3814       .Case("ishst", ARM_MB::ISHST)
3815       .Case("ishld", ARM_MB::ISHLD)
3816       .Case("nsh",   ARM_MB::NSH)
3817       .Case("un",    ARM_MB::NSH)
3818       .Case("nshst", ARM_MB::NSHST)
3819       .Case("nshld", ARM_MB::NSHLD)
3820       .Case("unst",  ARM_MB::NSHST)
3821       .Case("osh",   ARM_MB::OSH)
3822       .Case("oshst", ARM_MB::OSHST)
3823       .Case("oshld", ARM_MB::OSHLD)
3824       .Default(~0U);
3825
3826     // ishld, oshld, nshld and ld are only available from ARMv8.
3827     if (!hasV8Ops() && (Opt == ARM_MB::ISHLD || Opt == ARM_MB::OSHLD ||
3828                         Opt == ARM_MB::NSHLD || Opt == ARM_MB::LD))
3829       Opt = ~0U;
3830
3831     if (Opt == ~0U)
3832       return MatchOperand_NoMatch;
3833
3834     Parser.Lex(); // Eat identifier token.
3835   } else if (Tok.is(AsmToken::Hash) ||
3836              Tok.is(AsmToken::Dollar) ||
3837              Tok.is(AsmToken::Integer)) {
3838     if (Parser.getTok().isNot(AsmToken::Integer))
3839       Parser.Lex(); // Eat '#' or '$'.
3840     SMLoc Loc = Parser.getTok().getLoc();
3841
3842     const MCExpr *MemBarrierID;
3843     if (getParser().parseExpression(MemBarrierID)) {
3844       Error(Loc, "illegal expression");
3845       return MatchOperand_ParseFail;
3846     }
3847
3848     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(MemBarrierID);
3849     if (!CE) {
3850       Error(Loc, "constant expression expected");
3851       return MatchOperand_ParseFail;
3852     }
3853
3854     int Val = CE->getValue();
3855     if (Val & ~0xf) {
3856       Error(Loc, "immediate value out of range");
3857       return MatchOperand_ParseFail;
3858     }
3859
3860     Opt = ARM_MB::RESERVED_0 + Val;
3861   } else
3862     return MatchOperand_ParseFail;
3863
3864   Operands.push_back(ARMOperand::CreateMemBarrierOpt((ARM_MB::MemBOpt)Opt, S));
3865   return MatchOperand_Success;
3866 }
3867
3868 /// parseInstSyncBarrierOptOperand - Try to parse ISB inst sync barrier options.
3869 ARMAsmParser::OperandMatchResultTy
3870 ARMAsmParser::parseInstSyncBarrierOptOperand(OperandVector &Operands) {
3871   MCAsmParser &Parser = getParser();
3872   SMLoc S = Parser.getTok().getLoc();
3873   const AsmToken &Tok = Parser.getTok();
3874   unsigned Opt;
3875
3876   if (Tok.is(AsmToken::Identifier)) {
3877     StringRef OptStr = Tok.getString();
3878
3879     if (OptStr.equals_lower("sy"))
3880       Opt = ARM_ISB::SY;
3881     else
3882       return MatchOperand_NoMatch;
3883
3884     Parser.Lex(); // Eat identifier token.
3885   } else if (Tok.is(AsmToken::Hash) ||
3886              Tok.is(AsmToken::Dollar) ||
3887              Tok.is(AsmToken::Integer)) {
3888     if (Parser.getTok().isNot(AsmToken::Integer))
3889       Parser.Lex(); // Eat '#' or '$'.
3890     SMLoc Loc = Parser.getTok().getLoc();
3891
3892     const MCExpr *ISBarrierID;
3893     if (getParser().parseExpression(ISBarrierID)) {
3894       Error(Loc, "illegal expression");
3895       return MatchOperand_ParseFail;
3896     }
3897
3898     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ISBarrierID);
3899     if (!CE) {
3900       Error(Loc, "constant expression expected");
3901       return MatchOperand_ParseFail;
3902     }
3903
3904     int Val = CE->getValue();
3905     if (Val & ~0xf) {
3906       Error(Loc, "immediate value out of range");
3907       return MatchOperand_ParseFail;
3908     }
3909
3910     Opt = ARM_ISB::RESERVED_0 + Val;
3911   } else
3912     return MatchOperand_ParseFail;
3913
3914   Operands.push_back(ARMOperand::CreateInstSyncBarrierOpt(
3915           (ARM_ISB::InstSyncBOpt)Opt, S));
3916   return MatchOperand_Success;
3917 }
3918
3919
3920 /// parseProcIFlagsOperand - Try to parse iflags from CPS instruction.
3921 ARMAsmParser::OperandMatchResultTy
3922 ARMAsmParser::parseProcIFlagsOperand(OperandVector &Operands) {
3923   MCAsmParser &Parser = getParser();
3924   SMLoc S = Parser.getTok().getLoc();
3925   const AsmToken &Tok = Parser.getTok();
3926   if (!Tok.is(AsmToken::Identifier)) 
3927     return MatchOperand_NoMatch;
3928   StringRef IFlagsStr = Tok.getString();
3929
3930   // An iflags string of "none" is interpreted to mean that none of the AIF
3931   // bits are set.  Not a terribly useful instruction, but a valid encoding.
3932   unsigned IFlags = 0;
3933   if (IFlagsStr != "none") {
3934         for (int i = 0, e = IFlagsStr.size(); i != e; ++i) {
3935       unsigned Flag = StringSwitch<unsigned>(IFlagsStr.substr(i, 1))
3936         .Case("a", ARM_PROC::A)
3937         .Case("i", ARM_PROC::I)
3938         .Case("f", ARM_PROC::F)
3939         .Default(~0U);
3940
3941       // If some specific iflag is already set, it means that some letter is
3942       // present more than once, this is not acceptable.
3943       if (Flag == ~0U || (IFlags & Flag))
3944         return MatchOperand_NoMatch;
3945
3946       IFlags |= Flag;
3947     }
3948   }
3949
3950   Parser.Lex(); // Eat identifier token.
3951   Operands.push_back(ARMOperand::CreateProcIFlags((ARM_PROC::IFlags)IFlags, S));
3952   return MatchOperand_Success;
3953 }
3954
3955 /// parseMSRMaskOperand - Try to parse mask flags from MSR instruction.
3956 ARMAsmParser::OperandMatchResultTy
3957 ARMAsmParser::parseMSRMaskOperand(OperandVector &Operands) {
3958   MCAsmParser &Parser = getParser();
3959   SMLoc S = Parser.getTok().getLoc();
3960   const AsmToken &Tok = Parser.getTok();
3961   if (!Tok.is(AsmToken::Identifier))
3962     return MatchOperand_NoMatch;
3963   StringRef Mask = Tok.getString();
3964
3965   if (isMClass()) {
3966     // See ARMv6-M 10.1.1
3967     std::string Name = Mask.lower();
3968     unsigned FlagsVal = StringSwitch<unsigned>(Name)
3969       // Note: in the documentation:
3970       //  ARM deprecates using MSR APSR without a _<bits> qualifier as an alias
3971       //  for MSR APSR_nzcvq.
3972       // but we do make it an alias here.  This is so to get the "mask encoding"
3973       // bits correct on MSR APSR writes.
3974       //
3975       // FIXME: Note the 0xc00 "mask encoding" bits version of the registers
3976       // should really only be allowed when writing a special register.  Note
3977       // they get dropped in the MRS instruction reading a special register as
3978       // the SYSm field is only 8 bits.
3979       .Case("apsr", 0x800)
3980       .Case("apsr_nzcvq", 0x800)
3981       .Case("apsr_g", 0x400)
3982       .Case("apsr_nzcvqg", 0xc00)
3983       .Case("iapsr", 0x801)
3984       .Case("iapsr_nzcvq", 0x801)
3985       .Case("iapsr_g", 0x401)
3986       .Case("iapsr_nzcvqg", 0xc01)
3987       .Case("eapsr", 0x802)
3988       .Case("eapsr_nzcvq", 0x802)
3989       .Case("eapsr_g", 0x402)
3990       .Case("eapsr_nzcvqg", 0xc02)
3991       .Case("xpsr", 0x803)
3992       .Case("xpsr_nzcvq", 0x803)
3993       .Case("xpsr_g", 0x403)
3994       .Case("xpsr_nzcvqg", 0xc03)
3995       .Case("ipsr", 0x805)
3996       .Case("epsr", 0x806)
3997       .Case("iepsr", 0x807)
3998       .Case("msp", 0x808)
3999       .Case("psp", 0x809)
4000       .Case("primask", 0x810)
4001       .Case("basepri", 0x811)
4002       .Case("basepri_max", 0x812)
4003       .Case("faultmask", 0x813)
4004       .Case("control", 0x814)
4005       .Default(~0U);
4006
4007     if (FlagsVal == ~0U)
4008       return MatchOperand_NoMatch;
4009
4010     if (!hasThumb2DSP() && (FlagsVal & 0x400))
4011       // The _g and _nzcvqg versions are only valid if the DSP extension is
4012       // available.
4013       return MatchOperand_NoMatch;
4014
4015     if (!hasV7Ops() && FlagsVal >= 0x811 && FlagsVal <= 0x813)
4016       // basepri, basepri_max and faultmask only valid for V7m.
4017       return MatchOperand_NoMatch;
4018
4019     Parser.Lex(); // Eat identifier token.
4020     Operands.push_back(ARMOperand::CreateMSRMask(FlagsVal, S));
4021     return MatchOperand_Success;
4022   }
4023
4024   // Split spec_reg from flag, example: CPSR_sxf => "CPSR" and "sxf"
4025   size_t Start = 0, Next = Mask.find('_');
4026   StringRef Flags = "";
4027   std::string SpecReg = Mask.slice(Start, Next).lower();
4028   if (Next != StringRef::npos)
4029     Flags = Mask.slice(Next+1, Mask.size());
4030
4031   // FlagsVal contains the complete mask:
4032   // 3-0: Mask
4033   // 4: Special Reg (cpsr, apsr => 0; spsr => 1)
4034   unsigned FlagsVal = 0;
4035
4036   if (SpecReg == "apsr") {
4037     FlagsVal = StringSwitch<unsigned>(Flags)
4038     .Case("nzcvq",  0x8) // same as CPSR_f
4039     .Case("g",      0x4) // same as CPSR_s
4040     .Case("nzcvqg", 0xc) // same as CPSR_fs
4041     .Default(~0U);
4042
4043     if (FlagsVal == ~0U) {
4044       if (!Flags.empty())
4045         return MatchOperand_NoMatch;
4046       else
4047         FlagsVal = 8; // No flag
4048     }
4049   } else if (SpecReg == "cpsr" || SpecReg == "spsr") {
4050     // cpsr_all is an alias for cpsr_fc, as is plain cpsr.
4051     if (Flags == "all" || Flags == "")
4052       Flags = "fc";
4053     for (int i = 0, e = Flags.size(); i != e; ++i) {
4054       unsigned Flag = StringSwitch<unsigned>(Flags.substr(i, 1))
4055       .Case("c", 1)
4056       .Case("x", 2)
4057       .Case("s", 4)
4058       .Case("f", 8)
4059       .Default(~0U);
4060
4061       // If some specific flag is already set, it means that some letter is
4062       // present more than once, this is not acceptable.
4063       if (FlagsVal == ~0U || (FlagsVal & Flag))
4064         return MatchOperand_NoMatch;
4065       FlagsVal |= Flag;
4066     }
4067   } else // No match for special register.
4068     return MatchOperand_NoMatch;
4069
4070   // Special register without flags is NOT equivalent to "fc" flags.
4071   // NOTE: This is a divergence from gas' behavior.  Uncommenting the following
4072   // two lines would enable gas compatibility at the expense of breaking
4073   // round-tripping.
4074   //
4075   // if (!FlagsVal)
4076   //  FlagsVal = 0x9;
4077
4078   // Bit 4: Special Reg (cpsr, apsr => 0; spsr => 1)
4079   if (SpecReg == "spsr")
4080     FlagsVal |= 16;
4081
4082   Parser.Lex(); // Eat identifier token.
4083   Operands.push_back(ARMOperand::CreateMSRMask(FlagsVal, S));
4084   return MatchOperand_Success;
4085 }
4086
4087 /// parseBankedRegOperand - Try to parse a banked register (e.g. "lr_irq") for
4088 /// use in the MRS/MSR instructions added to support virtualization.
4089 ARMAsmParser::OperandMatchResultTy
4090 ARMAsmParser::parseBankedRegOperand(OperandVector &Operands) {
4091   MCAsmParser &Parser = getParser();
4092   SMLoc S = Parser.getTok().getLoc();
4093   const AsmToken &Tok = Parser.getTok();
4094   if (!Tok.is(AsmToken::Identifier))
4095     return MatchOperand_NoMatch;
4096   StringRef RegName = Tok.getString();
4097
4098   // The values here come from B9.2.3 of the ARM ARM, where bits 4-0 are SysM
4099   // and bit 5 is R.
4100   unsigned Encoding = StringSwitch<unsigned>(RegName.lower())
4101                           .Case("r8_usr", 0x00)
4102                           .Case("r9_usr", 0x01)
4103                           .Case("r10_usr", 0x02)
4104                           .Case("r11_usr", 0x03)
4105                           .Case("r12_usr", 0x04)
4106                           .Case("sp_usr", 0x05)
4107                           .Case("lr_usr", 0x06)
4108                           .Case("r8_fiq", 0x08)
4109                           .Case("r9_fiq", 0x09)
4110                           .Case("r10_fiq", 0x0a)
4111                           .Case("r11_fiq", 0x0b)
4112                           .Case("r12_fiq", 0x0c)
4113                           .Case("sp_fiq", 0x0d)
4114                           .Case("lr_fiq", 0x0e)
4115                           .Case("lr_irq", 0x10)
4116                           .Case("sp_irq", 0x11)
4117                           .Case("lr_svc", 0x12)
4118                           .Case("sp_svc", 0x13)
4119                           .Case("lr_abt", 0x14)
4120                           .Case("sp_abt", 0x15)
4121                           .Case("lr_und", 0x16)
4122                           .Case("sp_und", 0x17)
4123                           .Case("lr_mon", 0x1c)
4124                           .Case("sp_mon", 0x1d)
4125                           .Case("elr_hyp", 0x1e)
4126                           .Case("sp_hyp", 0x1f)
4127                           .Case("spsr_fiq", 0x2e)
4128                           .Case("spsr_irq", 0x30)
4129                           .Case("spsr_svc", 0x32)
4130                           .Case("spsr_abt", 0x34)
4131                           .Case("spsr_und", 0x36)
4132                           .Case("spsr_mon", 0x3c)
4133                           .Case("spsr_hyp", 0x3e)
4134                           .Default(~0U);
4135
4136   if (Encoding == ~0U)
4137     return MatchOperand_NoMatch;
4138
4139   Parser.Lex(); // Eat identifier token.
4140   Operands.push_back(ARMOperand::CreateBankedReg(Encoding, S));
4141   return MatchOperand_Success;
4142 }
4143
4144 ARMAsmParser::OperandMatchResultTy
4145 ARMAsmParser::parsePKHImm(OperandVector &Operands, StringRef Op, int Low,
4146                           int High) {
4147   MCAsmParser &Parser = getParser();
4148   const AsmToken &Tok = Parser.getTok();
4149   if (Tok.isNot(AsmToken::Identifier)) {
4150     Error(Parser.getTok().getLoc(), Op + " operand expected.");
4151     return MatchOperand_ParseFail;
4152   }
4153   StringRef ShiftName = Tok.getString();
4154   std::string LowerOp = Op.lower();
4155   std::string UpperOp = Op.upper();
4156   if (ShiftName != LowerOp && ShiftName != UpperOp) {
4157     Error(Parser.getTok().getLoc(), Op + " operand expected.");
4158     return MatchOperand_ParseFail;
4159   }
4160   Parser.Lex(); // Eat shift type token.
4161
4162   // There must be a '#' and a shift amount.
4163   if (Parser.getTok().isNot(AsmToken::Hash) &&
4164       Parser.getTok().isNot(AsmToken::Dollar)) {
4165     Error(Parser.getTok().getLoc(), "'#' expected");
4166     return MatchOperand_ParseFail;
4167   }
4168   Parser.Lex(); // Eat hash token.
4169
4170   const MCExpr *ShiftAmount;
4171   SMLoc Loc = Parser.getTok().getLoc();
4172   SMLoc EndLoc;
4173   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4174     Error(Loc, "illegal expression");
4175     return MatchOperand_ParseFail;
4176   }
4177   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4178   if (!CE) {
4179     Error(Loc, "constant expression expected");
4180     return MatchOperand_ParseFail;
4181   }
4182   int Val = CE->getValue();
4183   if (Val < Low || Val > High) {
4184     Error(Loc, "immediate value out of range");
4185     return MatchOperand_ParseFail;
4186   }
4187
4188   Operands.push_back(ARMOperand::CreateImm(CE, Loc, EndLoc));
4189
4190   return MatchOperand_Success;
4191 }
4192
4193 ARMAsmParser::OperandMatchResultTy
4194 ARMAsmParser::parseSetEndImm(OperandVector &Operands) {
4195   MCAsmParser &Parser = getParser();
4196   const AsmToken &Tok = Parser.getTok();
4197   SMLoc S = Tok.getLoc();
4198   if (Tok.isNot(AsmToken::Identifier)) {
4199     Error(S, "'be' or 'le' operand expected");
4200     return MatchOperand_ParseFail;
4201   }
4202   int Val = StringSwitch<int>(Tok.getString().lower())
4203     .Case("be", 1)
4204     .Case("le", 0)
4205     .Default(-1);
4206   Parser.Lex(); // Eat the token.
4207
4208   if (Val == -1) {
4209     Error(S, "'be' or 'le' operand expected");
4210     return MatchOperand_ParseFail;
4211   }
4212   Operands.push_back(ARMOperand::CreateImm(MCConstantExpr::Create(Val,
4213                                                                   getContext()),
4214                                            S, Tok.getEndLoc()));
4215   return MatchOperand_Success;
4216 }
4217
4218 /// parseShifterImm - Parse the shifter immediate operand for SSAT/USAT
4219 /// instructions. Legal values are:
4220 ///     lsl #n  'n' in [0,31]
4221 ///     asr #n  'n' in [1,32]
4222 ///             n == 32 encoded as n == 0.
4223 ARMAsmParser::OperandMatchResultTy
4224 ARMAsmParser::parseShifterImm(OperandVector &Operands) {
4225   MCAsmParser &Parser = getParser();
4226   const AsmToken &Tok = Parser.getTok();
4227   SMLoc S = Tok.getLoc();
4228   if (Tok.isNot(AsmToken::Identifier)) {
4229     Error(S, "shift operator 'asr' or 'lsl' expected");
4230     return MatchOperand_ParseFail;
4231   }
4232   StringRef ShiftName = Tok.getString();
4233   bool isASR;
4234   if (ShiftName == "lsl" || ShiftName == "LSL")
4235     isASR = false;
4236   else if (ShiftName == "asr" || ShiftName == "ASR")
4237     isASR = true;
4238   else {
4239     Error(S, "shift operator 'asr' or 'lsl' expected");
4240     return MatchOperand_ParseFail;
4241   }
4242   Parser.Lex(); // Eat the operator.
4243
4244   // A '#' and a shift amount.
4245   if (Parser.getTok().isNot(AsmToken::Hash) &&
4246       Parser.getTok().isNot(AsmToken::Dollar)) {
4247     Error(Parser.getTok().getLoc(), "'#' expected");
4248     return MatchOperand_ParseFail;
4249   }
4250   Parser.Lex(); // Eat hash token.
4251   SMLoc ExLoc = Parser.getTok().getLoc();
4252
4253   const MCExpr *ShiftAmount;
4254   SMLoc EndLoc;
4255   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4256     Error(ExLoc, "malformed shift expression");
4257     return MatchOperand_ParseFail;
4258   }
4259   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4260   if (!CE) {
4261     Error(ExLoc, "shift amount must be an immediate");
4262     return MatchOperand_ParseFail;
4263   }
4264
4265   int64_t Val = CE->getValue();
4266   if (isASR) {
4267     // Shift amount must be in [1,32]
4268     if (Val < 1 || Val > 32) {
4269       Error(ExLoc, "'asr' shift amount must be in range [1,32]");
4270       return MatchOperand_ParseFail;
4271     }
4272     // asr #32 encoded as asr #0, but is not allowed in Thumb2 mode.
4273     if (isThumb() && Val == 32) {
4274       Error(ExLoc, "'asr #32' shift amount not allowed in Thumb mode");
4275       return MatchOperand_ParseFail;
4276     }
4277     if (Val == 32) Val = 0;
4278   } else {
4279     // Shift amount must be in [1,32]
4280     if (Val < 0 || Val > 31) {
4281       Error(ExLoc, "'lsr' shift amount must be in range [0,31]");
4282       return MatchOperand_ParseFail;
4283     }
4284   }
4285
4286   Operands.push_back(ARMOperand::CreateShifterImm(isASR, Val, S, EndLoc));
4287
4288   return MatchOperand_Success;
4289 }
4290
4291 /// parseRotImm - Parse the shifter immediate operand for SXTB/UXTB family
4292 /// of instructions. Legal values are:
4293 ///     ror #n  'n' in {0, 8, 16, 24}
4294 ARMAsmParser::OperandMatchResultTy
4295 ARMAsmParser::parseRotImm(OperandVector &Operands) {
4296   MCAsmParser &Parser = getParser();
4297   const AsmToken &Tok = Parser.getTok();
4298   SMLoc S = Tok.getLoc();
4299   if (Tok.isNot(AsmToken::Identifier))
4300     return MatchOperand_NoMatch;
4301   StringRef ShiftName = Tok.getString();
4302   if (ShiftName != "ror" && ShiftName != "ROR")
4303     return MatchOperand_NoMatch;
4304   Parser.Lex(); // Eat the operator.
4305
4306   // A '#' and a rotate amount.
4307   if (Parser.getTok().isNot(AsmToken::Hash) &&
4308       Parser.getTok().isNot(AsmToken::Dollar)) {
4309     Error(Parser.getTok().getLoc(), "'#' expected");
4310     return MatchOperand_ParseFail;
4311   }
4312   Parser.Lex(); // Eat hash token.
4313   SMLoc ExLoc = Parser.getTok().getLoc();
4314
4315   const MCExpr *ShiftAmount;
4316   SMLoc EndLoc;
4317   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4318     Error(ExLoc, "malformed rotate expression");
4319     return MatchOperand_ParseFail;
4320   }
4321   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4322   if (!CE) {
4323     Error(ExLoc, "rotate amount must be an immediate");
4324     return MatchOperand_ParseFail;
4325   }
4326
4327   int64_t Val = CE->getValue();
4328   // Shift amount must be in {0, 8, 16, 24} (0 is undocumented extension)
4329   // normally, zero is represented in asm by omitting the rotate operand
4330   // entirely.
4331   if (Val != 8 && Val != 16 && Val != 24 && Val != 0) {
4332     Error(ExLoc, "'ror' rotate amount must be 8, 16, or 24");
4333     return MatchOperand_ParseFail;
4334   }
4335
4336   Operands.push_back(ARMOperand::CreateRotImm(Val, S, EndLoc));
4337
4338   return MatchOperand_Success;
4339 }
4340
4341 ARMAsmParser::OperandMatchResultTy
4342 ARMAsmParser::parseBitfield(OperandVector &Operands) {
4343   MCAsmParser &Parser = getParser();
4344   SMLoc S = Parser.getTok().getLoc();
4345   // The bitfield descriptor is really two operands, the LSB and the width.
4346   if (Parser.getTok().isNot(AsmToken::Hash) &&
4347       Parser.getTok().isNot(AsmToken::Dollar)) {
4348     Error(Parser.getTok().getLoc(), "'#' expected");
4349     return MatchOperand_ParseFail;
4350   }
4351   Parser.Lex(); // Eat hash token.
4352
4353   const MCExpr *LSBExpr;
4354   SMLoc E = Parser.getTok().getLoc();
4355   if (getParser().parseExpression(LSBExpr)) {
4356     Error(E, "malformed immediate expression");
4357     return MatchOperand_ParseFail;
4358   }
4359   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LSBExpr);
4360   if (!CE) {
4361     Error(E, "'lsb' operand must be an immediate");
4362     return MatchOperand_ParseFail;
4363   }
4364
4365   int64_t LSB = CE->getValue();
4366   // The LSB must be in the range [0,31]
4367   if (LSB < 0 || LSB > 31) {
4368     Error(E, "'lsb' operand must be in the range [0,31]");
4369     return MatchOperand_ParseFail;
4370   }
4371   E = Parser.getTok().getLoc();
4372
4373   // Expect another immediate operand.
4374   if (Parser.getTok().isNot(AsmToken::Comma)) {
4375     Error(Parser.getTok().getLoc(), "too few operands");
4376     return MatchOperand_ParseFail;
4377   }
4378   Parser.Lex(); // Eat hash token.
4379   if (Parser.getTok().isNot(AsmToken::Hash) &&
4380       Parser.getTok().isNot(AsmToken::Dollar)) {
4381     Error(Parser.getTok().getLoc(), "'#' expected");
4382     return MatchOperand_ParseFail;
4383   }
4384   Parser.Lex(); // Eat hash token.
4385
4386   const MCExpr *WidthExpr;
4387   SMLoc EndLoc;
4388   if (getParser().parseExpression(WidthExpr, EndLoc)) {
4389     Error(E, "malformed immediate expression");
4390     return MatchOperand_ParseFail;
4391   }
4392   CE = dyn_cast<MCConstantExpr>(WidthExpr);
4393   if (!CE) {
4394     Error(E, "'width' operand must be an immediate");
4395     return MatchOperand_ParseFail;
4396   }
4397
4398   int64_t Width = CE->getValue();
4399   // The LSB must be in the range [1,32-lsb]
4400   if (Width < 1 || Width > 32 - LSB) {
4401     Error(E, "'width' operand must be in the range [1,32-lsb]");
4402     return MatchOperand_ParseFail;
4403   }
4404
4405   Operands.push_back(ARMOperand::CreateBitfield(LSB, Width, S, EndLoc));
4406
4407   return MatchOperand_Success;
4408 }
4409
4410 ARMAsmParser::OperandMatchResultTy
4411 ARMAsmParser::parsePostIdxReg(OperandVector &Operands) {
4412   // Check for a post-index addressing register operand. Specifically:
4413   // postidx_reg := '+' register {, shift}
4414   //              | '-' register {, shift}
4415   //              | register {, shift}
4416
4417   // This method must return MatchOperand_NoMatch without consuming any tokens
4418   // in the case where there is no match, as other alternatives take other
4419   // parse methods.
4420   MCAsmParser &Parser = getParser();
4421   AsmToken Tok = Parser.getTok();
4422   SMLoc S = Tok.getLoc();
4423   bool haveEaten = false;
4424   bool isAdd = true;
4425   if (Tok.is(AsmToken::Plus)) {
4426     Parser.Lex(); // Eat the '+' token.
4427     haveEaten = true;
4428   } else if (Tok.is(AsmToken::Minus)) {
4429     Parser.Lex(); // Eat the '-' token.
4430     isAdd = false;
4431     haveEaten = true;
4432   }
4433
4434   SMLoc E = Parser.getTok().getEndLoc();
4435   int Reg = tryParseRegister();
4436   if (Reg == -1) {
4437     if (!haveEaten)
4438       return MatchOperand_NoMatch;
4439     Error(Parser.getTok().getLoc(), "register expected");
4440     return MatchOperand_ParseFail;
4441   }
4442
4443   ARM_AM::ShiftOpc ShiftTy = ARM_AM::no_shift;
4444   unsigned ShiftImm = 0;
4445   if (Parser.getTok().is(AsmToken::Comma)) {
4446     Parser.Lex(); // Eat the ','.
4447     if (parseMemRegOffsetShift(ShiftTy, ShiftImm))
4448       return MatchOperand_ParseFail;
4449
4450     // FIXME: Only approximates end...may include intervening whitespace.
4451     E = Parser.getTok().getLoc();
4452   }
4453
4454   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ShiftTy,
4455                                                   ShiftImm, S, E));
4456
4457   return MatchOperand_Success;
4458 }
4459
4460 ARMAsmParser::OperandMatchResultTy
4461 ARMAsmParser::parseAM3Offset(OperandVector &Operands) {
4462   // Check for a post-index addressing register operand. Specifically:
4463   // am3offset := '+' register
4464   //              | '-' register
4465   //              | register
4466   //              | # imm
4467   //              | # + imm
4468   //              | # - imm
4469
4470   // This method must return MatchOperand_NoMatch without consuming any tokens
4471   // in the case where there is no match, as other alternatives take other
4472   // parse methods.
4473   MCAsmParser &Parser = getParser();
4474   AsmToken Tok = Parser.getTok();
4475   SMLoc S = Tok.getLoc();
4476
4477   // Do immediates first, as we always parse those if we have a '#'.
4478   if (Parser.getTok().is(AsmToken::Hash) ||
4479       Parser.getTok().is(AsmToken::Dollar)) {
4480     Parser.Lex(); // Eat '#' or '$'.
4481     // Explicitly look for a '-', as we need to encode negative zero
4482     // differently.
4483     bool isNegative = Parser.getTok().is(AsmToken::Minus);
4484     const MCExpr *Offset;
4485     SMLoc E;
4486     if (getParser().parseExpression(Offset, E))
4487       return MatchOperand_ParseFail;
4488     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
4489     if (!CE) {
4490       Error(S, "constant expression expected");
4491       return MatchOperand_ParseFail;
4492     }
4493     // Negative zero is encoded as the flag value INT32_MIN.
4494     int32_t Val = CE->getValue();
4495     if (isNegative && Val == 0)
4496       Val = INT32_MIN;
4497
4498     Operands.push_back(
4499       ARMOperand::CreateImm(MCConstantExpr::Create(Val, getContext()), S, E));
4500
4501     return MatchOperand_Success;
4502   }
4503
4504
4505   bool haveEaten = false;
4506   bool isAdd = true;
4507   if (Tok.is(AsmToken::Plus)) {
4508     Parser.Lex(); // Eat the '+' token.
4509     haveEaten = true;
4510   } else if (Tok.is(AsmToken::Minus)) {
4511     Parser.Lex(); // Eat the '-' token.
4512     isAdd = false;
4513     haveEaten = true;
4514   }
4515
4516   Tok = Parser.getTok();
4517   int Reg = tryParseRegister();
4518   if (Reg == -1) {
4519     if (!haveEaten)
4520       return MatchOperand_NoMatch;
4521     Error(Tok.getLoc(), "register expected");
4522     return MatchOperand_ParseFail;
4523   }
4524
4525   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ARM_AM::no_shift,
4526                                                   0, S, Tok.getEndLoc()));
4527
4528   return MatchOperand_Success;
4529 }
4530
4531 /// Convert parsed operands to MCInst.  Needed here because this instruction
4532 /// only has two register operands, but multiplication is commutative so
4533 /// assemblers should accept both "mul rD, rN, rD" and "mul rD, rD, rN".
4534 void ARMAsmParser::cvtThumbMultiply(MCInst &Inst,
4535                                     const OperandVector &Operands) {
4536   ((ARMOperand &)*Operands[3]).addRegOperands(Inst, 1);
4537   ((ARMOperand &)*Operands[1]).addCCOutOperands(Inst, 1);
4538   // If we have a three-operand form, make sure to set Rn to be the operand
4539   // that isn't the same as Rd.
4540   unsigned RegOp = 4;
4541   if (Operands.size() == 6 &&
4542       ((ARMOperand &)*Operands[4]).getReg() ==
4543           ((ARMOperand &)*Operands[3]).getReg())
4544     RegOp = 5;
4545   ((ARMOperand &)*Operands[RegOp]).addRegOperands(Inst, 1);
4546   Inst.addOperand(Inst.getOperand(0));
4547   ((ARMOperand &)*Operands[2]).addCondCodeOperands(Inst, 2);
4548 }
4549
4550 void ARMAsmParser::cvtThumbBranches(MCInst &Inst,
4551                                     const OperandVector &Operands) {
4552   int CondOp = -1, ImmOp = -1;
4553   switch(Inst.getOpcode()) {
4554     case ARM::tB:
4555     case ARM::tBcc:  CondOp = 1; ImmOp = 2; break;
4556
4557     case ARM::t2B:
4558     case ARM::t2Bcc: CondOp = 1; ImmOp = 3; break;
4559
4560     default: llvm_unreachable("Unexpected instruction in cvtThumbBranches");
4561   }
4562   // first decide whether or not the branch should be conditional
4563   // by looking at it's location relative to an IT block
4564   if(inITBlock()) {
4565     // inside an IT block we cannot have any conditional branches. any 
4566     // such instructions needs to be converted to unconditional form
4567     switch(Inst.getOpcode()) {
4568       case ARM::tBcc: Inst.setOpcode(ARM::tB); break;
4569       case ARM::t2Bcc: Inst.setOpcode(ARM::t2B); break;
4570     }
4571   } else {
4572     // outside IT blocks we can only have unconditional branches with AL
4573     // condition code or conditional branches with non-AL condition code
4574     unsigned Cond = static_cast<ARMOperand &>(*Operands[CondOp]).getCondCode();
4575     switch(Inst.getOpcode()) {
4576       case ARM::tB:
4577       case ARM::tBcc: 
4578         Inst.setOpcode(Cond == ARMCC::AL ? ARM::tB : ARM::tBcc); 
4579         break;
4580       case ARM::t2B:
4581       case ARM::t2Bcc: 
4582         Inst.setOpcode(Cond == ARMCC::AL ? ARM::t2B : ARM::t2Bcc);
4583         break;
4584     }
4585   }
4586
4587   // now decide on encoding size based on branch target range
4588   switch(Inst.getOpcode()) {
4589     // classify tB as either t2B or t1B based on range of immediate operand
4590     case ARM::tB: {
4591       ARMOperand &op = static_cast<ARMOperand &>(*Operands[ImmOp]);
4592       if (!op.isSignedOffset<11, 1>() && isThumbTwo())
4593         Inst.setOpcode(ARM::t2B);
4594       break;
4595     }
4596     // classify tBcc as either t2Bcc or t1Bcc based on range of immediate operand
4597     case ARM::tBcc: {
4598       ARMOperand &op = static_cast<ARMOperand &>(*Operands[ImmOp]);
4599       if (!op.isSignedOffset<8, 1>() && isThumbTwo())
4600         Inst.setOpcode(ARM::t2Bcc);
4601       break;
4602     }
4603   }
4604   ((ARMOperand &)*Operands[ImmOp]).addImmOperands(Inst, 1);
4605   ((ARMOperand &)*Operands[CondOp]).addCondCodeOperands(Inst, 2);
4606 }
4607
4608 /// Parse an ARM memory expression, return false if successful else return true
4609 /// or an error.  The first token must be a '[' when called.
4610 bool ARMAsmParser::parseMemory(OperandVector &Operands) {
4611   MCAsmParser &Parser = getParser();
4612   SMLoc S, E;
4613   assert(Parser.getTok().is(AsmToken::LBrac) &&
4614          "Token is not a Left Bracket");
4615   S = Parser.getTok().getLoc();
4616   Parser.Lex(); // Eat left bracket token.
4617
4618   const AsmToken &BaseRegTok = Parser.getTok();
4619   int BaseRegNum = tryParseRegister();
4620   if (BaseRegNum == -1)
4621     return Error(BaseRegTok.getLoc(), "register expected");
4622
4623   // The next token must either be a comma, a colon or a closing bracket.
4624   const AsmToken &Tok = Parser.getTok();
4625   if (!Tok.is(AsmToken::Colon) && !Tok.is(AsmToken::Comma) &&
4626       !Tok.is(AsmToken::RBrac))
4627     return Error(Tok.getLoc(), "malformed memory operand");
4628
4629   if (Tok.is(AsmToken::RBrac)) {
4630     E = Tok.getEndLoc();
4631     Parser.Lex(); // Eat right bracket token.
4632
4633     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, 0,
4634                                              ARM_AM::no_shift, 0, 0, false,
4635                                              S, E));
4636
4637     // If there's a pre-indexing writeback marker, '!', just add it as a token
4638     // operand. It's rather odd, but syntactically valid.
4639     if (Parser.getTok().is(AsmToken::Exclaim)) {
4640       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
4641       Parser.Lex(); // Eat the '!'.
4642     }
4643
4644     return false;
4645   }
4646
4647   assert((Tok.is(AsmToken::Colon) || Tok.is(AsmToken::Comma)) &&
4648          "Lost colon or comma in memory operand?!");
4649   if (Tok.is(AsmToken::Comma)) {
4650     Parser.Lex(); // Eat the comma.
4651   }
4652
4653   // If we have a ':', it's an alignment specifier.
4654   if (Parser.getTok().is(AsmToken::Colon)) {
4655     Parser.Lex(); // Eat the ':'.
4656     E = Parser.getTok().getLoc();
4657     SMLoc AlignmentLoc = Tok.getLoc();
4658
4659     const MCExpr *Expr;
4660     if (getParser().parseExpression(Expr))
4661      return true;
4662
4663     // The expression has to be a constant. Memory references with relocations
4664     // don't come through here, as they use the <label> forms of the relevant
4665     // instructions.
4666     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
4667     if (!CE)
4668       return Error (E, "constant expression expected");
4669
4670     unsigned Align = 0;
4671     switch (CE->getValue()) {
4672     default:
4673       return Error(E,
4674                    "alignment specifier must be 16, 32, 64, 128, or 256 bits");
4675     case 16:  Align = 2; break;
4676     case 32:  Align = 4; break;
4677     case 64:  Align = 8; break;
4678     case 128: Align = 16; break;
4679     case 256: Align = 32; break;
4680     }
4681
4682     // Now we should have the closing ']'
4683     if (Parser.getTok().isNot(AsmToken::RBrac))
4684       return Error(Parser.getTok().getLoc(), "']' expected");
4685     E = Parser.getTok().getEndLoc();
4686     Parser.Lex(); // Eat right bracket token.
4687
4688     // Don't worry about range checking the value here. That's handled by
4689     // the is*() predicates.
4690     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, 0,
4691                                              ARM_AM::no_shift, 0, Align,
4692                                              false, S, E, AlignmentLoc));
4693
4694     // If there's a pre-indexing writeback marker, '!', just add it as a token
4695     // operand.
4696     if (Parser.getTok().is(AsmToken::Exclaim)) {
4697       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
4698       Parser.Lex(); // Eat the '!'.
4699     }
4700
4701     return false;
4702   }
4703
4704   // If we have a '#', it's an immediate offset, else assume it's a register
4705   // offset. Be friendly and also accept a plain integer (without a leading
4706   // hash) for gas compatibility.
4707   if (Parser.getTok().is(AsmToken::Hash) ||
4708       Parser.getTok().is(AsmToken::Dollar) ||
4709       Parser.getTok().is(AsmToken::Integer)) {
4710     if (Parser.getTok().isNot(AsmToken::Integer))
4711       Parser.Lex(); // Eat '#' or '$'.
4712     E = Parser.getTok().getLoc();
4713
4714     bool isNegative = getParser().getTok().is(AsmToken::Minus);
4715     const MCExpr *Offset;
4716     if (getParser().parseExpression(Offset))
4717      return true;
4718
4719     // The expression has to be a constant. Memory references with relocations
4720     // don't come through here, as they use the <label> forms of the relevant
4721     // instructions.
4722     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
4723     if (!CE)
4724       return Error (E, "constant expression expected");
4725
4726     // If the constant was #-0, represent it as INT32_MIN.
4727     int32_t Val = CE->getValue();
4728     if (isNegative && Val == 0)
4729       CE = MCConstantExpr::Create(INT32_MIN, getContext());
4730
4731     // Now we should have the closing ']'
4732     if (Parser.getTok().isNot(AsmToken::RBrac))
4733       return Error(Parser.getTok().getLoc(), "']' expected");
4734     E = Parser.getTok().getEndLoc();
4735     Parser.Lex(); // Eat right bracket token.
4736
4737     // Don't worry about range checking the value here. That's handled by
4738     // the is*() predicates.
4739     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, CE, 0,
4740                                              ARM_AM::no_shift, 0, 0,
4741                                              false, S, E));
4742
4743     // If there's a pre-indexing writeback marker, '!', just add it as a token
4744     // operand.
4745     if (Parser.getTok().is(AsmToken::Exclaim)) {
4746       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
4747       Parser.Lex(); // Eat the '!'.
4748     }
4749
4750     return false;
4751   }
4752
4753   // The register offset is optionally preceded by a '+' or '-'
4754   bool isNegative = false;
4755   if (Parser.getTok().is(AsmToken::Minus)) {
4756     isNegative = true;
4757     Parser.Lex(); // Eat the '-'.
4758   } else if (Parser.getTok().is(AsmToken::Plus)) {
4759     // Nothing to do.
4760     Parser.Lex(); // Eat the '+'.
4761   }
4762
4763   E = Parser.getTok().getLoc();
4764   int OffsetRegNum = tryParseRegister();
4765   if (OffsetRegNum == -1)
4766     return Error(E, "register expected");
4767
4768   // If there's a shift operator, handle it.
4769   ARM_AM::ShiftOpc ShiftType = ARM_AM::no_shift;
4770   unsigned ShiftImm = 0;
4771   if (Parser.getTok().is(AsmToken::Comma)) {
4772     Parser.Lex(); // Eat the ','.
4773     if (parseMemRegOffsetShift(ShiftType, ShiftImm))
4774       return true;
4775   }
4776
4777   // Now we should have the closing ']'
4778   if (Parser.getTok().isNot(AsmToken::RBrac))
4779     return Error(Parser.getTok().getLoc(), "']' expected");
4780   E = Parser.getTok().getEndLoc();
4781   Parser.Lex(); // Eat right bracket token.
4782
4783   Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, OffsetRegNum,
4784                                            ShiftType, ShiftImm, 0, isNegative,
4785                                            S, E));
4786
4787   // If there's a pre-indexing writeback marker, '!', just add it as a token
4788   // operand.
4789   if (Parser.getTok().is(AsmToken::Exclaim)) {
4790     Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
4791     Parser.Lex(); // Eat the '!'.
4792   }
4793
4794   return false;
4795 }
4796
4797 /// parseMemRegOffsetShift - one of these two:
4798 ///   ( lsl | lsr | asr | ror ) , # shift_amount
4799 ///   rrx
4800 /// return true if it parses a shift otherwise it returns false.
4801 bool ARMAsmParser::parseMemRegOffsetShift(ARM_AM::ShiftOpc &St,
4802                                           unsigned &Amount) {
4803   MCAsmParser &Parser = getParser();
4804   SMLoc Loc = Parser.getTok().getLoc();
4805   const AsmToken &Tok = Parser.getTok();
4806   if (Tok.isNot(AsmToken::Identifier))
4807     return true;
4808   StringRef ShiftName = Tok.getString();
4809   if (ShiftName == "lsl" || ShiftName == "LSL" ||
4810       ShiftName == "asl" || ShiftName == "ASL")
4811     St = ARM_AM::lsl;
4812   else if (ShiftName == "lsr" || ShiftName == "LSR")
4813     St = ARM_AM::lsr;
4814   else if (ShiftName == "asr" || ShiftName == "ASR")
4815     St = ARM_AM::asr;
4816   else if (ShiftName == "ror" || ShiftName == "ROR")
4817     St = ARM_AM::ror;
4818   else if (ShiftName == "rrx" || ShiftName == "RRX")
4819     St = ARM_AM::rrx;
4820   else
4821     return Error(Loc, "illegal shift operator");
4822   Parser.Lex(); // Eat shift type token.
4823
4824   // rrx stands alone.
4825   Amount = 0;
4826   if (St != ARM_AM::rrx) {
4827     Loc = Parser.getTok().getLoc();
4828     // A '#' and a shift amount.
4829     const AsmToken &HashTok = Parser.getTok();
4830     if (HashTok.isNot(AsmToken::Hash) &&
4831         HashTok.isNot(AsmToken::Dollar))
4832       return Error(HashTok.getLoc(), "'#' expected");
4833     Parser.Lex(); // Eat hash token.
4834
4835     const MCExpr *Expr;
4836     if (getParser().parseExpression(Expr))
4837       return true;
4838     // Range check the immediate.
4839     // lsl, ror: 0 <= imm <= 31
4840     // lsr, asr: 0 <= imm <= 32
4841     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
4842     if (!CE)
4843       return Error(Loc, "shift amount must be an immediate");
4844     int64_t Imm = CE->getValue();
4845     if (Imm < 0 ||
4846         ((St == ARM_AM::lsl || St == ARM_AM::ror) && Imm > 31) ||
4847         ((St == ARM_AM::lsr || St == ARM_AM::asr) && Imm > 32))
4848       return Error(Loc, "immediate shift value out of range");
4849     // If <ShiftTy> #0, turn it into a no_shift.
4850     if (Imm == 0)
4851       St = ARM_AM::lsl;
4852     // For consistency, treat lsr #32 and asr #32 as having immediate value 0.
4853     if (Imm == 32)
4854       Imm = 0;
4855     Amount = Imm;
4856   }
4857
4858   return false;
4859 }
4860
4861 /// parseFPImm - A floating point immediate expression operand.
4862 ARMAsmParser::OperandMatchResultTy
4863 ARMAsmParser::parseFPImm(OperandVector &Operands) {
4864   MCAsmParser &Parser = getParser();
4865   // Anything that can accept a floating point constant as an operand
4866   // needs to go through here, as the regular parseExpression is
4867   // integer only.
4868   //
4869   // This routine still creates a generic Immediate operand, containing
4870   // a bitcast of the 64-bit floating point value. The various operands
4871   // that accept floats can check whether the value is valid for them
4872   // via the standard is*() predicates.
4873
4874   SMLoc S = Parser.getTok().getLoc();
4875
4876   if (Parser.getTok().isNot(AsmToken::Hash) &&
4877       Parser.getTok().isNot(AsmToken::Dollar))
4878     return MatchOperand_NoMatch;
4879
4880   // Disambiguate the VMOV forms that can accept an FP immediate.
4881   // vmov.f32 <sreg>, #imm
4882   // vmov.f64 <dreg>, #imm
4883   // vmov.f32 <dreg>, #imm  @ vector f32x2
4884   // vmov.f32 <qreg>, #imm  @ vector f32x4
4885   //
4886   // There are also the NEON VMOV instructions which expect an
4887   // integer constant. Make sure we don't try to parse an FPImm
4888   // for these:
4889   // vmov.i{8|16|32|64} <dreg|qreg>, #imm
4890   ARMOperand &TyOp = static_cast<ARMOperand &>(*Operands[2]);
4891   bool isVmovf = TyOp.isToken() &&
4892                  (TyOp.getToken() == ".f32" || TyOp.getToken() == ".f64");
4893   ARMOperand &Mnemonic = static_cast<ARMOperand &>(*Operands[0]);
4894   bool isFconst = Mnemonic.isToken() && (Mnemonic.getToken() == "fconstd" ||
4895                                          Mnemonic.getToken() == "fconsts");
4896   if (!(isVmovf || isFconst))
4897     return MatchOperand_NoMatch;
4898
4899   Parser.Lex(); // Eat '#' or '$'.
4900
4901   // Handle negation, as that still comes through as a separate token.
4902   bool isNegative = false;
4903   if (Parser.getTok().is(AsmToken::Minus)) {
4904     isNegative = true;
4905     Parser.Lex();
4906   }
4907   const AsmToken &Tok = Parser.getTok();
4908   SMLoc Loc = Tok.getLoc();
4909   if (Tok.is(AsmToken::Real) && isVmovf) {
4910     APFloat RealVal(APFloat::IEEEsingle, Tok.getString());
4911     uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
4912     // If we had a '-' in front, toggle the sign bit.
4913     IntVal ^= (uint64_t)isNegative << 31;
4914     Parser.Lex(); // Eat the token.
4915     Operands.push_back(ARMOperand::CreateImm(
4916           MCConstantExpr::Create(IntVal, getContext()),
4917           S, Parser.getTok().getLoc()));
4918     return MatchOperand_Success;
4919   }
4920   // Also handle plain integers. Instructions which allow floating point
4921   // immediates also allow a raw encoded 8-bit value.
4922   if (Tok.is(AsmToken::Integer) && isFconst) {
4923     int64_t Val = Tok.getIntVal();
4924     Parser.Lex(); // Eat the token.
4925     if (Val > 255 || Val < 0) {
4926       Error(Loc, "encoded floating point value out of range");
4927       return MatchOperand_ParseFail;
4928     }
4929     float RealVal = ARM_AM::getFPImmFloat(Val);
4930     Val = APFloat(RealVal).bitcastToAPInt().getZExtValue();
4931
4932     Operands.push_back(ARMOperand::CreateImm(
4933         MCConstantExpr::Create(Val, getContext()), S,
4934         Parser.getTok().getLoc()));
4935     return MatchOperand_Success;
4936   }
4937
4938   Error(Loc, "invalid floating point immediate");
4939   return MatchOperand_ParseFail;
4940 }
4941
4942 /// Parse a arm instruction operand.  For now this parses the operand regardless
4943 /// of the mnemonic.
4944 bool ARMAsmParser::parseOperand(OperandVector &Operands, StringRef Mnemonic) {
4945   MCAsmParser &Parser = getParser();
4946   SMLoc S, E;
4947
4948   // Check if the current operand has a custom associated parser, if so, try to
4949   // custom parse the operand, or fallback to the general approach.
4950   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
4951   if (ResTy == MatchOperand_Success)
4952     return false;
4953   // If there wasn't a custom match, try the generic matcher below. Otherwise,
4954   // there was a match, but an error occurred, in which case, just return that
4955   // the operand parsing failed.
4956   if (ResTy == MatchOperand_ParseFail)
4957     return true;
4958
4959   switch (getLexer().getKind()) {
4960   default:
4961     Error(Parser.getTok().getLoc(), "unexpected token in operand");
4962     return true;
4963   case AsmToken::Identifier: {
4964     // If we've seen a branch mnemonic, the next operand must be a label.  This
4965     // is true even if the label is a register name.  So "br r1" means branch to
4966     // label "r1".
4967     bool ExpectLabel = Mnemonic == "b" || Mnemonic == "bl";
4968     if (!ExpectLabel) {
4969       if (!tryParseRegisterWithWriteBack(Operands))
4970         return false;
4971       int Res = tryParseShiftRegister(Operands);
4972       if (Res == 0) // success
4973         return false;
4974       else if (Res == -1) // irrecoverable error
4975         return true;
4976       // If this is VMRS, check for the apsr_nzcv operand.
4977       if (Mnemonic == "vmrs" &&
4978           Parser.getTok().getString().equals_lower("apsr_nzcv")) {
4979         S = Parser.getTok().getLoc();
4980         Parser.Lex();
4981         Operands.push_back(ARMOperand::CreateToken("APSR_nzcv", S));
4982         return false;
4983       }
4984     }
4985
4986     // Fall though for the Identifier case that is not a register or a
4987     // special name.
4988   }
4989   case AsmToken::LParen:  // parenthesized expressions like (_strcmp-4)
4990   case AsmToken::Integer: // things like 1f and 2b as a branch targets
4991   case AsmToken::String:  // quoted label names.
4992   case AsmToken::Dot: {   // . as a branch target
4993     // This was not a register so parse other operands that start with an
4994     // identifier (like labels) as expressions and create them as immediates.
4995     const MCExpr *IdVal;
4996     S = Parser.getTok().getLoc();
4997     if (getParser().parseExpression(IdVal))
4998       return true;
4999     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5000     Operands.push_back(ARMOperand::CreateImm(IdVal, S, E));
5001     return false;
5002   }
5003   case AsmToken::LBrac:
5004     return parseMemory(Operands);
5005   case AsmToken::LCurly:
5006     return parseRegisterList(Operands);
5007   case AsmToken::Dollar:
5008   case AsmToken::Hash: {
5009     // #42 -> immediate.
5010     S = Parser.getTok().getLoc();
5011     Parser.Lex();
5012
5013     if (Parser.getTok().isNot(AsmToken::Colon)) {
5014       bool isNegative = Parser.getTok().is(AsmToken::Minus);
5015       const MCExpr *ImmVal;
5016       if (getParser().parseExpression(ImmVal))
5017         return true;
5018       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ImmVal);
5019       if (CE) {
5020         int32_t Val = CE->getValue();
5021         if (isNegative && Val == 0)
5022           ImmVal = MCConstantExpr::Create(INT32_MIN, getContext());
5023       }
5024       E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5025       Operands.push_back(ARMOperand::CreateImm(ImmVal, S, E));
5026
5027       // There can be a trailing '!' on operands that we want as a separate
5028       // '!' Token operand. Handle that here. For example, the compatibility
5029       // alias for 'srsdb sp!, #imm' is 'srsdb #imm!'.
5030       if (Parser.getTok().is(AsmToken::Exclaim)) {
5031         Operands.push_back(ARMOperand::CreateToken(Parser.getTok().getString(),
5032                                                    Parser.getTok().getLoc()));
5033         Parser.Lex(); // Eat exclaim token
5034       }
5035       return false;
5036     }
5037     // w/ a ':' after the '#', it's just like a plain ':'.
5038     // FALLTHROUGH
5039   }
5040   case AsmToken::Colon: {
5041     // ":lower16:" and ":upper16:" expression prefixes
5042     // FIXME: Check it's an expression prefix,
5043     // e.g. (FOO - :lower16:BAR) isn't legal.
5044     ARMMCExpr::VariantKind RefKind;
5045     if (parsePrefix(RefKind))
5046       return true;
5047
5048     const MCExpr *SubExprVal;
5049     if (getParser().parseExpression(SubExprVal))
5050       return true;
5051
5052     const MCExpr *ExprVal = ARMMCExpr::Create(RefKind, SubExprVal,
5053                                               getContext());
5054     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5055     Operands.push_back(ARMOperand::CreateImm(ExprVal, S, E));
5056     return false;
5057   }
5058   case AsmToken::Equal: {
5059     if (Mnemonic != "ldr") // only parse for ldr pseudo (e.g. ldr r0, =val)
5060       return Error(Parser.getTok().getLoc(), "unexpected token in operand");
5061
5062     Parser.Lex(); // Eat '='
5063     const MCExpr *SubExprVal;
5064     if (getParser().parseExpression(SubExprVal))
5065       return true;
5066     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5067
5068     const MCExpr *CPLoc = getTargetStreamer().addConstantPoolEntry(SubExprVal);
5069     Operands.push_back(ARMOperand::CreateImm(CPLoc, S, E));
5070     return false;
5071   }
5072   }
5073 }
5074
5075 // parsePrefix - Parse ARM 16-bit relocations expression prefix, i.e.
5076 //  :lower16: and :upper16:.
5077 bool ARMAsmParser::parsePrefix(ARMMCExpr::VariantKind &RefKind) {
5078   MCAsmParser &Parser = getParser();
5079   RefKind = ARMMCExpr::VK_ARM_None;
5080
5081   // consume an optional '#' (GNU compatibility)
5082   if (getLexer().is(AsmToken::Hash))
5083     Parser.Lex();
5084
5085   // :lower16: and :upper16: modifiers
5086   assert(getLexer().is(AsmToken::Colon) && "expected a :");
5087   Parser.Lex(); // Eat ':'
5088
5089   if (getLexer().isNot(AsmToken::Identifier)) {
5090     Error(Parser.getTok().getLoc(), "expected prefix identifier in operand");
5091     return true;
5092   }
5093
5094   StringRef IDVal = Parser.getTok().getIdentifier();
5095   if (IDVal == "lower16") {
5096     RefKind = ARMMCExpr::VK_ARM_LO16;
5097   } else if (IDVal == "upper16") {
5098     RefKind = ARMMCExpr::VK_ARM_HI16;
5099   } else {
5100     Error(Parser.getTok().getLoc(), "unexpected prefix in operand");
5101     return true;
5102   }
5103   Parser.Lex();
5104
5105   if (getLexer().isNot(AsmToken::Colon)) {
5106     Error(Parser.getTok().getLoc(), "unexpected token after prefix");
5107     return true;
5108   }
5109   Parser.Lex(); // Eat the last ':'
5110   return false;
5111 }
5112
5113 /// \brief Given a mnemonic, split out possible predication code and carry
5114 /// setting letters to form a canonical mnemonic and flags.
5115 //
5116 // FIXME: Would be nice to autogen this.
5117 // FIXME: This is a bit of a maze of special cases.
5118 StringRef ARMAsmParser::splitMnemonic(StringRef Mnemonic,
5119                                       unsigned &PredicationCode,
5120                                       bool &CarrySetting,
5121                                       unsigned &ProcessorIMod,
5122                                       StringRef &ITMask) {
5123   PredicationCode = ARMCC::AL;
5124   CarrySetting = false;
5125   ProcessorIMod = 0;
5126
5127   // Ignore some mnemonics we know aren't predicated forms.
5128   //
5129   // FIXME: Would be nice to autogen this.
5130   if ((Mnemonic == "movs" && isThumb()) ||
5131       Mnemonic == "teq"   || Mnemonic == "vceq"   || Mnemonic == "svc"   ||
5132       Mnemonic == "mls"   || Mnemonic == "smmls"  || Mnemonic == "vcls"  ||
5133       Mnemonic == "vmls"  || Mnemonic == "vnmls"  || Mnemonic == "vacge" ||
5134       Mnemonic == "vcge"  || Mnemonic == "vclt"   || Mnemonic == "vacgt" ||
5135       Mnemonic == "vaclt" || Mnemonic == "vacle"  || Mnemonic == "hlt" ||
5136       Mnemonic == "vcgt"  || Mnemonic == "vcle"   || Mnemonic == "smlal" ||
5137       Mnemonic == "umaal" || Mnemonic == "umlal"  || Mnemonic == "vabal" ||
5138       Mnemonic == "vmlal" || Mnemonic == "vpadal" || Mnemonic == "vqdmlal" ||
5139       Mnemonic == "fmuls" || Mnemonic == "vmaxnm" || Mnemonic == "vminnm" ||
5140       Mnemonic == "vcvta" || Mnemonic == "vcvtn"  || Mnemonic == "vcvtp" ||
5141       Mnemonic == "vcvtm" || Mnemonic == "vrinta" || Mnemonic == "vrintn" ||
5142       Mnemonic == "vrintp" || Mnemonic == "vrintm" || Mnemonic.startswith("vsel"))
5143     return Mnemonic;
5144
5145   // First, split out any predication code. Ignore mnemonics we know aren't
5146   // predicated but do have a carry-set and so weren't caught above.
5147   if (Mnemonic != "adcs" && Mnemonic != "bics" && Mnemonic != "movs" &&
5148       Mnemonic != "muls" && Mnemonic != "smlals" && Mnemonic != "smulls" &&
5149       Mnemonic != "umlals" && Mnemonic != "umulls" && Mnemonic != "lsls" &&
5150       Mnemonic != "sbcs" && Mnemonic != "rscs") {
5151     unsigned CC = StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2))
5152       .Case("eq", ARMCC::EQ)
5153       .Case("ne", ARMCC::NE)
5154       .Case("hs", ARMCC::HS)
5155       .Case("cs", ARMCC::HS)
5156       .Case("lo", ARMCC::LO)
5157       .Case("cc", ARMCC::LO)
5158       .Case("mi", ARMCC::MI)
5159       .Case("pl", ARMCC::PL)
5160       .Case("vs", ARMCC::VS)
5161       .Case("vc", ARMCC::VC)
5162       .Case("hi", ARMCC::HI)
5163       .Case("ls", ARMCC::LS)
5164       .Case("ge", ARMCC::GE)
5165       .Case("lt", ARMCC::LT)
5166       .Case("gt", ARMCC::GT)
5167       .Case("le", ARMCC::LE)
5168       .Case("al", ARMCC::AL)
5169       .Default(~0U);
5170     if (CC != ~0U) {
5171       Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 2);
5172       PredicationCode = CC;
5173     }
5174   }
5175
5176   // Next, determine if we have a carry setting bit. We explicitly ignore all
5177   // the instructions we know end in 's'.
5178   if (Mnemonic.endswith("s") &&
5179       !(Mnemonic == "cps" || Mnemonic == "mls" ||
5180         Mnemonic == "mrs" || Mnemonic == "smmls" || Mnemonic == "vabs" ||
5181         Mnemonic == "vcls" || Mnemonic == "vmls" || Mnemonic == "vmrs" ||
5182         Mnemonic == "vnmls" || Mnemonic == "vqabs" || Mnemonic == "vrecps" ||
5183         Mnemonic == "vrsqrts" || Mnemonic == "srs" || Mnemonic == "flds" ||
5184         Mnemonic == "fmrs" || Mnemonic == "fsqrts" || Mnemonic == "fsubs" ||
5185         Mnemonic == "fsts" || Mnemonic == "fcpys" || Mnemonic == "fdivs" ||
5186         Mnemonic == "fmuls" || Mnemonic == "fcmps" || Mnemonic == "fcmpzs" ||
5187         Mnemonic == "vfms" || Mnemonic == "vfnms" || Mnemonic == "fconsts" ||
5188         (Mnemonic == "movs" && isThumb()))) {
5189     Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 1);
5190     CarrySetting = true;
5191   }
5192
5193   // The "cps" instruction can have a interrupt mode operand which is glued into
5194   // the mnemonic. Check if this is the case, split it and parse the imod op
5195   if (Mnemonic.startswith("cps")) {
5196     // Split out any imod code.
5197     unsigned IMod =
5198       StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2, 2))
5199       .Case("ie", ARM_PROC::IE)
5200       .Case("id", ARM_PROC::ID)
5201       .Default(~0U);
5202     if (IMod != ~0U) {
5203       Mnemonic = Mnemonic.slice(0, Mnemonic.size()-2);
5204       ProcessorIMod = IMod;
5205     }
5206   }
5207
5208   // The "it" instruction has the condition mask on the end of the mnemonic.
5209   if (Mnemonic.startswith("it")) {
5210     ITMask = Mnemonic.slice(2, Mnemonic.size());
5211     Mnemonic = Mnemonic.slice(0, 2);
5212   }
5213
5214   return Mnemonic;
5215 }
5216
5217 /// \brief Given a canonical mnemonic, determine if the instruction ever allows
5218 /// inclusion of carry set or predication code operands.
5219 //
5220 // FIXME: It would be nice to autogen this.
5221 void ARMAsmParser::
5222 getMnemonicAcceptInfo(StringRef Mnemonic, StringRef FullInst,
5223                      bool &CanAcceptCarrySet, bool &CanAcceptPredicationCode) {
5224   if (Mnemonic == "and" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
5225       Mnemonic == "rrx" || Mnemonic == "ror" || Mnemonic == "sub" ||
5226       Mnemonic == "add" || Mnemonic == "adc" ||
5227       Mnemonic == "mul" || Mnemonic == "bic" || Mnemonic == "asr" ||
5228       Mnemonic == "orr" || Mnemonic == "mvn" ||
5229       Mnemonic == "rsb" || Mnemonic == "rsc" || Mnemonic == "orn" ||
5230       Mnemonic == "sbc" || Mnemonic == "eor" || Mnemonic == "neg" ||
5231       Mnemonic == "vfm" || Mnemonic == "vfnm" ||
5232       (!isThumb() && (Mnemonic == "smull" || Mnemonic == "mov" ||
5233                       Mnemonic == "mla" || Mnemonic == "smlal" ||
5234                       Mnemonic == "umlal" || Mnemonic == "umull"))) {
5235     CanAcceptCarrySet = true;
5236   } else
5237     CanAcceptCarrySet = false;
5238
5239   if (Mnemonic == "bkpt" || Mnemonic == "cbnz" || Mnemonic == "setend" ||
5240       Mnemonic == "cps" ||  Mnemonic == "it" ||  Mnemonic == "cbz" ||
5241       Mnemonic == "trap" || Mnemonic == "hlt" || Mnemonic == "udf" ||
5242       Mnemonic.startswith("crc32") || Mnemonic.startswith("cps") ||
5243       Mnemonic.startswith("vsel") ||
5244       Mnemonic == "vmaxnm" || Mnemonic == "vminnm" || Mnemonic == "vcvta" ||
5245       Mnemonic == "vcvtn" || Mnemonic == "vcvtp" || Mnemonic == "vcvtm" ||
5246       Mnemonic == "vrinta" || Mnemonic == "vrintn" || Mnemonic == "vrintp" ||
5247       Mnemonic == "vrintm" || Mnemonic.startswith("aes") ||
5248       Mnemonic.startswith("sha1") || Mnemonic.startswith("sha256") ||
5249       (FullInst.startswith("vmull") && FullInst.endswith(".p64"))) {
5250     // These mnemonics are never predicable
5251     CanAcceptPredicationCode = false;
5252   } else if (!isThumb()) {
5253     // Some instructions are only predicable in Thumb mode
5254     CanAcceptPredicationCode
5255       = Mnemonic != "cdp2" && Mnemonic != "clrex" && Mnemonic != "mcr2" &&
5256         Mnemonic != "mcrr2" && Mnemonic != "mrc2" && Mnemonic != "mrrc2" &&
5257         Mnemonic != "dmb" && Mnemonic != "dsb" && Mnemonic != "isb" &&
5258         Mnemonic != "pld" && Mnemonic != "pli" && Mnemonic != "pldw" &&
5259         Mnemonic != "ldc2" && Mnemonic != "ldc2l" &&
5260         Mnemonic != "stc2" && Mnemonic != "stc2l" &&
5261         !Mnemonic.startswith("rfe") && !Mnemonic.startswith("srs");
5262   } else if (isThumbOne()) {
5263     if (hasV6MOps())
5264       CanAcceptPredicationCode = Mnemonic != "movs";
5265     else
5266       CanAcceptPredicationCode = Mnemonic != "nop" && Mnemonic != "movs";
5267   } else
5268     CanAcceptPredicationCode = true;
5269 }
5270
5271 bool ARMAsmParser::shouldOmitCCOutOperand(StringRef Mnemonic,
5272                                           OperandVector &Operands) {
5273   // FIXME: This is all horribly hacky. We really need a better way to deal
5274   // with optional operands like this in the matcher table.
5275
5276   // The 'mov' mnemonic is special. One variant has a cc_out operand, while
5277   // another does not. Specifically, the MOVW instruction does not. So we
5278   // special case it here and remove the defaulted (non-setting) cc_out
5279   // operand if that's the instruction we're trying to match.
5280   //
5281   // We do this as post-processing of the explicit operands rather than just
5282   // conditionally adding the cc_out in the first place because we need
5283   // to check the type of the parsed immediate operand.
5284   if (Mnemonic == "mov" && Operands.size() > 4 && !isThumb() &&
5285       !static_cast<ARMOperand &>(*Operands[4]).isARMSOImm() &&
5286       static_cast<ARMOperand &>(*Operands[4]).isImm0_65535Expr() &&
5287       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0)
5288     return true;
5289
5290   // Register-register 'add' for thumb does not have a cc_out operand
5291   // when there are only two register operands.
5292   if (isThumb() && Mnemonic == "add" && Operands.size() == 5 &&
5293       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5294       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5295       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0)
5296     return true;
5297   // Register-register 'add' for thumb does not have a cc_out operand
5298   // when it's an ADD Rdm, SP, {Rdm|#imm0_255} instruction. We do
5299   // have to check the immediate range here since Thumb2 has a variant
5300   // that can handle a different range and has a cc_out operand.
5301   if (((isThumb() && Mnemonic == "add") ||
5302        (isThumbTwo() && Mnemonic == "sub")) &&
5303       Operands.size() == 6 && static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5304       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5305       static_cast<ARMOperand &>(*Operands[4]).getReg() == ARM::SP &&
5306       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5307       ((Mnemonic == "add" && static_cast<ARMOperand &>(*Operands[5]).isReg()) ||
5308        static_cast<ARMOperand &>(*Operands[5]).isImm0_1020s4()))
5309     return true;
5310   // For Thumb2, add/sub immediate does not have a cc_out operand for the
5311   // imm0_4095 variant. That's the least-preferred variant when
5312   // selecting via the generic "add" mnemonic, so to know that we
5313   // should remove the cc_out operand, we have to explicitly check that
5314   // it's not one of the other variants. Ugh.
5315   if (isThumbTwo() && (Mnemonic == "add" || Mnemonic == "sub") &&
5316       Operands.size() == 6 && static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5317       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5318       static_cast<ARMOperand &>(*Operands[5]).isImm()) {
5319     // Nest conditions rather than one big 'if' statement for readability.
5320     //
5321     // If both registers are low, we're in an IT block, and the immediate is
5322     // in range, we should use encoding T1 instead, which has a cc_out.
5323     if (inITBlock() &&
5324         isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) &&
5325         isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) &&
5326         static_cast<ARMOperand &>(*Operands[5]).isImm0_7())
5327       return false;
5328     // Check against T3. If the second register is the PC, this is an
5329     // alternate form of ADR, which uses encoding T4, so check for that too.
5330     if (static_cast<ARMOperand &>(*Operands[4]).getReg() != ARM::PC &&
5331         static_cast<ARMOperand &>(*Operands[5]).isT2SOImm())
5332       return false;
5333
5334     // Otherwise, we use encoding T4, which does not have a cc_out
5335     // operand.
5336     return true;
5337   }
5338
5339   // The thumb2 multiply instruction doesn't have a CCOut register, so
5340   // if we have a "mul" mnemonic in Thumb mode, check if we'll be able to
5341   // use the 16-bit encoding or not.
5342   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 6 &&
5343       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5344       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5345       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5346       static_cast<ARMOperand &>(*Operands[5]).isReg() &&
5347       // If the registers aren't low regs, the destination reg isn't the
5348       // same as one of the source regs, or the cc_out operand is zero
5349       // outside of an IT block, we have to use the 32-bit encoding, so
5350       // remove the cc_out operand.
5351       (!isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) ||
5352        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) ||
5353        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[5]).getReg()) ||
5354        !inITBlock() || (static_cast<ARMOperand &>(*Operands[3]).getReg() !=
5355                             static_cast<ARMOperand &>(*Operands[5]).getReg() &&
5356                         static_cast<ARMOperand &>(*Operands[3]).getReg() !=
5357                             static_cast<ARMOperand &>(*Operands[4]).getReg())))
5358     return true;
5359
5360   // Also check the 'mul' syntax variant that doesn't specify an explicit
5361   // destination register.
5362   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 5 &&
5363       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5364       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5365       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5366       // If the registers aren't low regs  or the cc_out operand is zero
5367       // outside of an IT block, we have to use the 32-bit encoding, so
5368       // remove the cc_out operand.
5369       (!isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) ||
5370        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) ||
5371        !inITBlock()))
5372     return true;
5373
5374
5375
5376   // Register-register 'add/sub' for thumb does not have a cc_out operand
5377   // when it's an ADD/SUB SP, #imm. Be lenient on count since there's also
5378   // the "add/sub SP, SP, #imm" version. If the follow-up operands aren't
5379   // right, this will result in better diagnostics (which operand is off)
5380   // anyway.
5381   if (isThumb() && (Mnemonic == "add" || Mnemonic == "sub") &&
5382       (Operands.size() == 5 || Operands.size() == 6) &&
5383       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5384       static_cast<ARMOperand &>(*Operands[3]).getReg() == ARM::SP &&
5385       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5386       (static_cast<ARMOperand &>(*Operands[4]).isImm() ||
5387        (Operands.size() == 6 &&
5388         static_cast<ARMOperand &>(*Operands[5]).isImm())))
5389     return true;
5390
5391   return false;
5392 }
5393
5394 bool ARMAsmParser::shouldOmitPredicateOperand(StringRef Mnemonic,
5395                                               OperandVector &Operands) {
5396   // VRINT{Z, R, X} have a predicate operand in VFP, but not in NEON
5397   unsigned RegIdx = 3;
5398   if ((Mnemonic == "vrintz" || Mnemonic == "vrintx" || Mnemonic == "vrintr") &&
5399       static_cast<ARMOperand &>(*Operands[2]).getToken() == ".f32") {
5400     if (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
5401         static_cast<ARMOperand &>(*Operands[3]).getToken() == ".f32")
5402       RegIdx = 4;
5403
5404     if (static_cast<ARMOperand &>(*Operands[RegIdx]).isReg() &&
5405         (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(
5406              static_cast<ARMOperand &>(*Operands[RegIdx]).getReg()) ||
5407          ARMMCRegisterClasses[ARM::QPRRegClassID].contains(
5408              static_cast<ARMOperand &>(*Operands[RegIdx]).getReg())))
5409       return true;
5410   }
5411   return false;
5412 }
5413
5414 static bool isDataTypeToken(StringRef Tok) {
5415   return Tok == ".8" || Tok == ".16" || Tok == ".32" || Tok == ".64" ||
5416     Tok == ".i8" || Tok == ".i16" || Tok == ".i32" || Tok == ".i64" ||
5417     Tok == ".u8" || Tok == ".u16" || Tok == ".u32" || Tok == ".u64" ||
5418     Tok == ".s8" || Tok == ".s16" || Tok == ".s32" || Tok == ".s64" ||
5419     Tok == ".p8" || Tok == ".p16" || Tok == ".f32" || Tok == ".f64" ||
5420     Tok == ".f" || Tok == ".d";
5421 }
5422
5423 // FIXME: This bit should probably be handled via an explicit match class
5424 // in the .td files that matches the suffix instead of having it be
5425 // a literal string token the way it is now.
5426 static bool doesIgnoreDataTypeSuffix(StringRef Mnemonic, StringRef DT) {
5427   return Mnemonic.startswith("vldm") || Mnemonic.startswith("vstm");
5428 }
5429 static void applyMnemonicAliases(StringRef &Mnemonic, uint64_t Features,
5430                                  unsigned VariantID);
5431
5432 static bool RequiresVFPRegListValidation(StringRef Inst,
5433                                          bool &AcceptSinglePrecisionOnly,
5434                                          bool &AcceptDoublePrecisionOnly) {
5435   if (Inst.size() < 7)
5436     return false;
5437
5438   if (Inst.startswith("fldm") || Inst.startswith("fstm")) {
5439     StringRef AddressingMode = Inst.substr(4, 2);
5440     if (AddressingMode == "ia" || AddressingMode == "db" ||
5441         AddressingMode == "ea" || AddressingMode == "fd") {
5442       AcceptSinglePrecisionOnly = Inst[6] == 's';
5443       AcceptDoublePrecisionOnly = Inst[6] == 'd' || Inst[6] == 'x';
5444       return true;
5445     }
5446   }
5447
5448   return false;
5449 }
5450
5451 /// Parse an arm instruction mnemonic followed by its operands.
5452 bool ARMAsmParser::ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
5453                                     SMLoc NameLoc, OperandVector &Operands) {
5454   MCAsmParser &Parser = getParser();
5455   // FIXME: Can this be done via tablegen in some fashion?
5456   bool RequireVFPRegisterListCheck;
5457   bool AcceptSinglePrecisionOnly;
5458   bool AcceptDoublePrecisionOnly;
5459   RequireVFPRegisterListCheck =
5460     RequiresVFPRegListValidation(Name, AcceptSinglePrecisionOnly,
5461                                  AcceptDoublePrecisionOnly);
5462
5463   // Apply mnemonic aliases before doing anything else, as the destination
5464   // mnemonic may include suffices and we want to handle them normally.
5465   // The generic tblgen'erated code does this later, at the start of
5466   // MatchInstructionImpl(), but that's too late for aliases that include
5467   // any sort of suffix.
5468   uint64_t AvailableFeatures = getAvailableFeatures();
5469   unsigned AssemblerDialect = getParser().getAssemblerDialect();
5470   applyMnemonicAliases(Name, AvailableFeatures, AssemblerDialect);
5471
5472   // First check for the ARM-specific .req directive.
5473   if (Parser.getTok().is(AsmToken::Identifier) &&
5474       Parser.getTok().getIdentifier() == ".req") {
5475     parseDirectiveReq(Name, NameLoc);
5476     // We always return 'error' for this, as we're done with this
5477     // statement and don't need to match the 'instruction."
5478     return true;
5479   }
5480
5481   // Create the leading tokens for the mnemonic, split by '.' characters.
5482   size_t Start = 0, Next = Name.find('.');
5483   StringRef Mnemonic = Name.slice(Start, Next);
5484
5485   // Split out the predication code and carry setting flag from the mnemonic.
5486   unsigned PredicationCode;
5487   unsigned ProcessorIMod;
5488   bool CarrySetting;
5489   StringRef ITMask;
5490   Mnemonic = splitMnemonic(Mnemonic, PredicationCode, CarrySetting,
5491                            ProcessorIMod, ITMask);
5492
5493   // In Thumb1, only the branch (B) instruction can be predicated.
5494   if (isThumbOne() && PredicationCode != ARMCC::AL && Mnemonic != "b") {
5495     Parser.eatToEndOfStatement();
5496     return Error(NameLoc, "conditional execution not supported in Thumb1");
5497   }
5498
5499   Operands.push_back(ARMOperand::CreateToken(Mnemonic, NameLoc));
5500
5501   // Handle the IT instruction ITMask. Convert it to a bitmask. This
5502   // is the mask as it will be for the IT encoding if the conditional
5503   // encoding has a '1' as it's bit0 (i.e. 't' ==> '1'). In the case
5504   // where the conditional bit0 is zero, the instruction post-processing
5505   // will adjust the mask accordingly.
5506   if (Mnemonic == "it") {
5507     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + 2);
5508     if (ITMask.size() > 3) {
5509       Parser.eatToEndOfStatement();
5510       return Error(Loc, "too many conditions on IT instruction");
5511     }
5512     unsigned Mask = 8;
5513     for (unsigned i = ITMask.size(); i != 0; --i) {
5514       char pos = ITMask[i - 1];
5515       if (pos != 't' && pos != 'e') {
5516         Parser.eatToEndOfStatement();
5517         return Error(Loc, "illegal IT block condition mask '" + ITMask + "'");
5518       }
5519       Mask >>= 1;
5520       if (ITMask[i - 1] == 't')
5521         Mask |= 8;
5522     }
5523     Operands.push_back(ARMOperand::CreateITMask(Mask, Loc));
5524   }
5525
5526   // FIXME: This is all a pretty gross hack. We should automatically handle
5527   // optional operands like this via tblgen.
5528
5529   // Next, add the CCOut and ConditionCode operands, if needed.
5530   //
5531   // For mnemonics which can ever incorporate a carry setting bit or predication
5532   // code, our matching model involves us always generating CCOut and
5533   // ConditionCode operands to match the mnemonic "as written" and then we let
5534   // the matcher deal with finding the right instruction or generating an
5535   // appropriate error.
5536   bool CanAcceptCarrySet, CanAcceptPredicationCode;
5537   getMnemonicAcceptInfo(Mnemonic, Name, CanAcceptCarrySet, CanAcceptPredicationCode);
5538
5539   // If we had a carry-set on an instruction that can't do that, issue an
5540   // error.
5541   if (!CanAcceptCarrySet && CarrySetting) {
5542     Parser.eatToEndOfStatement();
5543     return Error(NameLoc, "instruction '" + Mnemonic +
5544                  "' can not set flags, but 's' suffix specified");
5545   }
5546   // If we had a predication code on an instruction that can't do that, issue an
5547   // error.
5548   if (!CanAcceptPredicationCode && PredicationCode != ARMCC::AL) {
5549     Parser.eatToEndOfStatement();
5550     return Error(NameLoc, "instruction '" + Mnemonic +
5551                  "' is not predicable, but condition code specified");
5552   }
5553
5554   // Add the carry setting operand, if necessary.
5555   if (CanAcceptCarrySet) {
5556     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size());
5557     Operands.push_back(ARMOperand::CreateCCOut(CarrySetting ? ARM::CPSR : 0,
5558                                                Loc));
5559   }
5560
5561   // Add the predication code operand, if necessary.
5562   if (CanAcceptPredicationCode) {
5563     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size() +
5564                                       CarrySetting);
5565     Operands.push_back(ARMOperand::CreateCondCode(
5566                          ARMCC::CondCodes(PredicationCode), Loc));
5567   }
5568
5569   // Add the processor imod operand, if necessary.
5570   if (ProcessorIMod) {
5571     Operands.push_back(ARMOperand::CreateImm(
5572           MCConstantExpr::Create(ProcessorIMod, getContext()),
5573                                  NameLoc, NameLoc));
5574   } else if (Mnemonic == "cps" && isMClass()) {
5575     return Error(NameLoc, "instruction 'cps' requires effect for M-class");
5576   }
5577
5578   // Add the remaining tokens in the mnemonic.
5579   while (Next != StringRef::npos) {
5580     Start = Next;
5581     Next = Name.find('.', Start + 1);
5582     StringRef ExtraToken = Name.slice(Start, Next);
5583
5584     // Some NEON instructions have an optional datatype suffix that is
5585     // completely ignored. Check for that.
5586     if (isDataTypeToken(ExtraToken) &&
5587         doesIgnoreDataTypeSuffix(Mnemonic, ExtraToken))
5588       continue;
5589
5590     // For for ARM mode generate an error if the .n qualifier is used.
5591     if (ExtraToken == ".n" && !isThumb()) {
5592       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
5593       Parser.eatToEndOfStatement();
5594       return Error(Loc, "instruction with .n (narrow) qualifier not allowed in "
5595                    "arm mode");
5596     }
5597
5598     // The .n qualifier is always discarded as that is what the tables
5599     // and matcher expect.  In ARM mode the .w qualifier has no effect,
5600     // so discard it to avoid errors that can be caused by the matcher.
5601     if (ExtraToken != ".n" && (isThumb() || ExtraToken != ".w")) {
5602       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
5603       Operands.push_back(ARMOperand::CreateToken(ExtraToken, Loc));
5604     }
5605   }
5606
5607   // Read the remaining operands.
5608   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5609     // Read the first operand.
5610     if (parseOperand(Operands, Mnemonic)) {
5611       Parser.eatToEndOfStatement();
5612       return true;
5613     }
5614
5615     while (getLexer().is(AsmToken::Comma)) {
5616       Parser.Lex();  // Eat the comma.
5617
5618       // Parse and remember the operand.
5619       if (parseOperand(Operands, Mnemonic)) {
5620         Parser.eatToEndOfStatement();
5621         return true;
5622       }
5623     }
5624   }
5625
5626   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5627     SMLoc Loc = getLexer().getLoc();
5628     Parser.eatToEndOfStatement();
5629     return Error(Loc, "unexpected token in argument list");
5630   }
5631
5632   Parser.Lex(); // Consume the EndOfStatement
5633
5634   if (RequireVFPRegisterListCheck) {
5635     ARMOperand &Op = static_cast<ARMOperand &>(*Operands.back());
5636     if (AcceptSinglePrecisionOnly && !Op.isSPRRegList())
5637       return Error(Op.getStartLoc(),
5638                    "VFP/Neon single precision register expected");
5639     if (AcceptDoublePrecisionOnly && !Op.isDPRRegList())
5640       return Error(Op.getStartLoc(),
5641                    "VFP/Neon double precision register expected");
5642   }
5643
5644   // Some instructions, mostly Thumb, have forms for the same mnemonic that
5645   // do and don't have a cc_out optional-def operand. With some spot-checks
5646   // of the operand list, we can figure out which variant we're trying to
5647   // parse and adjust accordingly before actually matching. We shouldn't ever
5648   // try to remove a cc_out operand that was explicitly set on the the
5649   // mnemonic, of course (CarrySetting == true). Reason number #317 the
5650   // table driven matcher doesn't fit well with the ARM instruction set.
5651   if (!CarrySetting && shouldOmitCCOutOperand(Mnemonic, Operands))
5652     Operands.erase(Operands.begin() + 1);
5653
5654   // Some instructions have the same mnemonic, but don't always
5655   // have a predicate. Distinguish them here and delete the
5656   // predicate if needed.
5657   if (shouldOmitPredicateOperand(Mnemonic, Operands))
5658     Operands.erase(Operands.begin() + 1);
5659
5660   // ARM mode 'blx' need special handling, as the register operand version
5661   // is predicable, but the label operand version is not. So, we can't rely
5662   // on the Mnemonic based checking to correctly figure out when to put
5663   // a k_CondCode operand in the list. If we're trying to match the label
5664   // version, remove the k_CondCode operand here.
5665   if (!isThumb() && Mnemonic == "blx" && Operands.size() == 3 &&
5666       static_cast<ARMOperand &>(*Operands[2]).isImm())
5667     Operands.erase(Operands.begin() + 1);
5668
5669   // Adjust operands of ldrexd/strexd to MCK_GPRPair.
5670   // ldrexd/strexd require even/odd GPR pair. To enforce this constraint,
5671   // a single GPRPair reg operand is used in the .td file to replace the two
5672   // GPRs. However, when parsing from asm, the two GRPs cannot be automatically
5673   // expressed as a GPRPair, so we have to manually merge them.
5674   // FIXME: We would really like to be able to tablegen'erate this.
5675   if (!isThumb() && Operands.size() > 4 &&
5676       (Mnemonic == "ldrexd" || Mnemonic == "strexd" || Mnemonic == "ldaexd" ||
5677        Mnemonic == "stlexd")) {
5678     bool isLoad = (Mnemonic == "ldrexd" || Mnemonic == "ldaexd");
5679     unsigned Idx = isLoad ? 2 : 3;
5680     ARMOperand &Op1 = static_cast<ARMOperand &>(*Operands[Idx]);
5681     ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[Idx + 1]);
5682
5683     const MCRegisterClass& MRC = MRI->getRegClass(ARM::GPRRegClassID);
5684     // Adjust only if Op1 and Op2 are GPRs.
5685     if (Op1.isReg() && Op2.isReg() && MRC.contains(Op1.getReg()) &&
5686         MRC.contains(Op2.getReg())) {
5687       unsigned Reg1 = Op1.getReg();
5688       unsigned Reg2 = Op2.getReg();
5689       unsigned Rt = MRI->getEncodingValue(Reg1);
5690       unsigned Rt2 = MRI->getEncodingValue(Reg2);
5691
5692       // Rt2 must be Rt + 1 and Rt must be even.
5693       if (Rt + 1 != Rt2 || (Rt & 1)) {
5694         Error(Op2.getStartLoc(), isLoad
5695                                      ? "destination operands must be sequential"
5696                                      : "source operands must be sequential");
5697         return true;
5698       }
5699       unsigned NewReg = MRI->getMatchingSuperReg(Reg1, ARM::gsub_0,
5700           &(MRI->getRegClass(ARM::GPRPairRegClassID)));
5701       Operands[Idx] =
5702           ARMOperand::CreateReg(NewReg, Op1.getStartLoc(), Op2.getEndLoc());
5703       Operands.erase(Operands.begin() + Idx + 1);
5704     }
5705   }
5706
5707   // If first 2 operands of a 3 operand instruction are the same
5708   // then transform to 2 operand version of the same instruction
5709   // e.g. 'adds r0, r0, #1' transforms to 'adds r0, #1'
5710   // FIXME: We would really like to be able to tablegen'erate this.
5711   if (isThumbOne() && Operands.size() == 6 &&
5712        (Mnemonic == "add" || Mnemonic == "sub" || Mnemonic == "and" ||
5713         Mnemonic == "eor" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
5714         Mnemonic == "asr" || Mnemonic == "adc" || Mnemonic == "sbc" ||
5715         Mnemonic == "ror" || Mnemonic == "orr" || Mnemonic == "bic")) {
5716       ARMOperand &Op3 = static_cast<ARMOperand &>(*Operands[3]);
5717       ARMOperand &Op4 = static_cast<ARMOperand &>(*Operands[4]);
5718       ARMOperand &Op5 = static_cast<ARMOperand &>(*Operands[5]);
5719
5720       // If both registers are the same then remove one of them from
5721       // the operand list.
5722       if (Op3.isReg() && Op4.isReg() && Op3.getReg() == Op4.getReg()) {
5723           // If 3rd operand (variable Op5) is a register and the instruction is adds/sub
5724           // then do not transform as the backend already handles this instruction
5725           // correctly.
5726           if (!Op5.isReg() || !((Mnemonic == "add" && CarrySetting) || Mnemonic == "sub")) {
5727               Operands.erase(Operands.begin() + 3);
5728               if (Mnemonic == "add" && !CarrySetting) {
5729                   // Special case for 'add' (not 'adds') instruction must
5730                   // remove the CCOut operand as well.
5731                   Operands.erase(Operands.begin() + 1);
5732               }
5733           }
5734       }
5735   }
5736
5737   // If instruction is 'add' and first two register operands
5738   // use SP register, then remove one of the SP registers from
5739   // the instruction.
5740   // FIXME: We would really like to be able to tablegen'erate this.
5741   if (isThumbOne() && Operands.size() == 5 && Mnemonic == "add" && !CarrySetting) {
5742       ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[2]);
5743       ARMOperand &Op3 = static_cast<ARMOperand &>(*Operands[3]);
5744       if (Op2.isReg() && Op3.isReg() && Op2.getReg() == ARM::SP && Op3.getReg() == ARM::SP) {
5745           Operands.erase(Operands.begin() + 2);
5746       }
5747   }
5748
5749   // GNU Assembler extension (compatibility)
5750   if ((Mnemonic == "ldrd" || Mnemonic == "strd")) {
5751     ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[2]);
5752     ARMOperand &Op3 = static_cast<ARMOperand &>(*Operands[3]);
5753     if (Op3.isMem()) {
5754       assert(Op2.isReg() && "expected register argument");
5755
5756       unsigned SuperReg = MRI->getMatchingSuperReg(
5757           Op2.getReg(), ARM::gsub_0, &MRI->getRegClass(ARM::GPRPairRegClassID));
5758
5759       assert(SuperReg && "expected register pair");
5760
5761       unsigned PairedReg = MRI->getSubReg(SuperReg, ARM::gsub_1);
5762
5763       Operands.insert(
5764           Operands.begin() + 3,
5765           ARMOperand::CreateReg(PairedReg, Op2.getStartLoc(), Op2.getEndLoc()));
5766     }
5767   }
5768
5769   // FIXME: As said above, this is all a pretty gross hack.  This instruction
5770   // does not fit with other "subs" and tblgen.
5771   // Adjust operands of B9.3.19 SUBS PC, LR, #imm (Thumb2) system instruction
5772   // so the Mnemonic is the original name "subs" and delete the predicate
5773   // operand so it will match the table entry.
5774   if (isThumbTwo() && Mnemonic == "sub" && Operands.size() == 6 &&
5775       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5776       static_cast<ARMOperand &>(*Operands[3]).getReg() == ARM::PC &&
5777       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5778       static_cast<ARMOperand &>(*Operands[4]).getReg() == ARM::LR &&
5779       static_cast<ARMOperand &>(*Operands[5]).isImm()) {
5780     Operands.front() = ARMOperand::CreateToken(Name, NameLoc);
5781     Operands.erase(Operands.begin() + 1);
5782   }
5783   return false;
5784 }
5785
5786 // Validate context-sensitive operand constraints.
5787
5788 // return 'true' if register list contains non-low GPR registers,
5789 // 'false' otherwise. If Reg is in the register list or is HiReg, set
5790 // 'containsReg' to true.
5791 static bool checkLowRegisterList(MCInst Inst, unsigned OpNo, unsigned Reg,
5792                                  unsigned HiReg, bool &containsReg) {
5793   containsReg = false;
5794   for (unsigned i = OpNo; i < Inst.getNumOperands(); ++i) {
5795     unsigned OpReg = Inst.getOperand(i).getReg();
5796     if (OpReg == Reg)
5797       containsReg = true;
5798     // Anything other than a low register isn't legal here.
5799     if (!isARMLowRegister(OpReg) && (!HiReg || OpReg != HiReg))
5800       return true;
5801   }
5802   return false;
5803 }
5804
5805 // Check if the specified regisgter is in the register list of the inst,
5806 // starting at the indicated operand number.
5807 static bool listContainsReg(MCInst &Inst, unsigned OpNo, unsigned Reg) {
5808   for (unsigned i = OpNo; i < Inst.getNumOperands(); ++i) {
5809     unsigned OpReg = Inst.getOperand(i).getReg();
5810     if (OpReg == Reg)
5811       return true;
5812   }
5813   return false;
5814 }
5815
5816 // Return true if instruction has the interesting property of being
5817 // allowed in IT blocks, but not being predicable.
5818 static bool instIsBreakpoint(const MCInst &Inst) {
5819     return Inst.getOpcode() == ARM::tBKPT ||
5820            Inst.getOpcode() == ARM::BKPT ||
5821            Inst.getOpcode() == ARM::tHLT ||
5822            Inst.getOpcode() == ARM::HLT;
5823
5824 }
5825
5826 // FIXME: We would really like to be able to tablegen'erate this.
5827 bool ARMAsmParser::validateInstruction(MCInst &Inst,
5828                                        const OperandVector &Operands) {
5829   const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
5830   SMLoc Loc = Operands[0]->getStartLoc();
5831
5832   // Check the IT block state first.
5833   // NOTE: BKPT and HLT instructions have the interesting property of being
5834   // allowed in IT blocks, but not being predicable. They just always execute.
5835   if (inITBlock() && !instIsBreakpoint(Inst)) {
5836     unsigned Bit = 1;
5837     if (ITState.FirstCond)
5838       ITState.FirstCond = false;
5839     else
5840       Bit = (ITState.Mask >> (5 - ITState.CurPosition)) & 1;
5841     // The instruction must be predicable.
5842     if (!MCID.isPredicable())
5843       return Error(Loc, "instructions in IT block must be predicable");
5844     unsigned Cond = Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm();
5845     unsigned ITCond = Bit ? ITState.Cond :
5846       ARMCC::getOppositeCondition(ITState.Cond);
5847     if (Cond != ITCond) {
5848       // Find the condition code Operand to get its SMLoc information.
5849       SMLoc CondLoc;
5850       for (unsigned I = 1; I < Operands.size(); ++I)
5851         if (static_cast<ARMOperand &>(*Operands[I]).isCondCode())
5852           CondLoc = Operands[I]->getStartLoc();
5853       return Error(CondLoc, "incorrect condition in IT block; got '" +
5854                    StringRef(ARMCondCodeToString(ARMCC::CondCodes(Cond))) +
5855                    "', but expected '" +
5856                    ARMCondCodeToString(ARMCC::CondCodes(ITCond)) + "'");
5857     }
5858   // Check for non-'al' condition codes outside of the IT block.
5859   } else if (isThumbTwo() && MCID.isPredicable() &&
5860              Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm() !=
5861              ARMCC::AL && Inst.getOpcode() != ARM::tBcc &&
5862              Inst.getOpcode() != ARM::t2Bcc)
5863     return Error(Loc, "predicated instructions must be in IT block");
5864
5865   const unsigned Opcode = Inst.getOpcode();
5866   switch (Opcode) {
5867   case ARM::LDRD:
5868   case ARM::LDRD_PRE:
5869   case ARM::LDRD_POST: {
5870     const unsigned RtReg = Inst.getOperand(0).getReg();
5871
5872     // Rt can't be R14.
5873     if (RtReg == ARM::LR)
5874       return Error(Operands[3]->getStartLoc(),
5875                    "Rt can't be R14");
5876
5877     const unsigned Rt = MRI->getEncodingValue(RtReg);
5878     // Rt must be even-numbered.
5879     if ((Rt & 1) == 1)
5880       return Error(Operands[3]->getStartLoc(),
5881                    "Rt must be even-numbered");
5882
5883     // Rt2 must be Rt + 1.
5884     const unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
5885     if (Rt2 != Rt + 1)
5886       return Error(Operands[3]->getStartLoc(),
5887                    "destination operands must be sequential");
5888
5889     if (Opcode == ARM::LDRD_PRE || Opcode == ARM::LDRD_POST) {
5890       const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(3).getReg());
5891       // For addressing modes with writeback, the base register needs to be
5892       // different from the destination registers.
5893       if (Rn == Rt || Rn == Rt2)
5894         return Error(Operands[3]->getStartLoc(),
5895                      "base register needs to be different from destination "
5896                      "registers");
5897     }
5898
5899     return false;
5900   }
5901   case ARM::t2LDRDi8:
5902   case ARM::t2LDRD_PRE:
5903   case ARM::t2LDRD_POST: {
5904     // Rt2 must be different from Rt.
5905     unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
5906     unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
5907     if (Rt2 == Rt)
5908       return Error(Operands[3]->getStartLoc(),
5909                    "destination operands can't be identical");
5910     return false;
5911   }
5912   case ARM::STRD: {
5913     // Rt2 must be Rt + 1.
5914     unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
5915     unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
5916     if (Rt2 != Rt + 1)
5917       return Error(Operands[3]->getStartLoc(),
5918                    "source operands must be sequential");
5919     return false;
5920   }
5921   case ARM::STRD_PRE:
5922   case ARM::STRD_POST: {
5923     // Rt2 must be Rt + 1.
5924     unsigned Rt = MRI->getEncodingValue(Inst.getOperand(1).getReg());
5925     unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(2).getReg());
5926     if (Rt2 != Rt + 1)
5927       return Error(Operands[3]->getStartLoc(),
5928                    "source operands must be sequential");
5929     return false;
5930   }
5931   case ARM::STR_PRE_IMM:
5932   case ARM::STR_PRE_REG:
5933   case ARM::STR_POST_IMM:
5934   case ARM::STR_POST_REG:
5935   case ARM::STRH_PRE:
5936   case ARM::STRH_POST:
5937   case ARM::STRB_PRE_IMM:
5938   case ARM::STRB_PRE_REG:
5939   case ARM::STRB_POST_IMM:
5940   case ARM::STRB_POST_REG: {
5941     // Rt must be different from Rn.
5942     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(1).getReg());
5943     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(2).getReg());
5944
5945     if (Rt == Rn)
5946       return Error(Operands[3]->getStartLoc(),
5947                    "source register and base register can't be identical");
5948     return false;
5949   }
5950   case ARM::LDR_PRE_IMM:
5951   case ARM::LDR_PRE_REG:
5952   case ARM::LDR_POST_IMM:
5953   case ARM::LDR_POST_REG:
5954   case ARM::LDRH_PRE:
5955   case ARM::LDRH_POST:
5956   case ARM::LDRSH_PRE:
5957   case ARM::LDRSH_POST:
5958   case ARM::LDRB_PRE_IMM:
5959   case ARM::LDRB_PRE_REG:
5960   case ARM::LDRB_POST_IMM:
5961   case ARM::LDRB_POST_REG:
5962   case ARM::LDRSB_PRE:
5963   case ARM::LDRSB_POST: {
5964     // Rt must be different from Rn.
5965     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
5966     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(2).getReg());
5967
5968     if (Rt == Rn)
5969       return Error(Operands[3]->getStartLoc(),
5970                    "destination register and base register can't be identical");
5971     return false;
5972   }
5973   case ARM::SBFX:
5974   case ARM::UBFX: {
5975     // Width must be in range [1, 32-lsb].
5976     unsigned LSB = Inst.getOperand(2).getImm();
5977     unsigned Widthm1 = Inst.getOperand(3).getImm();
5978     if (Widthm1 >= 32 - LSB)
5979       return Error(Operands[5]->getStartLoc(),
5980                    "bitfield width must be in range [1,32-lsb]");
5981     return false;
5982   }
5983   // Notionally handles ARM::tLDMIA_UPD too.
5984   case ARM::tLDMIA: {
5985     // If we're parsing Thumb2, the .w variant is available and handles
5986     // most cases that are normally illegal for a Thumb1 LDM instruction.
5987     // We'll make the transformation in processInstruction() if necessary.
5988     //
5989     // Thumb LDM instructions are writeback iff the base register is not
5990     // in the register list.
5991     unsigned Rn = Inst.getOperand(0).getReg();
5992     bool HasWritebackToken =
5993         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
5994          static_cast<ARMOperand &>(*Operands[3]).getToken() == "!");
5995     bool ListContainsBase;
5996     if (checkLowRegisterList(Inst, 3, Rn, 0, ListContainsBase) && !isThumbTwo())
5997       return Error(Operands[3 + HasWritebackToken]->getStartLoc(),
5998                    "registers must be in range r0-r7");
5999     // If we should have writeback, then there should be a '!' token.
6000     if (!ListContainsBase && !HasWritebackToken && !isThumbTwo())
6001       return Error(Operands[2]->getStartLoc(),
6002                    "writeback operator '!' expected");
6003     // If we should not have writeback, there must not be a '!'. This is
6004     // true even for the 32-bit wide encodings.
6005     if (ListContainsBase && HasWritebackToken)
6006       return Error(Operands[3]->getStartLoc(),
6007                    "writeback operator '!' not allowed when base register "
6008                    "in register list");
6009     if (listContainsReg(Inst, 3 + HasWritebackToken, ARM::SP))
6010       return Error(Operands[3 + HasWritebackToken]->getStartLoc(),
6011                    "SP not allowed in register list");
6012     break;
6013   }
6014   case ARM::LDMIA_UPD:
6015   case ARM::LDMDB_UPD:
6016   case ARM::LDMIB_UPD:
6017   case ARM::LDMDA_UPD:
6018     // ARM variants loading and updating the same register are only officially
6019     // UNPREDICTABLE on v7 upwards. Goodness knows what they did before.
6020     if (!hasV7Ops())
6021       break;
6022     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
6023       return Error(Operands.back()->getStartLoc(),
6024                    "writeback register not allowed in register list");
6025     break;
6026   case ARM::t2LDMIA:
6027   case ARM::t2LDMDB:
6028   case ARM::t2STMIA:
6029   case ARM::t2STMDB: {
6030     if (listContainsReg(Inst, 3, ARM::SP))
6031       return Error(Operands.back()->getStartLoc(),
6032                    "SP not allowed in register list");
6033     break;
6034   }
6035   case ARM::t2LDMIA_UPD:
6036   case ARM::t2LDMDB_UPD:
6037   case ARM::t2STMIA_UPD:
6038   case ARM::t2STMDB_UPD: {
6039     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
6040       return Error(Operands.back()->getStartLoc(),
6041                    "writeback register not allowed in register list");
6042
6043     if (listContainsReg(Inst, 4, ARM::SP))
6044       return Error(Operands.back()->getStartLoc(),
6045                    "SP not allowed in register list");
6046     break;
6047   }
6048   case ARM::sysLDMIA_UPD:
6049   case ARM::sysLDMDA_UPD:
6050   case ARM::sysLDMDB_UPD:
6051   case ARM::sysLDMIB_UPD:
6052     if (!listContainsReg(Inst, 3, ARM::PC))
6053       return Error(Operands[4]->getStartLoc(),
6054                    "writeback register only allowed on system LDM "
6055                    "if PC in register-list");
6056     break;
6057   case ARM::sysSTMIA_UPD:
6058   case ARM::sysSTMDA_UPD:
6059   case ARM::sysSTMDB_UPD:
6060   case ARM::sysSTMIB_UPD:
6061     return Error(Operands[2]->getStartLoc(),
6062                  "system STM cannot have writeback register");
6063   case ARM::tMUL: {
6064     // The second source operand must be the same register as the destination
6065     // operand.
6066     //
6067     // In this case, we must directly check the parsed operands because the
6068     // cvtThumbMultiply() function is written in such a way that it guarantees
6069     // this first statement is always true for the new Inst.  Essentially, the
6070     // destination is unconditionally copied into the second source operand
6071     // without checking to see if it matches what we actually parsed.
6072     if (Operands.size() == 6 && (((ARMOperand &)*Operands[3]).getReg() !=
6073                                  ((ARMOperand &)*Operands[5]).getReg()) &&
6074         (((ARMOperand &)*Operands[3]).getReg() !=
6075          ((ARMOperand &)*Operands[4]).getReg())) {
6076       return Error(Operands[3]->getStartLoc(),
6077                    "destination register must match source register");
6078     }
6079     break;
6080   }
6081   // Like for ldm/stm, push and pop have hi-reg handling version in Thumb2,
6082   // so only issue a diagnostic for thumb1. The instructions will be
6083   // switched to the t2 encodings in processInstruction() if necessary.
6084   case ARM::tPOP: {
6085     bool ListContainsBase;
6086     if (checkLowRegisterList(Inst, 2, 0, ARM::PC, ListContainsBase) &&
6087         !isThumbTwo())
6088       return Error(Operands[2]->getStartLoc(),
6089                    "registers must be in range r0-r7 or pc");
6090     break;
6091   }
6092   case ARM::tPUSH: {
6093     bool ListContainsBase;
6094     if (checkLowRegisterList(Inst, 2, 0, ARM::LR, ListContainsBase) &&
6095         !isThumbTwo())
6096       return Error(Operands[2]->getStartLoc(),
6097                    "registers must be in range r0-r7 or lr");
6098     break;
6099   }
6100   case ARM::tSTMIA_UPD: {
6101     bool ListContainsBase, InvalidLowList;
6102     InvalidLowList = checkLowRegisterList(Inst, 4, Inst.getOperand(0).getReg(),
6103                                           0, ListContainsBase);
6104     if (InvalidLowList && !isThumbTwo())
6105       return Error(Operands[4]->getStartLoc(),
6106                    "registers must be in range r0-r7");
6107
6108     // This would be converted to a 32-bit stm, but that's not valid if the
6109     // writeback register is in the list.
6110     if (InvalidLowList && ListContainsBase)
6111       return Error(Operands[4]->getStartLoc(),
6112                    "writeback operator '!' not allowed when base register "
6113                    "in register list");
6114     if (listContainsReg(Inst, 4, ARM::SP) && !inITBlock())
6115       return Error(Operands.back()->getStartLoc(),
6116                    "SP not allowed in register list");
6117     break;
6118   }
6119   case ARM::tADDrSP: {
6120     // If the non-SP source operand and the destination operand are not the
6121     // same, we need thumb2 (for the wide encoding), or we have an error.
6122     if (!isThumbTwo() &&
6123         Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg()) {
6124       return Error(Operands[4]->getStartLoc(),
6125                    "source register must be the same as destination");
6126     }
6127     break;
6128   }
6129   // Final range checking for Thumb unconditional branch instructions.
6130   case ARM::tB:
6131     if (!(static_cast<ARMOperand &>(*Operands[2])).isSignedOffset<11, 1>())
6132       return Error(Operands[2]->getStartLoc(), "branch target out of range");
6133     break;
6134   case ARM::t2B: {
6135     int op = (Operands[2]->isImm()) ? 2 : 3;
6136     if (!static_cast<ARMOperand &>(*Operands[op]).isSignedOffset<24, 1>())
6137       return Error(Operands[op]->getStartLoc(), "branch target out of range");
6138     break;
6139   }
6140   // Final range checking for Thumb conditional branch instructions.
6141   case ARM::tBcc:
6142     if (!static_cast<ARMOperand &>(*Operands[2]).isSignedOffset<8, 1>())
6143       return Error(Operands[2]->getStartLoc(), "branch target out of range");
6144     break;
6145   case ARM::t2Bcc: {
6146     int Op = (Operands[2]->isImm()) ? 2 : 3;
6147     if (!static_cast<ARMOperand &>(*Operands[Op]).isSignedOffset<20, 1>())
6148       return Error(Operands[Op]->getStartLoc(), "branch target out of range");
6149     break;
6150   }
6151   case ARM::MOVi16:
6152   case ARM::t2MOVi16:
6153   case ARM::t2MOVTi16:
6154     {
6155     // We want to avoid misleadingly allowing something like "mov r0, <symbol>"
6156     // especially when we turn it into a movw and the expression <symbol> does
6157     // not have a :lower16: or :upper16 as part of the expression.  We don't
6158     // want the behavior of silently truncating, which can be unexpected and
6159     // lead to bugs that are difficult to find since this is an easy mistake
6160     // to make.
6161     int i = (Operands[3]->isImm()) ? 3 : 4;
6162     ARMOperand &Op = static_cast<ARMOperand &>(*Operands[i]);
6163     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm());
6164     if (CE) break;
6165     const MCExpr *E = dyn_cast<MCExpr>(Op.getImm());
6166     if (!E) break;
6167     const ARMMCExpr *ARM16Expr = dyn_cast<ARMMCExpr>(E);
6168     if (!ARM16Expr || (ARM16Expr->getKind() != ARMMCExpr::VK_ARM_HI16 &&
6169                        ARM16Expr->getKind() != ARMMCExpr::VK_ARM_LO16))
6170       return Error(
6171           Op.getStartLoc(),
6172           "immediate expression for mov requires :lower16: or :upper16");
6173     break;
6174   }
6175   }
6176
6177   return false;
6178 }
6179
6180 static unsigned getRealVSTOpcode(unsigned Opc, unsigned &Spacing) {
6181   switch(Opc) {
6182   default: llvm_unreachable("unexpected opcode!");
6183   // VST1LN
6184   case ARM::VST1LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST1LNd8_UPD;
6185   case ARM::VST1LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST1LNd16_UPD;
6186   case ARM::VST1LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST1LNd32_UPD;
6187   case ARM::VST1LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST1LNd8_UPD;
6188   case ARM::VST1LNdWB_register_Asm_16: Spacing = 1; return ARM::VST1LNd16_UPD;
6189   case ARM::VST1LNdWB_register_Asm_32: Spacing = 1; return ARM::VST1LNd32_UPD;
6190   case ARM::VST1LNdAsm_8:  Spacing = 1; return ARM::VST1LNd8;
6191   case ARM::VST1LNdAsm_16: Spacing = 1; return ARM::VST1LNd16;
6192   case ARM::VST1LNdAsm_32: Spacing = 1; return ARM::VST1LNd32;
6193
6194   // VST2LN
6195   case ARM::VST2LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST2LNd8_UPD;
6196   case ARM::VST2LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST2LNd16_UPD;
6197   case ARM::VST2LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST2LNd32_UPD;
6198   case ARM::VST2LNqWB_fixed_Asm_16: Spacing = 2; return ARM::VST2LNq16_UPD;
6199   case ARM::VST2LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST2LNq32_UPD;
6200
6201   case ARM::VST2LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST2LNd8_UPD;
6202   case ARM::VST2LNdWB_register_Asm_16: Spacing = 1; return ARM::VST2LNd16_UPD;
6203   case ARM::VST2LNdWB_register_Asm_32: Spacing = 1; return ARM::VST2LNd32_UPD;
6204   case ARM::VST2LNqWB_register_Asm_16: Spacing = 2; return ARM::VST2LNq16_UPD;
6205   case ARM::VST2LNqWB_register_Asm_32: Spacing = 2; return ARM::VST2LNq32_UPD;
6206
6207   case ARM::VST2LNdAsm_8:  Spacing = 1; return ARM::VST2LNd8;
6208   case ARM::VST2LNdAsm_16: Spacing = 1; return ARM::VST2LNd16;
6209   case ARM::VST2LNdAsm_32: Spacing = 1; return ARM::VST2LNd32;
6210   case ARM::VST2LNqAsm_16: Spacing = 2; return ARM::VST2LNq16;
6211   case ARM::VST2LNqAsm_32: Spacing = 2; return ARM::VST2LNq32;
6212
6213   // VST3LN
6214   case ARM::VST3LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST3LNd8_UPD;
6215   case ARM::VST3LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST3LNd16_UPD;
6216   case ARM::VST3LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST3LNd32_UPD;
6217   case ARM::VST3LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VST3LNq16_UPD;
6218   case ARM::VST3LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST3LNq32_UPD;
6219   case ARM::VST3LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST3LNd8_UPD;
6220   case ARM::VST3LNdWB_register_Asm_16: Spacing = 1; return ARM::VST3LNd16_UPD;
6221   case ARM::VST3LNdWB_register_Asm_32: Spacing = 1; return ARM::VST3LNd32_UPD;
6222   case ARM::VST3LNqWB_register_Asm_16: Spacing = 2; return ARM::VST3LNq16_UPD;
6223   case ARM::VST3LNqWB_register_Asm_32: Spacing = 2; return ARM::VST3LNq32_UPD;
6224   case ARM::VST3LNdAsm_8:  Spacing = 1; return ARM::VST3LNd8;
6225   case ARM::VST3LNdAsm_16: Spacing = 1; return ARM::VST3LNd16;
6226   case ARM::VST3LNdAsm_32: Spacing = 1; return ARM::VST3LNd32;
6227   case ARM::VST3LNqAsm_16: Spacing = 2; return ARM::VST3LNq16;
6228   case ARM::VST3LNqAsm_32: Spacing = 2; return ARM::VST3LNq32;
6229
6230   // VST3
6231   case ARM::VST3dWB_fixed_Asm_8:  Spacing = 1; return ARM::VST3d8_UPD;
6232   case ARM::VST3dWB_fixed_Asm_16: Spacing = 1; return ARM::VST3d16_UPD;
6233   case ARM::VST3dWB_fixed_Asm_32: Spacing = 1; return ARM::VST3d32_UPD;
6234   case ARM::VST3qWB_fixed_Asm_8:  Spacing = 2; return ARM::VST3q8_UPD;
6235   case ARM::VST3qWB_fixed_Asm_16: Spacing = 2; return ARM::VST3q16_UPD;
6236   case ARM::VST3qWB_fixed_Asm_32: Spacing = 2; return ARM::VST3q32_UPD;
6237   case ARM::VST3dWB_register_Asm_8:  Spacing = 1; return ARM::VST3d8_UPD;
6238   case ARM::VST3dWB_register_Asm_16: Spacing = 1; return ARM::VST3d16_UPD;
6239   case ARM::VST3dWB_register_Asm_32: Spacing = 1; return ARM::VST3d32_UPD;
6240   case ARM::VST3qWB_register_Asm_8:  Spacing = 2; return ARM::VST3q8_UPD;
6241   case ARM::VST3qWB_register_Asm_16: Spacing = 2; return ARM::VST3q16_UPD;
6242   case ARM::VST3qWB_register_Asm_32: Spacing = 2; return ARM::VST3q32_UPD;
6243   case ARM::VST3dAsm_8:  Spacing = 1; return ARM::VST3d8;
6244   case ARM::VST3dAsm_16: Spacing = 1; return ARM::VST3d16;
6245   case ARM::VST3dAsm_32: Spacing = 1; return ARM::VST3d32;
6246   case ARM::VST3qAsm_8:  Spacing = 2; return ARM::VST3q8;
6247   case ARM::VST3qAsm_16: Spacing = 2; return ARM::VST3q16;
6248   case ARM::VST3qAsm_32: Spacing = 2; return ARM::VST3q32;
6249
6250   // VST4LN
6251   case ARM::VST4LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST4LNd8_UPD;
6252   case ARM::VST4LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST4LNd16_UPD;
6253   case ARM::VST4LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST4LNd32_UPD;
6254   case ARM::VST4LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VST4LNq16_UPD;
6255   case ARM::VST4LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST4LNq32_UPD;
6256   case ARM::VST4LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST4LNd8_UPD;
6257   case ARM::VST4LNdWB_register_Asm_16: Spacing = 1; return ARM::VST4LNd16_UPD;
6258   case ARM::VST4LNdWB_register_Asm_32: Spacing = 1; return ARM::VST4LNd32_UPD;
6259   case ARM::VST4LNqWB_register_Asm_16: Spacing = 2; return ARM::VST4LNq16_UPD;
6260   case ARM::VST4LNqWB_register_Asm_32: Spacing = 2; return ARM::VST4LNq32_UPD;
6261   case ARM::VST4LNdAsm_8:  Spacing = 1; return ARM::VST4LNd8;
6262   case ARM::VST4LNdAsm_16: Spacing = 1; return ARM::VST4LNd16;
6263   case ARM::VST4LNdAsm_32: Spacing = 1; return ARM::VST4LNd32;
6264   case ARM::VST4LNqAsm_16: Spacing = 2; return ARM::VST4LNq16;
6265   case ARM::VST4LNqAsm_32: Spacing = 2; return ARM::VST4LNq32;
6266
6267   // VST4
6268   case ARM::VST4dWB_fixed_Asm_8:  Spacing = 1; return ARM::VST4d8_UPD;
6269   case ARM::VST4dWB_fixed_Asm_16: Spacing = 1; return ARM::VST4d16_UPD;
6270   case ARM::VST4dWB_fixed_Asm_32: Spacing = 1; return ARM::VST4d32_UPD;
6271   case ARM::VST4qWB_fixed_Asm_8:  Spacing = 2; return ARM::VST4q8_UPD;
6272   case ARM::VST4qWB_fixed_Asm_16: Spacing = 2; return ARM::VST4q16_UPD;
6273   case ARM::VST4qWB_fixed_Asm_32: Spacing = 2; return ARM::VST4q32_UPD;
6274   case ARM::VST4dWB_register_Asm_8:  Spacing = 1; return ARM::VST4d8_UPD;
6275   case ARM::VST4dWB_register_Asm_16: Spacing = 1; return ARM::VST4d16_UPD;
6276   case ARM::VST4dWB_register_Asm_32: Spacing = 1; return ARM::VST4d32_UPD;
6277   case ARM::VST4qWB_register_Asm_8:  Spacing = 2; return ARM::VST4q8_UPD;
6278   case ARM::VST4qWB_register_Asm_16: Spacing = 2; return ARM::VST4q16_UPD;
6279   case ARM::VST4qWB_register_Asm_32: Spacing = 2; return ARM::VST4q32_UPD;
6280   case ARM::VST4dAsm_8:  Spacing = 1; return ARM::VST4d8;
6281   case ARM::VST4dAsm_16: Spacing = 1; return ARM::VST4d16;
6282   case ARM::VST4dAsm_32: Spacing = 1; return ARM::VST4d32;
6283   case ARM::VST4qAsm_8:  Spacing = 2; return ARM::VST4q8;
6284   case ARM::VST4qAsm_16: Spacing = 2; return ARM::VST4q16;
6285   case ARM::VST4qAsm_32: Spacing = 2; return ARM::VST4q32;
6286   }
6287 }
6288
6289 static unsigned getRealVLDOpcode(unsigned Opc, unsigned &Spacing) {
6290   switch(Opc) {
6291   default: llvm_unreachable("unexpected opcode!");
6292   // VLD1LN
6293   case ARM::VLD1LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD1LNd8_UPD;
6294   case ARM::VLD1LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD1LNd16_UPD;
6295   case ARM::VLD1LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD1LNd32_UPD;
6296   case ARM::VLD1LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD1LNd8_UPD;
6297   case ARM::VLD1LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD1LNd16_UPD;
6298   case ARM::VLD1LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD1LNd32_UPD;
6299   case ARM::VLD1LNdAsm_8:  Spacing = 1; return ARM::VLD1LNd8;
6300   case ARM::VLD1LNdAsm_16: Spacing = 1; return ARM::VLD1LNd16;
6301   case ARM::VLD1LNdAsm_32: Spacing = 1; return ARM::VLD1LNd32;
6302
6303   // VLD2LN
6304   case ARM::VLD2LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD2LNd8_UPD;
6305   case ARM::VLD2LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD2LNd16_UPD;
6306   case ARM::VLD2LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD2LNd32_UPD;
6307   case ARM::VLD2LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD2LNq16_UPD;
6308   case ARM::VLD2LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD2LNq32_UPD;
6309   case ARM::VLD2LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD2LNd8_UPD;
6310   case ARM::VLD2LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD2LNd16_UPD;
6311   case ARM::VLD2LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD2LNd32_UPD;
6312   case ARM::VLD2LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD2LNq16_UPD;
6313   case ARM::VLD2LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD2LNq32_UPD;
6314   case ARM::VLD2LNdAsm_8:  Spacing = 1; return ARM::VLD2LNd8;
6315   case ARM::VLD2LNdAsm_16: Spacing = 1; return ARM::VLD2LNd16;
6316   case ARM::VLD2LNdAsm_32: Spacing = 1; return ARM::VLD2LNd32;
6317   case ARM::VLD2LNqAsm_16: Spacing = 2; return ARM::VLD2LNq16;
6318   case ARM::VLD2LNqAsm_32: Spacing = 2; return ARM::VLD2LNq32;
6319
6320   // VLD3DUP
6321   case ARM::VLD3DUPdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3DUPd8_UPD;
6322   case ARM::VLD3DUPdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3DUPd16_UPD;
6323   case ARM::VLD3DUPdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3DUPd32_UPD;
6324   case ARM::VLD3DUPqWB_fixed_Asm_8: Spacing = 1; return ARM::VLD3DUPq8_UPD;
6325   case ARM::VLD3DUPqWB_fixed_Asm_16: Spacing = 2; return ARM::VLD3DUPq16_UPD;
6326   case ARM::VLD3DUPqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3DUPq32_UPD;
6327   case ARM::VLD3DUPdWB_register_Asm_8:  Spacing = 1; return ARM::VLD3DUPd8_UPD;
6328   case ARM::VLD3DUPdWB_register_Asm_16: Spacing = 1; return ARM::VLD3DUPd16_UPD;
6329   case ARM::VLD3DUPdWB_register_Asm_32: Spacing = 1; return ARM::VLD3DUPd32_UPD;
6330   case ARM::VLD3DUPqWB_register_Asm_8: Spacing = 2; return ARM::VLD3DUPq8_UPD;
6331   case ARM::VLD3DUPqWB_register_Asm_16: Spacing = 2; return ARM::VLD3DUPq16_UPD;
6332   case ARM::VLD3DUPqWB_register_Asm_32: Spacing = 2; return ARM::VLD3DUPq32_UPD;
6333   case ARM::VLD3DUPdAsm_8:  Spacing = 1; return ARM::VLD3DUPd8;
6334   case ARM::VLD3DUPdAsm_16: Spacing = 1; return ARM::VLD3DUPd16;
6335   case ARM::VLD3DUPdAsm_32: Spacing = 1; return ARM::VLD3DUPd32;
6336   case ARM::VLD3DUPqAsm_8: Spacing = 2; return ARM::VLD3DUPq8;
6337   case ARM::VLD3DUPqAsm_16: Spacing = 2; return ARM::VLD3DUPq16;
6338   case ARM::VLD3DUPqAsm_32: Spacing = 2; return ARM::VLD3DUPq32;
6339
6340   // VLD3LN
6341   case ARM::VLD3LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3LNd8_UPD;
6342   case ARM::VLD3LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3LNd16_UPD;
6343   case ARM::VLD3LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3LNd32_UPD;
6344   case ARM::VLD3LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3LNq16_UPD;
6345   case ARM::VLD3LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3LNq32_UPD;
6346   case ARM::VLD3LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD3LNd8_UPD;
6347   case ARM::VLD3LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD3LNd16_UPD;
6348   case ARM::VLD3LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD3LNd32_UPD;
6349   case ARM::VLD3LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD3LNq16_UPD;
6350   case ARM::VLD3LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD3LNq32_UPD;
6351   case ARM::VLD3LNdAsm_8:  Spacing = 1; return ARM::VLD3LNd8;
6352   case ARM::VLD3LNdAsm_16: Spacing = 1; return ARM::VLD3LNd16;
6353   case ARM::VLD3LNdAsm_32: Spacing = 1; return ARM::VLD3LNd32;
6354   case ARM::VLD3LNqAsm_16: Spacing = 2; return ARM::VLD3LNq16;
6355   case ARM::VLD3LNqAsm_32: Spacing = 2; return ARM::VLD3LNq32;
6356
6357   // VLD3
6358   case ARM::VLD3dWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3d8_UPD;
6359   case ARM::VLD3dWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3d16_UPD;
6360   case ARM::VLD3dWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3d32_UPD;
6361   case ARM::VLD3qWB_fixed_Asm_8:  Spacing = 2; return ARM::VLD3q8_UPD;
6362   case ARM::VLD3qWB_fixed_Asm_16: Spacing = 2; return ARM::VLD3q16_UPD;
6363   case ARM::VLD3qWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3q32_UPD;
6364   case ARM::VLD3dWB_register_Asm_8:  Spacing = 1; return ARM::VLD3d8_UPD;
6365   case ARM::VLD3dWB_register_Asm_16: Spacing = 1; return ARM::VLD3d16_UPD;
6366   case ARM::VLD3dWB_register_Asm_32: Spacing = 1; return ARM::VLD3d32_UPD;
6367   case ARM::VLD3qWB_register_Asm_8:  Spacing = 2; return ARM::VLD3q8_UPD;
6368   case ARM::VLD3qWB_register_Asm_16: Spacing = 2; return ARM::VLD3q16_UPD;
6369   case ARM::VLD3qWB_register_Asm_32: Spacing = 2; return ARM::VLD3q32_UPD;
6370   case ARM::VLD3dAsm_8:  Spacing = 1; return ARM::VLD3d8;
6371   case ARM::VLD3dAsm_16: Spacing = 1; return ARM::VLD3d16;
6372   case ARM::VLD3dAsm_32: Spacing = 1; return ARM::VLD3d32;
6373   case ARM::VLD3qAsm_8:  Spacing = 2; return ARM::VLD3q8;
6374   case ARM::VLD3qAsm_16: Spacing = 2; return ARM::VLD3q16;
6375   case ARM::VLD3qAsm_32: Spacing = 2; return ARM::VLD3q32;
6376
6377   // VLD4LN
6378   case ARM::VLD4LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4LNd8_UPD;
6379   case ARM::VLD4LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4LNd16_UPD;
6380   case ARM::VLD4LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4LNd32_UPD;
6381   case ARM::VLD4LNqWB_fixed_Asm_16: Spacing = 2; return ARM::VLD4LNq16_UPD;
6382   case ARM::VLD4LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4LNq32_UPD;
6383   case ARM::VLD4LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD4LNd8_UPD;
6384   case ARM::VLD4LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD4LNd16_UPD;
6385   case ARM::VLD4LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD4LNd32_UPD;
6386   case ARM::VLD4LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD4LNq16_UPD;
6387   case ARM::VLD4LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD4LNq32_UPD;
6388   case ARM::VLD4LNdAsm_8:  Spacing = 1; return ARM::VLD4LNd8;
6389   case ARM::VLD4LNdAsm_16: Spacing = 1; return ARM::VLD4LNd16;
6390   case ARM::VLD4LNdAsm_32: Spacing = 1; return ARM::VLD4LNd32;
6391   case ARM::VLD4LNqAsm_16: Spacing = 2; return ARM::VLD4LNq16;
6392   case ARM::VLD4LNqAsm_32: Spacing = 2; return ARM::VLD4LNq32;
6393
6394   // VLD4DUP
6395   case ARM::VLD4DUPdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4DUPd8_UPD;
6396   case ARM::VLD4DUPdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4DUPd16_UPD;
6397   case ARM::VLD4DUPdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4DUPd32_UPD;
6398   case ARM::VLD4DUPqWB_fixed_Asm_8: Spacing = 1; return ARM::VLD4DUPq8_UPD;
6399   case ARM::VLD4DUPqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4DUPq16_UPD;
6400   case ARM::VLD4DUPqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4DUPq32_UPD;
6401   case ARM::VLD4DUPdWB_register_Asm_8:  Spacing = 1; return ARM::VLD4DUPd8_UPD;
6402   case ARM::VLD4DUPdWB_register_Asm_16: Spacing = 1; return ARM::VLD4DUPd16_UPD;
6403   case ARM::VLD4DUPdWB_register_Asm_32: Spacing = 1; return ARM::VLD4DUPd32_UPD;
6404   case ARM::VLD4DUPqWB_register_Asm_8: Spacing = 2; return ARM::VLD4DUPq8_UPD;
6405   case ARM::VLD4DUPqWB_register_Asm_16: Spacing = 2; return ARM::VLD4DUPq16_UPD;
6406   case ARM::VLD4DUPqWB_register_Asm_32: Spacing = 2; return ARM::VLD4DUPq32_UPD;
6407   case ARM::VLD4DUPdAsm_8:  Spacing = 1; return ARM::VLD4DUPd8;
6408   case ARM::VLD4DUPdAsm_16: Spacing = 1; return ARM::VLD4DUPd16;
6409   case ARM::VLD4DUPdAsm_32: Spacing = 1; return ARM::VLD4DUPd32;
6410   case ARM::VLD4DUPqAsm_8: Spacing = 2; return ARM::VLD4DUPq8;
6411   case ARM::VLD4DUPqAsm_16: Spacing = 2; return ARM::VLD4DUPq16;
6412   case ARM::VLD4DUPqAsm_32: Spacing = 2; return ARM::VLD4DUPq32;
6413
6414   // VLD4
6415   case ARM::VLD4dWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4d8_UPD;
6416   case ARM::VLD4dWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4d16_UPD;
6417   case ARM::VLD4dWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4d32_UPD;
6418   case ARM::VLD4qWB_fixed_Asm_8:  Spacing = 2; return ARM::VLD4q8_UPD;
6419   case ARM::VLD4qWB_fixed_Asm_16: Spacing = 2; return ARM::VLD4q16_UPD;
6420   case ARM::VLD4qWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4q32_UPD;
6421   case ARM::VLD4dWB_register_Asm_8:  Spacing = 1; return ARM::VLD4d8_UPD;
6422   case ARM::VLD4dWB_register_Asm_16: Spacing = 1; return ARM::VLD4d16_UPD;
6423   case ARM::VLD4dWB_register_Asm_32: Spacing = 1; return ARM::VLD4d32_UPD;
6424   case ARM::VLD4qWB_register_Asm_8:  Spacing = 2; return ARM::VLD4q8_UPD;
6425   case ARM::VLD4qWB_register_Asm_16: Spacing = 2; return ARM::VLD4q16_UPD;
6426   case ARM::VLD4qWB_register_Asm_32: Spacing = 2; return ARM::VLD4q32_UPD;
6427   case ARM::VLD4dAsm_8:  Spacing = 1; return ARM::VLD4d8;
6428   case ARM::VLD4dAsm_16: Spacing = 1; return ARM::VLD4d16;
6429   case ARM::VLD4dAsm_32: Spacing = 1; return ARM::VLD4d32;
6430   case ARM::VLD4qAsm_8:  Spacing = 2; return ARM::VLD4q8;
6431   case ARM::VLD4qAsm_16: Spacing = 2; return ARM::VLD4q16;
6432   case ARM::VLD4qAsm_32: Spacing = 2; return ARM::VLD4q32;
6433   }
6434 }
6435
6436 bool ARMAsmParser::processInstruction(MCInst &Inst,
6437                                       const OperandVector &Operands,
6438                                       MCStreamer &Out) {
6439   switch (Inst.getOpcode()) {
6440   // Alias for alternate form of 'ldr{,b}t Rt, [Rn], #imm' instruction.
6441   case ARM::LDRT_POST:
6442   case ARM::LDRBT_POST: {
6443     const unsigned Opcode =
6444       (Inst.getOpcode() == ARM::LDRT_POST) ? ARM::LDRT_POST_IMM
6445                                            : ARM::LDRBT_POST_IMM;
6446     MCInst TmpInst;
6447     TmpInst.setOpcode(Opcode);
6448     TmpInst.addOperand(Inst.getOperand(0));
6449     TmpInst.addOperand(Inst.getOperand(1));
6450     TmpInst.addOperand(Inst.getOperand(1));
6451     TmpInst.addOperand(MCOperand::CreateReg(0));
6452     TmpInst.addOperand(MCOperand::CreateImm(0));
6453     TmpInst.addOperand(Inst.getOperand(2));
6454     TmpInst.addOperand(Inst.getOperand(3));
6455     Inst = TmpInst;
6456     return true;
6457   }
6458   // Alias for alternate form of 'str{,b}t Rt, [Rn], #imm' instruction.
6459   case ARM::STRT_POST:
6460   case ARM::STRBT_POST: {
6461     const unsigned Opcode =
6462       (Inst.getOpcode() == ARM::STRT_POST) ? ARM::STRT_POST_IMM
6463                                            : ARM::STRBT_POST_IMM;
6464     MCInst TmpInst;
6465     TmpInst.setOpcode(Opcode);
6466     TmpInst.addOperand(Inst.getOperand(1));
6467     TmpInst.addOperand(Inst.getOperand(0));
6468     TmpInst.addOperand(Inst.getOperand(1));
6469     TmpInst.addOperand(MCOperand::CreateReg(0));
6470     TmpInst.addOperand(MCOperand::CreateImm(0));
6471     TmpInst.addOperand(Inst.getOperand(2));
6472     TmpInst.addOperand(Inst.getOperand(3));
6473     Inst = TmpInst;
6474     return true;
6475   }
6476   // Alias for alternate form of 'ADR Rd, #imm' instruction.
6477   case ARM::ADDri: {
6478     if (Inst.getOperand(1).getReg() != ARM::PC ||
6479         Inst.getOperand(5).getReg() != 0 ||
6480         !(Inst.getOperand(2).isExpr() || Inst.getOperand(2).isImm()))
6481       return false;
6482     MCInst TmpInst;
6483     TmpInst.setOpcode(ARM::ADR);
6484     TmpInst.addOperand(Inst.getOperand(0));
6485     if (Inst.getOperand(2).isImm()) {
6486       TmpInst.addOperand(Inst.getOperand(2));
6487     } else {
6488       // Turn PC-relative expression into absolute expression.
6489       // Reading PC provides the start of the current instruction + 8 and
6490       // the transform to adr is biased by that.
6491       MCSymbol *Dot = getContext().CreateTempSymbol();
6492       Out.EmitLabel(Dot);
6493       const MCExpr *OpExpr = Inst.getOperand(2).getExpr();
6494       const MCExpr *InstPC = MCSymbolRefExpr::Create(Dot,
6495                                                      MCSymbolRefExpr::VK_None,
6496                                                      getContext());
6497       const MCExpr *Const8 = MCConstantExpr::Create(8, getContext());
6498       const MCExpr *ReadPC = MCBinaryExpr::CreateAdd(InstPC, Const8,
6499                                                      getContext());
6500       const MCExpr *FixupAddr = MCBinaryExpr::CreateAdd(ReadPC, OpExpr,
6501                                                         getContext());
6502       TmpInst.addOperand(MCOperand::CreateExpr(FixupAddr));
6503     }
6504     TmpInst.addOperand(Inst.getOperand(3));
6505     TmpInst.addOperand(Inst.getOperand(4));
6506     Inst = TmpInst;
6507     return true;
6508   }
6509   // Aliases for alternate PC+imm syntax of LDR instructions.
6510   case ARM::t2LDRpcrel:
6511     // Select the narrow version if the immediate will fit.
6512     if (Inst.getOperand(1).getImm() > 0 &&
6513         Inst.getOperand(1).getImm() <= 0xff &&
6514         !(static_cast<ARMOperand &>(*Operands[2]).isToken() &&
6515           static_cast<ARMOperand &>(*Operands[2]).getToken() == ".w"))
6516       Inst.setOpcode(ARM::tLDRpci);
6517     else
6518       Inst.setOpcode(ARM::t2LDRpci);
6519     return true;
6520   case ARM::t2LDRBpcrel:
6521     Inst.setOpcode(ARM::t2LDRBpci);
6522     return true;
6523   case ARM::t2LDRHpcrel:
6524     Inst.setOpcode(ARM::t2LDRHpci);
6525     return true;
6526   case ARM::t2LDRSBpcrel:
6527     Inst.setOpcode(ARM::t2LDRSBpci);
6528     return true;
6529   case ARM::t2LDRSHpcrel:
6530     Inst.setOpcode(ARM::t2LDRSHpci);
6531     return true;
6532   // Handle NEON VST complex aliases.
6533   case ARM::VST1LNdWB_register_Asm_8:
6534   case ARM::VST1LNdWB_register_Asm_16:
6535   case ARM::VST1LNdWB_register_Asm_32: {
6536     MCInst TmpInst;
6537     // Shuffle the operands around so the lane index operand is in the
6538     // right place.
6539     unsigned Spacing;
6540     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6541     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
6542     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6543     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6544     TmpInst.addOperand(Inst.getOperand(4)); // Rm
6545     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6546     TmpInst.addOperand(Inst.getOperand(1)); // lane
6547     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
6548     TmpInst.addOperand(Inst.getOperand(6));
6549     Inst = TmpInst;
6550     return true;
6551   }
6552
6553   case ARM::VST2LNdWB_register_Asm_8:
6554   case ARM::VST2LNdWB_register_Asm_16:
6555   case ARM::VST2LNdWB_register_Asm_32:
6556   case ARM::VST2LNqWB_register_Asm_16:
6557   case ARM::VST2LNqWB_register_Asm_32: {
6558     MCInst TmpInst;
6559     // Shuffle the operands around so the lane index operand is in the
6560     // right place.
6561     unsigned Spacing;
6562     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6563     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
6564     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6565     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6566     TmpInst.addOperand(Inst.getOperand(4)); // Rm
6567     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6568     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
6569                                             Spacing));
6570     TmpInst.addOperand(Inst.getOperand(1)); // lane
6571     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
6572     TmpInst.addOperand(Inst.getOperand(6));
6573     Inst = TmpInst;
6574     return true;
6575   }
6576
6577   case ARM::VST3LNdWB_register_Asm_8:
6578   case ARM::VST3LNdWB_register_Asm_16:
6579   case ARM::VST3LNdWB_register_Asm_32:
6580   case ARM::VST3LNqWB_register_Asm_16:
6581   case ARM::VST3LNqWB_register_Asm_32: {
6582     MCInst TmpInst;
6583     // Shuffle the operands around so the lane index operand is in the
6584     // right place.
6585     unsigned Spacing;
6586     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6587     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
6588     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6589     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6590     TmpInst.addOperand(Inst.getOperand(4)); // Rm
6591     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6592     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
6593                                             Spacing));
6594     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
6595                                             Spacing * 2));
6596     TmpInst.addOperand(Inst.getOperand(1)); // lane
6597     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
6598     TmpInst.addOperand(Inst.getOperand(6));
6599     Inst = TmpInst;
6600     return true;
6601   }
6602
6603   case ARM::VST4LNdWB_register_Asm_8:
6604   case ARM::VST4LNdWB_register_Asm_16:
6605   case ARM::VST4LNdWB_register_Asm_32:
6606   case ARM::VST4LNqWB_register_Asm_16:
6607   case ARM::VST4LNqWB_register_Asm_32: {
6608     MCInst TmpInst;
6609     // Shuffle the operands around so the lane index operand is in the
6610     // right place.
6611     unsigned Spacing;
6612     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6613     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
6614     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6615     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6616     TmpInst.addOperand(Inst.getOperand(4)); // Rm
6617     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6618     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
6619                                             Spacing));
6620     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
6621                                             Spacing * 2));
6622     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
6623                                             Spacing * 3));
6624     TmpInst.addOperand(Inst.getOperand(1)); // lane
6625     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
6626     TmpInst.addOperand(Inst.getOperand(6));
6627     Inst = TmpInst;
6628     return true;
6629   }
6630
6631   case ARM::VST1LNdWB_fixed_Asm_8:
6632   case ARM::VST1LNdWB_fixed_Asm_16:
6633   case ARM::VST1LNdWB_fixed_Asm_32: {
6634     MCInst TmpInst;
6635     // Shuffle the operands around so the lane index operand is in the
6636     // right place.
6637     unsigned Spacing;
6638     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6639     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
6640     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6641     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6642     TmpInst.addOperand(MCOperand::CreateReg(0)); // Rm
6643     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6644     TmpInst.addOperand(Inst.getOperand(1)); // lane
6645     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
6646     TmpInst.addOperand(Inst.getOperand(5));
6647     Inst = TmpInst;
6648     return true;
6649   }
6650
6651   case ARM::VST2LNdWB_fixed_Asm_8:
6652   case ARM::VST2LNdWB_fixed_Asm_16:
6653   case ARM::VST2LNdWB_fixed_Asm_32:
6654   case ARM::VST2LNqWB_fixed_Asm_16:
6655   case ARM::VST2LNqWB_fixed_Asm_32: {
6656     MCInst TmpInst;
6657     // Shuffle the operands around so the lane index operand is in the
6658     // right place.
6659     unsigned Spacing;
6660     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6661     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
6662     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6663     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6664     TmpInst.addOperand(MCOperand::CreateReg(0)); // Rm
6665     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6666     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
6667                                             Spacing));
6668     TmpInst.addOperand(Inst.getOperand(1)); // lane
6669     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
6670     TmpInst.addOperand(Inst.getOperand(5));
6671     Inst = TmpInst;
6672     return true;
6673   }
6674
6675   case ARM::VST3LNdWB_fixed_Asm_8:
6676   case ARM::VST3LNdWB_fixed_Asm_16:
6677   case ARM::VST3LNdWB_fixed_Asm_32:
6678   case ARM::VST3LNqWB_fixed_Asm_16:
6679   case ARM::VST3LNqWB_fixed_Asm_32: {
6680     MCInst TmpInst;
6681     // Shuffle the operands around so the lane index operand is in the
6682     // right place.
6683     unsigned Spacing;
6684     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6685     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
6686     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6687     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6688     TmpInst.addOperand(MCOperand::CreateReg(0)); // Rm
6689     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6690     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
6691                                             Spacing));
6692     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
6693                                             Spacing * 2));
6694     TmpInst.addOperand(Inst.getOperand(1)); // lane
6695     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
6696     TmpInst.addOperand(Inst.getOperand(5));
6697     Inst = TmpInst;
6698     return true;
6699   }
6700
6701   case ARM::VST4LNdWB_fixed_Asm_8:
6702   case ARM::VST4LNdWB_fixed_Asm_16:
6703   case ARM::VST4LNdWB_fixed_Asm_32:
6704   case ARM::VST4LNqWB_fixed_Asm_16:
6705   case ARM::VST4LNqWB_fixed_Asm_32: {
6706     MCInst TmpInst;
6707     // Shuffle the operands around so the lane index operand is in the
6708     // right place.
6709     unsigned Spacing;
6710     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6711     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
6712     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6713     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6714     TmpInst.addOperand(MCOperand::CreateReg(0)); // Rm
6715     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6716     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
6717                                             Spacing));
6718     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
6719                                             Spacing * 2));
6720     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
6721                                             Spacing * 3));
6722     TmpInst.addOperand(Inst.getOperand(1)); // lane
6723     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
6724     TmpInst.addOperand(Inst.getOperand(5));
6725     Inst = TmpInst;
6726     return true;
6727   }
6728
6729   case ARM::VST1LNdAsm_8:
6730   case ARM::VST1LNdAsm_16:
6731   case ARM::VST1LNdAsm_32: {
6732     MCInst TmpInst;
6733     // Shuffle the operands around so the lane index operand is in the
6734     // right place.
6735     unsigned Spacing;
6736     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6737     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6738     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6739     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6740     TmpInst.addOperand(Inst.getOperand(1)); // lane
6741     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
6742     TmpInst.addOperand(Inst.getOperand(5));
6743     Inst = TmpInst;
6744     return true;
6745   }
6746
6747   case ARM::VST2LNdAsm_8:
6748   case ARM::VST2LNdAsm_16:
6749   case ARM::VST2LNdAsm_32:
6750   case ARM::VST2LNqAsm_16:
6751   case ARM::VST2LNqAsm_32: {
6752     MCInst TmpInst;
6753     // Shuffle the operands around so the lane index operand is in the
6754     // right place.
6755     unsigned Spacing;
6756     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6757     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6758     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6759     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6760     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
6761                                             Spacing));
6762     TmpInst.addOperand(Inst.getOperand(1)); // lane
6763     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
6764     TmpInst.addOperand(Inst.getOperand(5));
6765     Inst = TmpInst;
6766     return true;
6767   }
6768
6769   case ARM::VST3LNdAsm_8:
6770   case ARM::VST3LNdAsm_16:
6771   case ARM::VST3LNdAsm_32:
6772   case ARM::VST3LNqAsm_16:
6773   case ARM::VST3LNqAsm_32: {
6774     MCInst TmpInst;
6775     // Shuffle the operands around so the lane index operand is in the
6776     // right place.
6777     unsigned Spacing;
6778     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6779     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6780     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6781     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6782     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
6783                                             Spacing));
6784     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
6785                                             Spacing * 2));
6786     TmpInst.addOperand(Inst.getOperand(1)); // lane
6787     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
6788     TmpInst.addOperand(Inst.getOperand(5));
6789     Inst = TmpInst;
6790     return true;
6791   }
6792
6793   case ARM::VST4LNdAsm_8:
6794   case ARM::VST4LNdAsm_16:
6795   case ARM::VST4LNdAsm_32:
6796   case ARM::VST4LNqAsm_16:
6797   case ARM::VST4LNqAsm_32: {
6798     MCInst TmpInst;
6799     // Shuffle the operands around so the lane index operand is in the
6800     // right place.
6801     unsigned Spacing;
6802     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6803     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6804     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6805     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6806     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
6807                                             Spacing));
6808     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
6809                                             Spacing * 2));
6810     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
6811                                             Spacing * 3));
6812     TmpInst.addOperand(Inst.getOperand(1)); // lane
6813     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
6814     TmpInst.addOperand(Inst.getOperand(5));
6815     Inst = TmpInst;
6816     return true;
6817   }
6818
6819   // Handle NEON VLD complex aliases.
6820   case ARM::VLD1LNdWB_register_Asm_8:
6821   case ARM::VLD1LNdWB_register_Asm_16:
6822   case ARM::VLD1LNdWB_register_Asm_32: {
6823     MCInst TmpInst;
6824     // Shuffle the operands around so the lane index operand is in the
6825     // right place.
6826     unsigned Spacing;
6827     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
6828     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6829     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
6830     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6831     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6832     TmpInst.addOperand(Inst.getOperand(4)); // Rm
6833     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
6834     TmpInst.addOperand(Inst.getOperand(1)); // lane
6835     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
6836     TmpInst.addOperand(Inst.getOperand(6));
6837     Inst = TmpInst;
6838     return true;
6839   }
6840
6841   case ARM::VLD2LNdWB_register_Asm_8:
6842   case ARM::VLD2LNdWB_register_Asm_16:
6843   case ARM::VLD2LNdWB_register_Asm_32:
6844   case ARM::VLD2LNqWB_register_Asm_16:
6845   case ARM::VLD2LNqWB_register_Asm_32: {
6846     MCInst TmpInst;
6847     // Shuffle the operands around so the lane index operand is in the
6848     // right place.
6849     unsigned Spacing;
6850     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
6851     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6852     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
6853                                             Spacing));
6854     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
6855     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6856     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6857     TmpInst.addOperand(Inst.getOperand(4)); // Rm
6858     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
6859     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
6860                                             Spacing));
6861     TmpInst.addOperand(Inst.getOperand(1)); // lane
6862     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
6863     TmpInst.addOperand(Inst.getOperand(6));
6864     Inst = TmpInst;
6865     return true;
6866   }
6867
6868   case ARM::VLD3LNdWB_register_Asm_8:
6869   case ARM::VLD3LNdWB_register_Asm_16:
6870   case ARM::VLD3LNdWB_register_Asm_32:
6871   case ARM::VLD3LNqWB_register_Asm_16:
6872   case ARM::VLD3LNqWB_register_Asm_32: {
6873     MCInst TmpInst;
6874     // Shuffle the operands around so the lane index operand is in the
6875     // right place.
6876     unsigned Spacing;
6877     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
6878     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6879     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
6880                                             Spacing));
6881     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
6882                                             Spacing * 2));
6883     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
6884     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6885     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6886     TmpInst.addOperand(Inst.getOperand(4)); // Rm
6887     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
6888     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
6889                                             Spacing));
6890     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
6891                                             Spacing * 2));
6892     TmpInst.addOperand(Inst.getOperand(1)); // lane
6893     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
6894     TmpInst.addOperand(Inst.getOperand(6));
6895     Inst = TmpInst;
6896     return true;
6897   }
6898
6899   case ARM::VLD4LNdWB_register_Asm_8:
6900   case ARM::VLD4LNdWB_register_Asm_16:
6901   case ARM::VLD4LNdWB_register_Asm_32:
6902   case ARM::VLD4LNqWB_register_Asm_16:
6903   case ARM::VLD4LNqWB_register_Asm_32: {
6904     MCInst TmpInst;
6905     // Shuffle the operands around so the lane index operand is in the
6906     // right place.
6907     unsigned Spacing;
6908     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
6909     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6910     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
6911                                             Spacing));
6912     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
6913                                             Spacing * 2));
6914     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
6915                                             Spacing * 3));
6916     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
6917     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6918     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6919     TmpInst.addOperand(Inst.getOperand(4)); // Rm
6920     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
6921     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
6922                                             Spacing));
6923     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
6924                                             Spacing * 2));
6925     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
6926                                             Spacing * 3));
6927     TmpInst.addOperand(Inst.getOperand(1)); // lane
6928     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
6929     TmpInst.addOperand(Inst.getOperand(6));
6930     Inst = TmpInst;
6931     return true;
6932   }
6933
6934   case ARM::VLD1LNdWB_fixed_Asm_8:
6935   case ARM::VLD1LNdWB_fixed_Asm_16:
6936   case ARM::VLD1LNdWB_fixed_Asm_32: {
6937     MCInst TmpInst;
6938     // Shuffle the operands around so the lane index operand is in the
6939     // right place.
6940     unsigned Spacing;
6941     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
6942     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6943     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
6944     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6945     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6946     TmpInst.addOperand(MCOperand::CreateReg(0)); // Rm
6947     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
6948     TmpInst.addOperand(Inst.getOperand(1)); // lane
6949     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
6950     TmpInst.addOperand(Inst.getOperand(5));
6951     Inst = TmpInst;
6952     return true;
6953   }
6954
6955   case ARM::VLD2LNdWB_fixed_Asm_8:
6956   case ARM::VLD2LNdWB_fixed_Asm_16:
6957   case ARM::VLD2LNdWB_fixed_Asm_32:
6958   case ARM::VLD2LNqWB_fixed_Asm_16:
6959   case ARM::VLD2LNqWB_fixed_Asm_32: {
6960     MCInst TmpInst;
6961     // Shuffle the operands around so the lane index operand is in the
6962     // right place.
6963     unsigned Spacing;
6964     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
6965     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6966     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
6967                                             Spacing));
6968     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
6969     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6970     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6971     TmpInst.addOperand(MCOperand::CreateReg(0)); // Rm
6972     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
6973     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
6974                                             Spacing));
6975     TmpInst.addOperand(Inst.getOperand(1)); // lane
6976     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
6977     TmpInst.addOperand(Inst.getOperand(5));
6978     Inst = TmpInst;
6979     return true;
6980   }
6981
6982   case ARM::VLD3LNdWB_fixed_Asm_8:
6983   case ARM::VLD3LNdWB_fixed_Asm_16:
6984   case ARM::VLD3LNdWB_fixed_Asm_32:
6985   case ARM::VLD3LNqWB_fixed_Asm_16:
6986   case ARM::VLD3LNqWB_fixed_Asm_32: {
6987     MCInst TmpInst;
6988     // Shuffle the operands around so the lane index operand is in the
6989     // right place.
6990     unsigned Spacing;
6991     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
6992     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6993     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
6994                                             Spacing));
6995     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
6996                                             Spacing * 2));
6997     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
6998     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6999     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7000     TmpInst.addOperand(MCOperand::CreateReg(0)); // Rm
7001     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7002     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7003                                             Spacing));
7004     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7005                                             Spacing * 2));
7006     TmpInst.addOperand(Inst.getOperand(1)); // lane
7007     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7008     TmpInst.addOperand(Inst.getOperand(5));
7009     Inst = TmpInst;
7010     return true;
7011   }
7012
7013   case ARM::VLD4LNdWB_fixed_Asm_8:
7014   case ARM::VLD4LNdWB_fixed_Asm_16:
7015   case ARM::VLD4LNdWB_fixed_Asm_32:
7016   case ARM::VLD4LNqWB_fixed_Asm_16:
7017   case ARM::VLD4LNqWB_fixed_Asm_32: {
7018     MCInst TmpInst;
7019     // Shuffle the operands around so the lane index operand is in the
7020     // right place.
7021     unsigned Spacing;
7022     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7023     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7024     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7025                                             Spacing));
7026     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7027                                             Spacing * 2));
7028     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7029                                             Spacing * 3));
7030     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7031     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7032     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7033     TmpInst.addOperand(MCOperand::CreateReg(0)); // Rm
7034     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7035     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7036                                             Spacing));
7037     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7038                                             Spacing * 2));
7039     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7040                                             Spacing * 3));
7041     TmpInst.addOperand(Inst.getOperand(1)); // lane
7042     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7043     TmpInst.addOperand(Inst.getOperand(5));
7044     Inst = TmpInst;
7045     return true;
7046   }
7047
7048   case ARM::VLD1LNdAsm_8:
7049   case ARM::VLD1LNdAsm_16:
7050   case ARM::VLD1LNdAsm_32: {
7051     MCInst TmpInst;
7052     // Shuffle the operands around so the lane index operand is in the
7053     // right place.
7054     unsigned Spacing;
7055     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7056     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7057     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7058     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7059     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7060     TmpInst.addOperand(Inst.getOperand(1)); // lane
7061     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7062     TmpInst.addOperand(Inst.getOperand(5));
7063     Inst = TmpInst;
7064     return true;
7065   }
7066
7067   case ARM::VLD2LNdAsm_8:
7068   case ARM::VLD2LNdAsm_16:
7069   case ARM::VLD2LNdAsm_32:
7070   case ARM::VLD2LNqAsm_16:
7071   case ARM::VLD2LNqAsm_32: {
7072     MCInst TmpInst;
7073     // Shuffle the operands around so the lane index operand is in the
7074     // right place.
7075     unsigned Spacing;
7076     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7077     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7078     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7079                                             Spacing));
7080     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7081     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7082     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7083     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7084                                             Spacing));
7085     TmpInst.addOperand(Inst.getOperand(1)); // lane
7086     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7087     TmpInst.addOperand(Inst.getOperand(5));
7088     Inst = TmpInst;
7089     return true;
7090   }
7091
7092   case ARM::VLD3LNdAsm_8:
7093   case ARM::VLD3LNdAsm_16:
7094   case ARM::VLD3LNdAsm_32:
7095   case ARM::VLD3LNqAsm_16:
7096   case ARM::VLD3LNqAsm_32: {
7097     MCInst TmpInst;
7098     // Shuffle the operands around so the lane index operand is in the
7099     // right place.
7100     unsigned Spacing;
7101     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7102     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7103     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7104                                             Spacing));
7105     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7106                                             Spacing * 2));
7107     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7108     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7109     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7110     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7111                                             Spacing));
7112     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7113                                             Spacing * 2));
7114     TmpInst.addOperand(Inst.getOperand(1)); // lane
7115     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7116     TmpInst.addOperand(Inst.getOperand(5));
7117     Inst = TmpInst;
7118     return true;
7119   }
7120
7121   case ARM::VLD4LNdAsm_8:
7122   case ARM::VLD4LNdAsm_16:
7123   case ARM::VLD4LNdAsm_32:
7124   case ARM::VLD4LNqAsm_16:
7125   case ARM::VLD4LNqAsm_32: {
7126     MCInst TmpInst;
7127     // Shuffle the operands around so the lane index operand is in the
7128     // right place.
7129     unsigned Spacing;
7130     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7131     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7132     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7133                                             Spacing));
7134     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7135                                             Spacing * 2));
7136     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7137                                             Spacing * 3));
7138     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7139     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7140     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7141     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7142                                             Spacing));
7143     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7144                                             Spacing * 2));
7145     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7146                                             Spacing * 3));
7147     TmpInst.addOperand(Inst.getOperand(1)); // lane
7148     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7149     TmpInst.addOperand(Inst.getOperand(5));
7150     Inst = TmpInst;
7151     return true;
7152   }
7153
7154   // VLD3DUP single 3-element structure to all lanes instructions.
7155   case ARM::VLD3DUPdAsm_8:
7156   case ARM::VLD3DUPdAsm_16:
7157   case ARM::VLD3DUPdAsm_32:
7158   case ARM::VLD3DUPqAsm_8:
7159   case ARM::VLD3DUPqAsm_16:
7160   case ARM::VLD3DUPqAsm_32: {
7161     MCInst TmpInst;
7162     unsigned Spacing;
7163     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7164     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7165     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7166                                             Spacing));
7167     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7168                                             Spacing * 2));
7169     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7170     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7171     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7172     TmpInst.addOperand(Inst.getOperand(4));
7173     Inst = TmpInst;
7174     return true;
7175   }
7176
7177   case ARM::VLD3DUPdWB_fixed_Asm_8:
7178   case ARM::VLD3DUPdWB_fixed_Asm_16:
7179   case ARM::VLD3DUPdWB_fixed_Asm_32:
7180   case ARM::VLD3DUPqWB_fixed_Asm_8:
7181   case ARM::VLD3DUPqWB_fixed_Asm_16:
7182   case ARM::VLD3DUPqWB_fixed_Asm_32: {
7183     MCInst TmpInst;
7184     unsigned Spacing;
7185     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7186     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7187     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7188                                             Spacing));
7189     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7190                                             Spacing * 2));
7191     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7192     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7193     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7194     TmpInst.addOperand(MCOperand::CreateReg(0)); // Rm
7195     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7196     TmpInst.addOperand(Inst.getOperand(4));
7197     Inst = TmpInst;
7198     return true;
7199   }
7200
7201   case ARM::VLD3DUPdWB_register_Asm_8:
7202   case ARM::VLD3DUPdWB_register_Asm_16:
7203   case ARM::VLD3DUPdWB_register_Asm_32:
7204   case ARM::VLD3DUPqWB_register_Asm_8:
7205   case ARM::VLD3DUPqWB_register_Asm_16:
7206   case ARM::VLD3DUPqWB_register_Asm_32: {
7207     MCInst TmpInst;
7208     unsigned Spacing;
7209     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7210     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7211     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7212                                             Spacing));
7213     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7214                                             Spacing * 2));
7215     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7216     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7217     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7218     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7219     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7220     TmpInst.addOperand(Inst.getOperand(5));
7221     Inst = TmpInst;
7222     return true;
7223   }
7224
7225   // VLD3 multiple 3-element structure instructions.
7226   case ARM::VLD3dAsm_8:
7227   case ARM::VLD3dAsm_16:
7228   case ARM::VLD3dAsm_32:
7229   case ARM::VLD3qAsm_8:
7230   case ARM::VLD3qAsm_16:
7231   case ARM::VLD3qAsm_32: {
7232     MCInst TmpInst;
7233     unsigned Spacing;
7234     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7235     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7236     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7237                                             Spacing));
7238     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7239                                             Spacing * 2));
7240     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7241     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7242     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7243     TmpInst.addOperand(Inst.getOperand(4));
7244     Inst = TmpInst;
7245     return true;
7246   }
7247
7248   case ARM::VLD3dWB_fixed_Asm_8:
7249   case ARM::VLD3dWB_fixed_Asm_16:
7250   case ARM::VLD3dWB_fixed_Asm_32:
7251   case ARM::VLD3qWB_fixed_Asm_8:
7252   case ARM::VLD3qWB_fixed_Asm_16:
7253   case ARM::VLD3qWB_fixed_Asm_32: {
7254     MCInst TmpInst;
7255     unsigned Spacing;
7256     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7257     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7258     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7259                                             Spacing));
7260     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7261                                             Spacing * 2));
7262     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7263     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7264     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7265     TmpInst.addOperand(MCOperand::CreateReg(0)); // Rm
7266     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7267     TmpInst.addOperand(Inst.getOperand(4));
7268     Inst = TmpInst;
7269     return true;
7270   }
7271
7272   case ARM::VLD3dWB_register_Asm_8:
7273   case ARM::VLD3dWB_register_Asm_16:
7274   case ARM::VLD3dWB_register_Asm_32:
7275   case ARM::VLD3qWB_register_Asm_8:
7276   case ARM::VLD3qWB_register_Asm_16:
7277   case ARM::VLD3qWB_register_Asm_32: {
7278     MCInst TmpInst;
7279     unsigned Spacing;
7280     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7281     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7282     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7283                                             Spacing));
7284     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7285                                             Spacing * 2));
7286     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7287     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7288     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7289     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7290     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7291     TmpInst.addOperand(Inst.getOperand(5));
7292     Inst = TmpInst;
7293     return true;
7294   }
7295
7296   // VLD4DUP single 3-element structure to all lanes instructions.
7297   case ARM::VLD4DUPdAsm_8:
7298   case ARM::VLD4DUPdAsm_16:
7299   case ARM::VLD4DUPdAsm_32:
7300   case ARM::VLD4DUPqAsm_8:
7301   case ARM::VLD4DUPqAsm_16:
7302   case ARM::VLD4DUPqAsm_32: {
7303     MCInst TmpInst;
7304     unsigned Spacing;
7305     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7306     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7307     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7308                                             Spacing));
7309     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7310                                             Spacing * 2));
7311     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7312                                             Spacing * 3));
7313     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7314     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7315     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7316     TmpInst.addOperand(Inst.getOperand(4));
7317     Inst = TmpInst;
7318     return true;
7319   }
7320
7321   case ARM::VLD4DUPdWB_fixed_Asm_8:
7322   case ARM::VLD4DUPdWB_fixed_Asm_16:
7323   case ARM::VLD4DUPdWB_fixed_Asm_32:
7324   case ARM::VLD4DUPqWB_fixed_Asm_8:
7325   case ARM::VLD4DUPqWB_fixed_Asm_16:
7326   case ARM::VLD4DUPqWB_fixed_Asm_32: {
7327     MCInst TmpInst;
7328     unsigned Spacing;
7329     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7330     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7331     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7332                                             Spacing));
7333     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7334                                             Spacing * 2));
7335     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7336                                             Spacing * 3));
7337     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7338     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7339     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7340     TmpInst.addOperand(MCOperand::CreateReg(0)); // Rm
7341     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7342     TmpInst.addOperand(Inst.getOperand(4));
7343     Inst = TmpInst;
7344     return true;
7345   }
7346
7347   case ARM::VLD4DUPdWB_register_Asm_8:
7348   case ARM::VLD4DUPdWB_register_Asm_16:
7349   case ARM::VLD4DUPdWB_register_Asm_32:
7350   case ARM::VLD4DUPqWB_register_Asm_8:
7351   case ARM::VLD4DUPqWB_register_Asm_16:
7352   case ARM::VLD4DUPqWB_register_Asm_32: {
7353     MCInst TmpInst;
7354     unsigned Spacing;
7355     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7356     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7357     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7358                                             Spacing));
7359     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7360                                             Spacing * 2));
7361     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7362                                             Spacing * 3));
7363     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7364     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7365     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7366     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7367     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7368     TmpInst.addOperand(Inst.getOperand(5));
7369     Inst = TmpInst;
7370     return true;
7371   }
7372
7373   // VLD4 multiple 4-element structure instructions.
7374   case ARM::VLD4dAsm_8:
7375   case ARM::VLD4dAsm_16:
7376   case ARM::VLD4dAsm_32:
7377   case ARM::VLD4qAsm_8:
7378   case ARM::VLD4qAsm_16:
7379   case ARM::VLD4qAsm_32: {
7380     MCInst TmpInst;
7381     unsigned Spacing;
7382     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7383     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7384     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7385                                             Spacing));
7386     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7387                                             Spacing * 2));
7388     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7389                                             Spacing * 3));
7390     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7391     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7392     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7393     TmpInst.addOperand(Inst.getOperand(4));
7394     Inst = TmpInst;
7395     return true;
7396   }
7397
7398   case ARM::VLD4dWB_fixed_Asm_8:
7399   case ARM::VLD4dWB_fixed_Asm_16:
7400   case ARM::VLD4dWB_fixed_Asm_32:
7401   case ARM::VLD4qWB_fixed_Asm_8:
7402   case ARM::VLD4qWB_fixed_Asm_16:
7403   case ARM::VLD4qWB_fixed_Asm_32: {
7404     MCInst TmpInst;
7405     unsigned Spacing;
7406     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7407     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7408     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7409                                             Spacing));
7410     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7411                                             Spacing * 2));
7412     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7413                                             Spacing * 3));
7414     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7415     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7416     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7417     TmpInst.addOperand(MCOperand::CreateReg(0)); // Rm
7418     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7419     TmpInst.addOperand(Inst.getOperand(4));
7420     Inst = TmpInst;
7421     return true;
7422   }
7423
7424   case ARM::VLD4dWB_register_Asm_8:
7425   case ARM::VLD4dWB_register_Asm_16:
7426   case ARM::VLD4dWB_register_Asm_32:
7427   case ARM::VLD4qWB_register_Asm_8:
7428   case ARM::VLD4qWB_register_Asm_16:
7429   case ARM::VLD4qWB_register_Asm_32: {
7430     MCInst TmpInst;
7431     unsigned Spacing;
7432     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7433     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7434     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7435                                             Spacing));
7436     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7437                                             Spacing * 2));
7438     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7439                                             Spacing * 3));
7440     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7441     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7442     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7443     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7444     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7445     TmpInst.addOperand(Inst.getOperand(5));
7446     Inst = TmpInst;
7447     return true;
7448   }
7449
7450   // VST3 multiple 3-element structure instructions.
7451   case ARM::VST3dAsm_8:
7452   case ARM::VST3dAsm_16:
7453   case ARM::VST3dAsm_32:
7454   case ARM::VST3qAsm_8:
7455   case ARM::VST3qAsm_16:
7456   case ARM::VST3qAsm_32: {
7457     MCInst TmpInst;
7458     unsigned Spacing;
7459     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7460     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7461     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7462     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7463     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7464                                             Spacing));
7465     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7466                                             Spacing * 2));
7467     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7468     TmpInst.addOperand(Inst.getOperand(4));
7469     Inst = TmpInst;
7470     return true;
7471   }
7472
7473   case ARM::VST3dWB_fixed_Asm_8:
7474   case ARM::VST3dWB_fixed_Asm_16:
7475   case ARM::VST3dWB_fixed_Asm_32:
7476   case ARM::VST3qWB_fixed_Asm_8:
7477   case ARM::VST3qWB_fixed_Asm_16:
7478   case ARM::VST3qWB_fixed_Asm_32: {
7479     MCInst TmpInst;
7480     unsigned Spacing;
7481     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7482     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7483     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7484     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7485     TmpInst.addOperand(MCOperand::CreateReg(0)); // Rm
7486     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7487     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7488                                             Spacing));
7489     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7490                                             Spacing * 2));
7491     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7492     TmpInst.addOperand(Inst.getOperand(4));
7493     Inst = TmpInst;
7494     return true;
7495   }
7496
7497   case ARM::VST3dWB_register_Asm_8:
7498   case ARM::VST3dWB_register_Asm_16:
7499   case ARM::VST3dWB_register_Asm_32:
7500   case ARM::VST3qWB_register_Asm_8:
7501   case ARM::VST3qWB_register_Asm_16:
7502   case ARM::VST3qWB_register_Asm_32: {
7503     MCInst TmpInst;
7504     unsigned Spacing;
7505     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7506     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7507     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7508     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7509     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7510     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7511     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7512                                             Spacing));
7513     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7514                                             Spacing * 2));
7515     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7516     TmpInst.addOperand(Inst.getOperand(5));
7517     Inst = TmpInst;
7518     return true;
7519   }
7520
7521   // VST4 multiple 3-element structure instructions.
7522   case ARM::VST4dAsm_8:
7523   case ARM::VST4dAsm_16:
7524   case ARM::VST4dAsm_32:
7525   case ARM::VST4qAsm_8:
7526   case ARM::VST4qAsm_16:
7527   case ARM::VST4qAsm_32: {
7528     MCInst TmpInst;
7529     unsigned Spacing;
7530     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7531     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7532     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7533     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7534     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7535                                             Spacing));
7536     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7537                                             Spacing * 2));
7538     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7539                                             Spacing * 3));
7540     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7541     TmpInst.addOperand(Inst.getOperand(4));
7542     Inst = TmpInst;
7543     return true;
7544   }
7545
7546   case ARM::VST4dWB_fixed_Asm_8:
7547   case ARM::VST4dWB_fixed_Asm_16:
7548   case ARM::VST4dWB_fixed_Asm_32:
7549   case ARM::VST4qWB_fixed_Asm_8:
7550   case ARM::VST4qWB_fixed_Asm_16:
7551   case ARM::VST4qWB_fixed_Asm_32: {
7552     MCInst TmpInst;
7553     unsigned Spacing;
7554     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7555     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7556     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7557     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7558     TmpInst.addOperand(MCOperand::CreateReg(0)); // Rm
7559     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7560     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7561                                             Spacing));
7562     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7563                                             Spacing * 2));
7564     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7565                                             Spacing * 3));
7566     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7567     TmpInst.addOperand(Inst.getOperand(4));
7568     Inst = TmpInst;
7569     return true;
7570   }
7571
7572   case ARM::VST4dWB_register_Asm_8:
7573   case ARM::VST4dWB_register_Asm_16:
7574   case ARM::VST4dWB_register_Asm_32:
7575   case ARM::VST4qWB_register_Asm_8:
7576   case ARM::VST4qWB_register_Asm_16:
7577   case ARM::VST4qWB_register_Asm_32: {
7578     MCInst TmpInst;
7579     unsigned Spacing;
7580     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7581     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7582     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7583     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7584     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7585     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7586     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7587                                             Spacing));
7588     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7589                                             Spacing * 2));
7590     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7591                                             Spacing * 3));
7592     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7593     TmpInst.addOperand(Inst.getOperand(5));
7594     Inst = TmpInst;
7595     return true;
7596   }
7597
7598   // Handle encoding choice for the shift-immediate instructions.
7599   case ARM::t2LSLri:
7600   case ARM::t2LSRri:
7601   case ARM::t2ASRri: {
7602     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
7603         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
7604         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
7605         !(static_cast<ARMOperand &>(*Operands[3]).isToken() &&
7606           static_cast<ARMOperand &>(*Operands[3]).getToken() == ".w")) {
7607       unsigned NewOpc;
7608       switch (Inst.getOpcode()) {
7609       default: llvm_unreachable("unexpected opcode");
7610       case ARM::t2LSLri: NewOpc = ARM::tLSLri; break;
7611       case ARM::t2LSRri: NewOpc = ARM::tLSRri; break;
7612       case ARM::t2ASRri: NewOpc = ARM::tASRri; break;
7613       }
7614       // The Thumb1 operands aren't in the same order. Awesome, eh?
7615       MCInst TmpInst;
7616       TmpInst.setOpcode(NewOpc);
7617       TmpInst.addOperand(Inst.getOperand(0));
7618       TmpInst.addOperand(Inst.getOperand(5));
7619       TmpInst.addOperand(Inst.getOperand(1));
7620       TmpInst.addOperand(Inst.getOperand(2));
7621       TmpInst.addOperand(Inst.getOperand(3));
7622       TmpInst.addOperand(Inst.getOperand(4));
7623       Inst = TmpInst;
7624       return true;
7625     }
7626     return false;
7627   }
7628
7629   // Handle the Thumb2 mode MOV complex aliases.
7630   case ARM::t2MOVsr:
7631   case ARM::t2MOVSsr: {
7632     // Which instruction to expand to depends on the CCOut operand and
7633     // whether we're in an IT block if the register operands are low
7634     // registers.
7635     bool isNarrow = false;
7636     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
7637         isARMLowRegister(Inst.getOperand(1).getReg()) &&
7638         isARMLowRegister(Inst.getOperand(2).getReg()) &&
7639         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
7640         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsr))
7641       isNarrow = true;
7642     MCInst TmpInst;
7643     unsigned newOpc;
7644     switch(ARM_AM::getSORegShOp(Inst.getOperand(3).getImm())) {
7645     default: llvm_unreachable("unexpected opcode!");
7646     case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRrr : ARM::t2ASRrr; break;
7647     case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRrr : ARM::t2LSRrr; break;
7648     case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLrr : ARM::t2LSLrr; break;
7649     case ARM_AM::ror: newOpc = isNarrow ? ARM::tROR   : ARM::t2RORrr; break;
7650     }
7651     TmpInst.setOpcode(newOpc);
7652     TmpInst.addOperand(Inst.getOperand(0)); // Rd
7653     if (isNarrow)
7654       TmpInst.addOperand(MCOperand::CreateReg(
7655           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
7656     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7657     TmpInst.addOperand(Inst.getOperand(2)); // Rm
7658     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7659     TmpInst.addOperand(Inst.getOperand(5));
7660     if (!isNarrow)
7661       TmpInst.addOperand(MCOperand::CreateReg(
7662           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
7663     Inst = TmpInst;
7664     return true;
7665   }
7666   case ARM::t2MOVsi:
7667   case ARM::t2MOVSsi: {
7668     // Which instruction to expand to depends on the CCOut operand and
7669     // whether we're in an IT block if the register operands are low
7670     // registers.
7671     bool isNarrow = false;
7672     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
7673         isARMLowRegister(Inst.getOperand(1).getReg()) &&
7674         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsi))
7675       isNarrow = true;
7676     MCInst TmpInst;
7677     unsigned newOpc;
7678     switch(ARM_AM::getSORegShOp(Inst.getOperand(2).getImm())) {
7679     default: llvm_unreachable("unexpected opcode!");
7680     case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRri : ARM::t2ASRri; break;
7681     case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRri : ARM::t2LSRri; break;
7682     case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLri : ARM::t2LSLri; break;
7683     case ARM_AM::ror: newOpc = ARM::t2RORri; isNarrow = false; break;
7684     case ARM_AM::rrx: isNarrow = false; newOpc = ARM::t2RRX; break;
7685     }
7686     unsigned Amount = ARM_AM::getSORegOffset(Inst.getOperand(2).getImm());
7687     if (Amount == 32) Amount = 0;
7688     TmpInst.setOpcode(newOpc);
7689     TmpInst.addOperand(Inst.getOperand(0)); // Rd
7690     if (isNarrow)
7691       TmpInst.addOperand(MCOperand::CreateReg(
7692           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
7693     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7694     if (newOpc != ARM::t2RRX)
7695       TmpInst.addOperand(MCOperand::CreateImm(Amount));
7696     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7697     TmpInst.addOperand(Inst.getOperand(4));
7698     if (!isNarrow)
7699       TmpInst.addOperand(MCOperand::CreateReg(
7700           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
7701     Inst = TmpInst;
7702     return true;
7703   }
7704   // Handle the ARM mode MOV complex aliases.
7705   case ARM::ASRr:
7706   case ARM::LSRr:
7707   case ARM::LSLr:
7708   case ARM::RORr: {
7709     ARM_AM::ShiftOpc ShiftTy;
7710     switch(Inst.getOpcode()) {
7711     default: llvm_unreachable("unexpected opcode!");
7712     case ARM::ASRr: ShiftTy = ARM_AM::asr; break;
7713     case ARM::LSRr: ShiftTy = ARM_AM::lsr; break;
7714     case ARM::LSLr: ShiftTy = ARM_AM::lsl; break;
7715     case ARM::RORr: ShiftTy = ARM_AM::ror; break;
7716     }
7717     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, 0);
7718     MCInst TmpInst;
7719     TmpInst.setOpcode(ARM::MOVsr);
7720     TmpInst.addOperand(Inst.getOperand(0)); // Rd
7721     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7722     TmpInst.addOperand(Inst.getOperand(2)); // Rm
7723     TmpInst.addOperand(MCOperand::CreateImm(Shifter)); // Shift value and ty
7724     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7725     TmpInst.addOperand(Inst.getOperand(4));
7726     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
7727     Inst = TmpInst;
7728     return true;
7729   }
7730   case ARM::ASRi:
7731   case ARM::LSRi:
7732   case ARM::LSLi:
7733   case ARM::RORi: {
7734     ARM_AM::ShiftOpc ShiftTy;
7735     switch(Inst.getOpcode()) {
7736     default: llvm_unreachable("unexpected opcode!");
7737     case ARM::ASRi: ShiftTy = ARM_AM::asr; break;
7738     case ARM::LSRi: ShiftTy = ARM_AM::lsr; break;
7739     case ARM::LSLi: ShiftTy = ARM_AM::lsl; break;
7740     case ARM::RORi: ShiftTy = ARM_AM::ror; break;
7741     }
7742     // A shift by zero is a plain MOVr, not a MOVsi.
7743     unsigned Amt = Inst.getOperand(2).getImm();
7744     unsigned Opc = Amt == 0 ? ARM::MOVr : ARM::MOVsi;
7745     // A shift by 32 should be encoded as 0 when permitted
7746     if (Amt == 32 && (ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr))
7747       Amt = 0;
7748     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, Amt);
7749     MCInst TmpInst;
7750     TmpInst.setOpcode(Opc);
7751     TmpInst.addOperand(Inst.getOperand(0)); // Rd
7752     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7753     if (Opc == ARM::MOVsi)
7754       TmpInst.addOperand(MCOperand::CreateImm(Shifter)); // Shift value and ty
7755     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7756     TmpInst.addOperand(Inst.getOperand(4));
7757     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
7758     Inst = TmpInst;
7759     return true;
7760   }
7761   case ARM::RRXi: {
7762     unsigned Shifter = ARM_AM::getSORegOpc(ARM_AM::rrx, 0);
7763     MCInst TmpInst;
7764     TmpInst.setOpcode(ARM::MOVsi);
7765     TmpInst.addOperand(Inst.getOperand(0)); // Rd
7766     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7767     TmpInst.addOperand(MCOperand::CreateImm(Shifter)); // Shift value and ty
7768     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
7769     TmpInst.addOperand(Inst.getOperand(3));
7770     TmpInst.addOperand(Inst.getOperand(4)); // cc_out
7771     Inst = TmpInst;
7772     return true;
7773   }
7774   case ARM::t2LDMIA_UPD: {
7775     // If this is a load of a single register, then we should use
7776     // a post-indexed LDR instruction instead, per the ARM ARM.
7777     if (Inst.getNumOperands() != 5)
7778       return false;
7779     MCInst TmpInst;
7780     TmpInst.setOpcode(ARM::t2LDR_POST);
7781     TmpInst.addOperand(Inst.getOperand(4)); // Rt
7782     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
7783     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7784     TmpInst.addOperand(MCOperand::CreateImm(4));
7785     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
7786     TmpInst.addOperand(Inst.getOperand(3));
7787     Inst = TmpInst;
7788     return true;
7789   }
7790   case ARM::t2STMDB_UPD: {
7791     // If this is a store of a single register, then we should use
7792     // a pre-indexed STR instruction instead, per the ARM ARM.
7793     if (Inst.getNumOperands() != 5)
7794       return false;
7795     MCInst TmpInst;
7796     TmpInst.setOpcode(ARM::t2STR_PRE);
7797     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
7798     TmpInst.addOperand(Inst.getOperand(4)); // Rt
7799     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7800     TmpInst.addOperand(MCOperand::CreateImm(-4));
7801     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
7802     TmpInst.addOperand(Inst.getOperand(3));
7803     Inst = TmpInst;
7804     return true;
7805   }
7806   case ARM::LDMIA_UPD:
7807     // If this is a load of a single register via a 'pop', then we should use
7808     // a post-indexed LDR instruction instead, per the ARM ARM.
7809     if (static_cast<ARMOperand &>(*Operands[0]).getToken() == "pop" &&
7810         Inst.getNumOperands() == 5) {
7811       MCInst TmpInst;
7812       TmpInst.setOpcode(ARM::LDR_POST_IMM);
7813       TmpInst.addOperand(Inst.getOperand(4)); // Rt
7814       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
7815       TmpInst.addOperand(Inst.getOperand(1)); // Rn
7816       TmpInst.addOperand(MCOperand::CreateReg(0));  // am2offset
7817       TmpInst.addOperand(MCOperand::CreateImm(4));
7818       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
7819       TmpInst.addOperand(Inst.getOperand(3));
7820       Inst = TmpInst;
7821       return true;
7822     }
7823     break;
7824   case ARM::STMDB_UPD:
7825     // If this is a store of a single register via a 'push', then we should use
7826     // a pre-indexed STR instruction instead, per the ARM ARM.
7827     if (static_cast<ARMOperand &>(*Operands[0]).getToken() == "push" &&
7828         Inst.getNumOperands() == 5) {
7829       MCInst TmpInst;
7830       TmpInst.setOpcode(ARM::STR_PRE_IMM);
7831       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
7832       TmpInst.addOperand(Inst.getOperand(4)); // Rt
7833       TmpInst.addOperand(Inst.getOperand(1)); // addrmode_imm12
7834       TmpInst.addOperand(MCOperand::CreateImm(-4));
7835       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
7836       TmpInst.addOperand(Inst.getOperand(3));
7837       Inst = TmpInst;
7838     }
7839     break;
7840   case ARM::t2ADDri12:
7841     // If the immediate fits for encoding T3 (t2ADDri) and the generic "add"
7842     // mnemonic was used (not "addw"), encoding T3 is preferred.
7843     if (static_cast<ARMOperand &>(*Operands[0]).getToken() != "add" ||
7844         ARM_AM::getT2SOImmVal(Inst.getOperand(2).getImm()) == -1)
7845       break;
7846     Inst.setOpcode(ARM::t2ADDri);
7847     Inst.addOperand(MCOperand::CreateReg(0)); // cc_out
7848     break;
7849   case ARM::t2SUBri12:
7850     // If the immediate fits for encoding T3 (t2SUBri) and the generic "sub"
7851     // mnemonic was used (not "subw"), encoding T3 is preferred.
7852     if (static_cast<ARMOperand &>(*Operands[0]).getToken() != "sub" ||
7853         ARM_AM::getT2SOImmVal(Inst.getOperand(2).getImm()) == -1)
7854       break;
7855     Inst.setOpcode(ARM::t2SUBri);
7856     Inst.addOperand(MCOperand::CreateReg(0)); // cc_out
7857     break;
7858   case ARM::tADDi8:
7859     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
7860     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
7861     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
7862     // to encoding T1 if <Rd> is omitted."
7863     if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
7864       Inst.setOpcode(ARM::tADDi3);
7865       return true;
7866     }
7867     break;
7868   case ARM::tSUBi8:
7869     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
7870     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
7871     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
7872     // to encoding T1 if <Rd> is omitted."
7873     if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
7874       Inst.setOpcode(ARM::tSUBi3);
7875       return true;
7876     }
7877     break;
7878   case ARM::t2ADDri:
7879   case ARM::t2SUBri: {
7880     // If the destination and first source operand are the same, and
7881     // the flags are compatible with the current IT status, use encoding T2
7882     // instead of T3. For compatibility with the system 'as'. Make sure the
7883     // wide encoding wasn't explicit.
7884     if (Inst.getOperand(0).getReg() != Inst.getOperand(1).getReg() ||
7885         !isARMLowRegister(Inst.getOperand(0).getReg()) ||
7886         (unsigned)Inst.getOperand(2).getImm() > 255 ||
7887         ((!inITBlock() && Inst.getOperand(5).getReg() != ARM::CPSR) ||
7888          (inITBlock() && Inst.getOperand(5).getReg() != 0)) ||
7889         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
7890          static_cast<ARMOperand &>(*Operands[3]).getToken() == ".w"))
7891       break;
7892     MCInst TmpInst;
7893     TmpInst.setOpcode(Inst.getOpcode() == ARM::t2ADDri ?
7894                       ARM::tADDi8 : ARM::tSUBi8);
7895     TmpInst.addOperand(Inst.getOperand(0));
7896     TmpInst.addOperand(Inst.getOperand(5));
7897     TmpInst.addOperand(Inst.getOperand(0));
7898     TmpInst.addOperand(Inst.getOperand(2));
7899     TmpInst.addOperand(Inst.getOperand(3));
7900     TmpInst.addOperand(Inst.getOperand(4));
7901     Inst = TmpInst;
7902     return true;
7903   }
7904   case ARM::t2ADDrr: {
7905     // If the destination and first source operand are the same, and
7906     // there's no setting of the flags, use encoding T2 instead of T3.
7907     // Note that this is only for ADD, not SUB. This mirrors the system
7908     // 'as' behaviour. Make sure the wide encoding wasn't explicit.
7909     if (Inst.getOperand(0).getReg() != Inst.getOperand(1).getReg() ||
7910         Inst.getOperand(5).getReg() != 0 ||
7911         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
7912          static_cast<ARMOperand &>(*Operands[3]).getToken() == ".w"))
7913       break;
7914     MCInst TmpInst;
7915     TmpInst.setOpcode(ARM::tADDhirr);
7916     TmpInst.addOperand(Inst.getOperand(0));
7917     TmpInst.addOperand(Inst.getOperand(0));
7918     TmpInst.addOperand(Inst.getOperand(2));
7919     TmpInst.addOperand(Inst.getOperand(3));
7920     TmpInst.addOperand(Inst.getOperand(4));
7921     Inst = TmpInst;
7922     return true;
7923   }
7924   case ARM::tADDrSP: {
7925     // If the non-SP source operand and the destination operand are not the
7926     // same, we need to use the 32-bit encoding if it's available.
7927     if (Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg()) {
7928       Inst.setOpcode(ARM::t2ADDrr);
7929       Inst.addOperand(MCOperand::CreateReg(0)); // cc_out
7930       return true;
7931     }
7932     break;
7933   }
7934   case ARM::tB:
7935     // A Thumb conditional branch outside of an IT block is a tBcc.
7936     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()) {
7937       Inst.setOpcode(ARM::tBcc);
7938       return true;
7939     }
7940     break;
7941   case ARM::t2B:
7942     // A Thumb2 conditional branch outside of an IT block is a t2Bcc.
7943     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()){
7944       Inst.setOpcode(ARM::t2Bcc);
7945       return true;
7946     }
7947     break;
7948   case ARM::t2Bcc:
7949     // If the conditional is AL or we're in an IT block, we really want t2B.
7950     if (Inst.getOperand(1).getImm() == ARMCC::AL || inITBlock()) {
7951       Inst.setOpcode(ARM::t2B);
7952       return true;
7953     }
7954     break;
7955   case ARM::tBcc:
7956     // If the conditional is AL, we really want tB.
7957     if (Inst.getOperand(1).getImm() == ARMCC::AL) {
7958       Inst.setOpcode(ARM::tB);
7959       return true;
7960     }
7961     break;
7962   case ARM::tLDMIA: {
7963     // If the register list contains any high registers, or if the writeback
7964     // doesn't match what tLDMIA can do, we need to use the 32-bit encoding
7965     // instead if we're in Thumb2. Otherwise, this should have generated
7966     // an error in validateInstruction().
7967     unsigned Rn = Inst.getOperand(0).getReg();
7968     bool hasWritebackToken =
7969         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
7970          static_cast<ARMOperand &>(*Operands[3]).getToken() == "!");
7971     bool listContainsBase;
7972     if (checkLowRegisterList(Inst, 3, Rn, 0, listContainsBase) ||
7973         (!listContainsBase && !hasWritebackToken) ||
7974         (listContainsBase && hasWritebackToken)) {
7975       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
7976       assert (isThumbTwo());
7977       Inst.setOpcode(hasWritebackToken ? ARM::t2LDMIA_UPD : ARM::t2LDMIA);
7978       // If we're switching to the updating version, we need to insert
7979       // the writeback tied operand.
7980       if (hasWritebackToken)
7981         Inst.insert(Inst.begin(),
7982                     MCOperand::CreateReg(Inst.getOperand(0).getReg()));
7983       return true;
7984     }
7985     break;
7986   }
7987   case ARM::tSTMIA_UPD: {
7988     // If the register list contains any high registers, we need to use
7989     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
7990     // should have generated an error in validateInstruction().
7991     unsigned Rn = Inst.getOperand(0).getReg();
7992     bool listContainsBase;
7993     if (checkLowRegisterList(Inst, 4, Rn, 0, listContainsBase)) {
7994       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
7995       assert (isThumbTwo());
7996       Inst.setOpcode(ARM::t2STMIA_UPD);
7997       return true;
7998     }
7999     break;
8000   }
8001   case ARM::tPOP: {
8002     bool listContainsBase;
8003     // If the register list contains any high registers, we need to use
8004     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
8005     // should have generated an error in validateInstruction().
8006     if (!checkLowRegisterList(Inst, 2, 0, ARM::PC, listContainsBase))
8007       return false;
8008     assert (isThumbTwo());
8009     Inst.setOpcode(ARM::t2LDMIA_UPD);
8010     // Add the base register and writeback operands.
8011     Inst.insert(Inst.begin(), MCOperand::CreateReg(ARM::SP));
8012     Inst.insert(Inst.begin(), MCOperand::CreateReg(ARM::SP));
8013     return true;
8014   }
8015   case ARM::tPUSH: {
8016     bool listContainsBase;
8017     if (!checkLowRegisterList(Inst, 2, 0, ARM::LR, listContainsBase))
8018       return false;
8019     assert (isThumbTwo());
8020     Inst.setOpcode(ARM::t2STMDB_UPD);
8021     // Add the base register and writeback operands.
8022     Inst.insert(Inst.begin(), MCOperand::CreateReg(ARM::SP));
8023     Inst.insert(Inst.begin(), MCOperand::CreateReg(ARM::SP));
8024     return true;
8025   }
8026   case ARM::t2MOVi: {
8027     // If we can use the 16-bit encoding and the user didn't explicitly
8028     // request the 32-bit variant, transform it here.
8029     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8030         (unsigned)Inst.getOperand(1).getImm() <= 255 &&
8031         ((!inITBlock() && Inst.getOperand(2).getImm() == ARMCC::AL &&
8032           Inst.getOperand(4).getReg() == ARM::CPSR) ||
8033          (inITBlock() && Inst.getOperand(4).getReg() == 0)) &&
8034         (!static_cast<ARMOperand &>(*Operands[2]).isToken() ||
8035          static_cast<ARMOperand &>(*Operands[2]).getToken() != ".w")) {
8036       // The operands aren't in the same order for tMOVi8...
8037       MCInst TmpInst;
8038       TmpInst.setOpcode(ARM::tMOVi8);
8039       TmpInst.addOperand(Inst.getOperand(0));
8040       TmpInst.addOperand(Inst.getOperand(4));
8041       TmpInst.addOperand(Inst.getOperand(1));
8042       TmpInst.addOperand(Inst.getOperand(2));
8043       TmpInst.addOperand(Inst.getOperand(3));
8044       Inst = TmpInst;
8045       return true;
8046     }
8047     break;
8048   }
8049   case ARM::t2MOVr: {
8050     // If we can use the 16-bit encoding and the user didn't explicitly
8051     // request the 32-bit variant, transform it here.
8052     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8053         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8054         Inst.getOperand(2).getImm() == ARMCC::AL &&
8055         Inst.getOperand(4).getReg() == ARM::CPSR &&
8056         (!static_cast<ARMOperand &>(*Operands[2]).isToken() ||
8057          static_cast<ARMOperand &>(*Operands[2]).getToken() != ".w")) {
8058       // The operands aren't the same for tMOV[S]r... (no cc_out)
8059       MCInst TmpInst;
8060       TmpInst.setOpcode(Inst.getOperand(4).getReg() ? ARM::tMOVSr : ARM::tMOVr);
8061       TmpInst.addOperand(Inst.getOperand(0));
8062       TmpInst.addOperand(Inst.getOperand(1));
8063       TmpInst.addOperand(Inst.getOperand(2));
8064       TmpInst.addOperand(Inst.getOperand(3));
8065       Inst = TmpInst;
8066       return true;
8067     }
8068     break;
8069   }
8070   case ARM::t2SXTH:
8071   case ARM::t2SXTB:
8072   case ARM::t2UXTH:
8073   case ARM::t2UXTB: {
8074     // If we can use the 16-bit encoding and the user didn't explicitly
8075     // request the 32-bit variant, transform it here.
8076     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8077         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8078         Inst.getOperand(2).getImm() == 0 &&
8079         (!static_cast<ARMOperand &>(*Operands[2]).isToken() ||
8080          static_cast<ARMOperand &>(*Operands[2]).getToken() != ".w")) {
8081       unsigned NewOpc;
8082       switch (Inst.getOpcode()) {
8083       default: llvm_unreachable("Illegal opcode!");
8084       case ARM::t2SXTH: NewOpc = ARM::tSXTH; break;
8085       case ARM::t2SXTB: NewOpc = ARM::tSXTB; break;
8086       case ARM::t2UXTH: NewOpc = ARM::tUXTH; break;
8087       case ARM::t2UXTB: NewOpc = ARM::tUXTB; break;
8088       }
8089       // The operands aren't the same for thumb1 (no rotate operand).
8090       MCInst TmpInst;
8091       TmpInst.setOpcode(NewOpc);
8092       TmpInst.addOperand(Inst.getOperand(0));
8093       TmpInst.addOperand(Inst.getOperand(1));
8094       TmpInst.addOperand(Inst.getOperand(3));
8095       TmpInst.addOperand(Inst.getOperand(4));
8096       Inst = TmpInst;
8097       return true;
8098     }
8099     break;
8100   }
8101   case ARM::MOVsi: {
8102     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(2).getImm());
8103     // rrx shifts and asr/lsr of #32 is encoded as 0
8104     if (SOpc == ARM_AM::rrx || SOpc == ARM_AM::asr || SOpc == ARM_AM::lsr) 
8105       return false;
8106     if (ARM_AM::getSORegOffset(Inst.getOperand(2).getImm()) == 0) {
8107       // Shifting by zero is accepted as a vanilla 'MOVr'
8108       MCInst TmpInst;
8109       TmpInst.setOpcode(ARM::MOVr);
8110       TmpInst.addOperand(Inst.getOperand(0));
8111       TmpInst.addOperand(Inst.getOperand(1));
8112       TmpInst.addOperand(Inst.getOperand(3));
8113       TmpInst.addOperand(Inst.getOperand(4));
8114       TmpInst.addOperand(Inst.getOperand(5));
8115       Inst = TmpInst;
8116       return true;
8117     }
8118     return false;
8119   }
8120   case ARM::ANDrsi:
8121   case ARM::ORRrsi:
8122   case ARM::EORrsi:
8123   case ARM::BICrsi:
8124   case ARM::SUBrsi:
8125   case ARM::ADDrsi: {
8126     unsigned newOpc;
8127     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(3).getImm());
8128     if (SOpc == ARM_AM::rrx) return false;
8129     switch (Inst.getOpcode()) {
8130     default: llvm_unreachable("unexpected opcode!");
8131     case ARM::ANDrsi: newOpc = ARM::ANDrr; break;
8132     case ARM::ORRrsi: newOpc = ARM::ORRrr; break;
8133     case ARM::EORrsi: newOpc = ARM::EORrr; break;
8134     case ARM::BICrsi: newOpc = ARM::BICrr; break;
8135     case ARM::SUBrsi: newOpc = ARM::SUBrr; break;
8136     case ARM::ADDrsi: newOpc = ARM::ADDrr; break;
8137     }
8138     // If the shift is by zero, use the non-shifted instruction definition.
8139     // The exception is for right shifts, where 0 == 32
8140     if (ARM_AM::getSORegOffset(Inst.getOperand(3).getImm()) == 0 &&
8141         !(SOpc == ARM_AM::lsr || SOpc == ARM_AM::asr)) {
8142       MCInst TmpInst;
8143       TmpInst.setOpcode(newOpc);
8144       TmpInst.addOperand(Inst.getOperand(0));
8145       TmpInst.addOperand(Inst.getOperand(1));
8146       TmpInst.addOperand(Inst.getOperand(2));
8147       TmpInst.addOperand(Inst.getOperand(4));
8148       TmpInst.addOperand(Inst.getOperand(5));
8149       TmpInst.addOperand(Inst.getOperand(6));
8150       Inst = TmpInst;
8151       return true;
8152     }
8153     return false;
8154   }
8155   case ARM::ITasm:
8156   case ARM::t2IT: {
8157     // The mask bits for all but the first condition are represented as
8158     // the low bit of the condition code value implies 't'. We currently
8159     // always have 1 implies 't', so XOR toggle the bits if the low bit
8160     // of the condition code is zero. 
8161     MCOperand &MO = Inst.getOperand(1);
8162     unsigned Mask = MO.getImm();
8163     unsigned OrigMask = Mask;
8164     unsigned TZ = countTrailingZeros(Mask);
8165     if ((Inst.getOperand(0).getImm() & 1) == 0) {
8166       assert(Mask && TZ <= 3 && "illegal IT mask value!");
8167       Mask ^= (0xE << TZ) & 0xF;
8168     }
8169     MO.setImm(Mask);
8170
8171     // Set up the IT block state according to the IT instruction we just
8172     // matched.
8173     assert(!inITBlock() && "nested IT blocks?!");
8174     ITState.Cond = ARMCC::CondCodes(Inst.getOperand(0).getImm());
8175     ITState.Mask = OrigMask; // Use the original mask, not the updated one.
8176     ITState.CurPosition = 0;
8177     ITState.FirstCond = true;
8178     break;
8179   }
8180   case ARM::t2LSLrr:
8181   case ARM::t2LSRrr:
8182   case ARM::t2ASRrr:
8183   case ARM::t2SBCrr:
8184   case ARM::t2RORrr:
8185   case ARM::t2BICrr:
8186   {
8187     // Assemblers should use the narrow encodings of these instructions when permissible.
8188     if ((isARMLowRegister(Inst.getOperand(1).getReg()) &&
8189          isARMLowRegister(Inst.getOperand(2).getReg())) &&
8190         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
8191         ((!inITBlock() && Inst.getOperand(5).getReg() == ARM::CPSR) ||
8192          (inITBlock() && Inst.getOperand(5).getReg() != ARM::CPSR)) &&
8193         (!static_cast<ARMOperand &>(*Operands[3]).isToken() ||
8194          !static_cast<ARMOperand &>(*Operands[3]).getToken().equals_lower(
8195              ".w"))) {
8196       unsigned NewOpc;
8197       switch (Inst.getOpcode()) {
8198         default: llvm_unreachable("unexpected opcode");
8199         case ARM::t2LSLrr: NewOpc = ARM::tLSLrr; break;
8200         case ARM::t2LSRrr: NewOpc = ARM::tLSRrr; break;
8201         case ARM::t2ASRrr: NewOpc = ARM::tASRrr; break;
8202         case ARM::t2SBCrr: NewOpc = ARM::tSBC; break;
8203         case ARM::t2RORrr: NewOpc = ARM::tROR; break;
8204         case ARM::t2BICrr: NewOpc = ARM::tBIC; break;
8205       }
8206       MCInst TmpInst;
8207       TmpInst.setOpcode(NewOpc);
8208       TmpInst.addOperand(Inst.getOperand(0));
8209       TmpInst.addOperand(Inst.getOperand(5));
8210       TmpInst.addOperand(Inst.getOperand(1));
8211       TmpInst.addOperand(Inst.getOperand(2));
8212       TmpInst.addOperand(Inst.getOperand(3));
8213       TmpInst.addOperand(Inst.getOperand(4));
8214       Inst = TmpInst;
8215       return true;
8216     }
8217     return false;
8218   }
8219   case ARM::t2ANDrr:
8220   case ARM::t2EORrr:
8221   case ARM::t2ADCrr:
8222   case ARM::t2ORRrr:
8223   {
8224     // Assemblers should use the narrow encodings of these instructions when permissible.
8225     // These instructions are special in that they are commutable, so shorter encodings
8226     // are available more often.
8227     if ((isARMLowRegister(Inst.getOperand(1).getReg()) &&
8228          isARMLowRegister(Inst.getOperand(2).getReg())) &&
8229         (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() ||
8230          Inst.getOperand(0).getReg() == Inst.getOperand(2).getReg()) &&
8231         ((!inITBlock() && Inst.getOperand(5).getReg() == ARM::CPSR) ||
8232          (inITBlock() && Inst.getOperand(5).getReg() != ARM::CPSR)) &&
8233         (!static_cast<ARMOperand &>(*Operands[3]).isToken() ||
8234          !static_cast<ARMOperand &>(*Operands[3]).getToken().equals_lower(
8235              ".w"))) {
8236       unsigned NewOpc;
8237       switch (Inst.getOpcode()) {
8238         default: llvm_unreachable("unexpected opcode");
8239         case ARM::t2ADCrr: NewOpc = ARM::tADC; break;
8240         case ARM::t2ANDrr: NewOpc = ARM::tAND; break;
8241         case ARM::t2EORrr: NewOpc = ARM::tEOR; break;
8242         case ARM::t2ORRrr: NewOpc = ARM::tORR; break;
8243       }
8244       MCInst TmpInst;
8245       TmpInst.setOpcode(NewOpc);
8246       TmpInst.addOperand(Inst.getOperand(0));
8247       TmpInst.addOperand(Inst.getOperand(5));
8248       if (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg()) {
8249         TmpInst.addOperand(Inst.getOperand(1));
8250         TmpInst.addOperand(Inst.getOperand(2));
8251       } else {
8252         TmpInst.addOperand(Inst.getOperand(2));
8253         TmpInst.addOperand(Inst.getOperand(1));
8254       }
8255       TmpInst.addOperand(Inst.getOperand(3));
8256       TmpInst.addOperand(Inst.getOperand(4));
8257       Inst = TmpInst;
8258       return true;
8259     }
8260     return false;
8261   }
8262   }
8263   return false;
8264 }
8265
8266 unsigned ARMAsmParser::checkTargetMatchPredicate(MCInst &Inst) {
8267   // 16-bit thumb arithmetic instructions either require or preclude the 'S'
8268   // suffix depending on whether they're in an IT block or not.
8269   unsigned Opc = Inst.getOpcode();
8270   const MCInstrDesc &MCID = MII.get(Opc);
8271   if (MCID.TSFlags & ARMII::ThumbArithFlagSetting) {
8272     assert(MCID.hasOptionalDef() &&
8273            "optionally flag setting instruction missing optional def operand");
8274     assert(MCID.NumOperands == Inst.getNumOperands() &&
8275            "operand count mismatch!");
8276     // Find the optional-def operand (cc_out).
8277     unsigned OpNo;
8278     for (OpNo = 0;
8279          !MCID.OpInfo[OpNo].isOptionalDef() && OpNo < MCID.NumOperands;
8280          ++OpNo)
8281       ;
8282     // If we're parsing Thumb1, reject it completely.
8283     if (isThumbOne() && Inst.getOperand(OpNo).getReg() != ARM::CPSR)
8284       return Match_MnemonicFail;
8285     // If we're parsing Thumb2, which form is legal depends on whether we're
8286     // in an IT block.
8287     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() != ARM::CPSR &&
8288         !inITBlock())
8289       return Match_RequiresITBlock;
8290     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() == ARM::CPSR &&
8291         inITBlock())
8292       return Match_RequiresNotITBlock;
8293   }
8294   // Some high-register supporting Thumb1 encodings only allow both registers
8295   // to be from r0-r7 when in Thumb2.
8296   else if (Opc == ARM::tADDhirr && isThumbOne() && !hasV6MOps() &&
8297            isARMLowRegister(Inst.getOperand(1).getReg()) &&
8298            isARMLowRegister(Inst.getOperand(2).getReg()))
8299     return Match_RequiresThumb2;
8300   // Others only require ARMv6 or later.
8301   else if (Opc == ARM::tMOVr && isThumbOne() && !hasV6Ops() &&
8302            isARMLowRegister(Inst.getOperand(0).getReg()) &&
8303            isARMLowRegister(Inst.getOperand(1).getReg()))
8304     return Match_RequiresV6;
8305   return Match_Success;
8306 }
8307
8308 namespace llvm {
8309 template <> inline bool IsCPSRDead<MCInst>(MCInst *Instr) {
8310   return true; // In an assembly source, no need to second-guess
8311 }
8312 }
8313
8314 static const char *getSubtargetFeatureName(uint64_t Val);
8315 bool ARMAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
8316                                            OperandVector &Operands,
8317                                            MCStreamer &Out, uint64_t &ErrorInfo,
8318                                            bool MatchingInlineAsm) {
8319   MCInst Inst;
8320   unsigned MatchResult;
8321
8322   MatchResult = MatchInstructionImpl(Operands, Inst, ErrorInfo,
8323                                      MatchingInlineAsm);
8324   switch (MatchResult) {
8325   default: break;
8326   case Match_Success:
8327     // Context sensitive operand constraints aren't handled by the matcher,
8328     // so check them here.
8329     if (validateInstruction(Inst, Operands)) {
8330       // Still progress the IT block, otherwise one wrong condition causes
8331       // nasty cascading errors.
8332       forwardITPosition();
8333       return true;
8334     }
8335
8336     { // processInstruction() updates inITBlock state, we need to save it away
8337       bool wasInITBlock = inITBlock();
8338
8339       // Some instructions need post-processing to, for example, tweak which
8340       // encoding is selected. Loop on it while changes happen so the
8341       // individual transformations can chain off each other. E.g.,
8342       // tPOP(r8)->t2LDMIA_UPD(sp,r8)->t2STR_POST(sp,r8)
8343       while (processInstruction(Inst, Operands, Out))
8344         ;
8345
8346       // Only after the instruction is fully processed, we can validate it
8347       if (wasInITBlock && hasV8Ops() && isThumb() &&
8348           !isV8EligibleForIT(&Inst)) {
8349         Warning(IDLoc, "deprecated instruction in IT block");
8350       }
8351     }
8352
8353     // Only move forward at the very end so that everything in validate
8354     // and process gets a consistent answer about whether we're in an IT
8355     // block.
8356     forwardITPosition();
8357
8358     // ITasm is an ARM mode pseudo-instruction that just sets the ITblock and
8359     // doesn't actually encode.
8360     if (Inst.getOpcode() == ARM::ITasm)
8361       return false;
8362
8363     Inst.setLoc(IDLoc);
8364     Out.EmitInstruction(Inst, STI);
8365     return false;
8366   case Match_MissingFeature: {
8367     assert(ErrorInfo && "Unknown missing feature!");
8368     // Special case the error message for the very common case where only
8369     // a single subtarget feature is missing (Thumb vs. ARM, e.g.).
8370     std::string Msg = "instruction requires:";
8371     uint64_t Mask = 1;
8372     for (unsigned i = 0; i < (sizeof(ErrorInfo)*8-1); ++i) {
8373       if (ErrorInfo & Mask) {
8374         Msg += " ";
8375         Msg += getSubtargetFeatureName(ErrorInfo & Mask);
8376       }
8377       Mask <<= 1;
8378     }
8379     return Error(IDLoc, Msg);
8380   }
8381   case Match_InvalidOperand: {
8382     SMLoc ErrorLoc = IDLoc;
8383     if (ErrorInfo != ~0ULL) {
8384       if (ErrorInfo >= Operands.size())
8385         return Error(IDLoc, "too few operands for instruction");
8386
8387       ErrorLoc = ((ARMOperand &)*Operands[ErrorInfo]).getStartLoc();
8388       if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
8389     }
8390
8391     return Error(ErrorLoc, "invalid operand for instruction");
8392   }
8393   case Match_MnemonicFail:
8394     return Error(IDLoc, "invalid instruction",
8395                  ((ARMOperand &)*Operands[0]).getLocRange());
8396   case Match_RequiresNotITBlock:
8397     return Error(IDLoc, "flag setting instruction only valid outside IT block");
8398   case Match_RequiresITBlock:
8399     return Error(IDLoc, "instruction only valid inside IT block");
8400   case Match_RequiresV6:
8401     return Error(IDLoc, "instruction variant requires ARMv6 or later");
8402   case Match_RequiresThumb2:
8403     return Error(IDLoc, "instruction variant requires Thumb2");
8404   case Match_ImmRange0_15: {
8405     SMLoc ErrorLoc = ((ARMOperand &)*Operands[ErrorInfo]).getStartLoc();
8406     if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
8407     return Error(ErrorLoc, "immediate operand must be in the range [0,15]");
8408   }
8409   case Match_ImmRange0_239: {
8410     SMLoc ErrorLoc = ((ARMOperand &)*Operands[ErrorInfo]).getStartLoc();
8411     if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
8412     return Error(ErrorLoc, "immediate operand must be in the range [0,239]");
8413   }
8414   case Match_AlignedMemoryRequiresNone:
8415   case Match_DupAlignedMemoryRequiresNone:
8416   case Match_AlignedMemoryRequires16:
8417   case Match_DupAlignedMemoryRequires16:
8418   case Match_AlignedMemoryRequires32:
8419   case Match_DupAlignedMemoryRequires32:
8420   case Match_AlignedMemoryRequires64:
8421   case Match_DupAlignedMemoryRequires64:
8422   case Match_AlignedMemoryRequires64or128:
8423   case Match_DupAlignedMemoryRequires64or128:
8424   case Match_AlignedMemoryRequires64or128or256:
8425   {
8426     SMLoc ErrorLoc = ((ARMOperand &)*Operands[ErrorInfo]).getAlignmentLoc();
8427     if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
8428     switch (MatchResult) {
8429       default:
8430         llvm_unreachable("Missing Match_Aligned type");
8431       case Match_AlignedMemoryRequiresNone:
8432       case Match_DupAlignedMemoryRequiresNone:
8433         return Error(ErrorLoc, "alignment must be omitted");
8434       case Match_AlignedMemoryRequires16:
8435       case Match_DupAlignedMemoryRequires16:
8436         return Error(ErrorLoc, "alignment must be 16 or omitted");
8437       case Match_AlignedMemoryRequires32:
8438       case Match_DupAlignedMemoryRequires32:
8439         return Error(ErrorLoc, "alignment must be 32 or omitted");
8440       case Match_AlignedMemoryRequires64:
8441       case Match_DupAlignedMemoryRequires64:
8442         return Error(ErrorLoc, "alignment must be 64 or omitted");
8443       case Match_AlignedMemoryRequires64or128:
8444       case Match_DupAlignedMemoryRequires64or128:
8445         return Error(ErrorLoc, "alignment must be 64, 128 or omitted");
8446       case Match_AlignedMemoryRequires64or128or256:
8447         return Error(ErrorLoc, "alignment must be 64, 128, 256 or omitted");
8448     }
8449   }
8450   }
8451
8452   llvm_unreachable("Implement any new match types added!");
8453 }
8454
8455 /// parseDirective parses the arm specific directives
8456 bool ARMAsmParser::ParseDirective(AsmToken DirectiveID) {
8457   const MCObjectFileInfo::Environment Format =
8458     getContext().getObjectFileInfo()->getObjectFileType();
8459   bool IsMachO = Format == MCObjectFileInfo::IsMachO;
8460   bool IsCOFF = Format == MCObjectFileInfo::IsCOFF;
8461
8462   StringRef IDVal = DirectiveID.getIdentifier();
8463   if (IDVal == ".word")
8464     return parseLiteralValues(4, DirectiveID.getLoc());
8465   else if (IDVal == ".short" || IDVal == ".hword")
8466     return parseLiteralValues(2, DirectiveID.getLoc());
8467   else if (IDVal == ".thumb")
8468     return parseDirectiveThumb(DirectiveID.getLoc());
8469   else if (IDVal == ".arm")
8470     return parseDirectiveARM(DirectiveID.getLoc());
8471   else if (IDVal == ".thumb_func")
8472     return parseDirectiveThumbFunc(DirectiveID.getLoc());
8473   else if (IDVal == ".code")
8474     return parseDirectiveCode(DirectiveID.getLoc());
8475   else if (IDVal == ".syntax")
8476     return parseDirectiveSyntax(DirectiveID.getLoc());
8477   else if (IDVal == ".unreq")
8478     return parseDirectiveUnreq(DirectiveID.getLoc());
8479   else if (IDVal == ".fnend")
8480     return parseDirectiveFnEnd(DirectiveID.getLoc());
8481   else if (IDVal == ".cantunwind")
8482     return parseDirectiveCantUnwind(DirectiveID.getLoc());
8483   else if (IDVal == ".personality")
8484     return parseDirectivePersonality(DirectiveID.getLoc());
8485   else if (IDVal == ".handlerdata")
8486     return parseDirectiveHandlerData(DirectiveID.getLoc());
8487   else if (IDVal == ".setfp")
8488     return parseDirectiveSetFP(DirectiveID.getLoc());
8489   else if (IDVal == ".pad")
8490     return parseDirectivePad(DirectiveID.getLoc());
8491   else if (IDVal == ".save")
8492     return parseDirectiveRegSave(DirectiveID.getLoc(), false);
8493   else if (IDVal == ".vsave")
8494     return parseDirectiveRegSave(DirectiveID.getLoc(), true);
8495   else if (IDVal == ".ltorg" || IDVal == ".pool")
8496     return parseDirectiveLtorg(DirectiveID.getLoc());
8497   else if (IDVal == ".even")
8498     return parseDirectiveEven(DirectiveID.getLoc());
8499   else if (IDVal == ".personalityindex")
8500     return parseDirectivePersonalityIndex(DirectiveID.getLoc());
8501   else if (IDVal == ".unwind_raw")
8502     return parseDirectiveUnwindRaw(DirectiveID.getLoc());
8503   else if (IDVal == ".movsp")
8504     return parseDirectiveMovSP(DirectiveID.getLoc());
8505   else if (IDVal == ".arch_extension")
8506     return parseDirectiveArchExtension(DirectiveID.getLoc());
8507   else if (IDVal == ".align")
8508     return parseDirectiveAlign(DirectiveID.getLoc());
8509   else if (IDVal == ".thumb_set")
8510     return parseDirectiveThumbSet(DirectiveID.getLoc());
8511
8512   if (!IsMachO && !IsCOFF) {
8513     if (IDVal == ".arch")
8514       return parseDirectiveArch(DirectiveID.getLoc());
8515     else if (IDVal == ".cpu")
8516       return parseDirectiveCPU(DirectiveID.getLoc());
8517     else if (IDVal == ".eabi_attribute")
8518       return parseDirectiveEabiAttr(DirectiveID.getLoc());
8519     else if (IDVal == ".fpu")
8520       return parseDirectiveFPU(DirectiveID.getLoc());
8521     else if (IDVal == ".fnstart")
8522       return parseDirectiveFnStart(DirectiveID.getLoc());
8523     else if (IDVal == ".inst")
8524       return parseDirectiveInst(DirectiveID.getLoc());
8525     else if (IDVal == ".inst.n")
8526       return parseDirectiveInst(DirectiveID.getLoc(), 'n');
8527     else if (IDVal == ".inst.w")
8528       return parseDirectiveInst(DirectiveID.getLoc(), 'w');
8529     else if (IDVal == ".object_arch")
8530       return parseDirectiveObjectArch(DirectiveID.getLoc());
8531     else if (IDVal == ".tlsdescseq")
8532       return parseDirectiveTLSDescSeq(DirectiveID.getLoc());
8533   }
8534
8535   return true;
8536 }
8537
8538 /// parseLiteralValues
8539 ///  ::= .hword expression [, expression]*
8540 ///  ::= .short expression [, expression]*
8541 ///  ::= .word expression [, expression]*
8542 bool ARMAsmParser::parseLiteralValues(unsigned Size, SMLoc L) {
8543   MCAsmParser &Parser = getParser();
8544   if (getLexer().isNot(AsmToken::EndOfStatement)) {
8545     for (;;) {
8546       const MCExpr *Value;
8547       if (getParser().parseExpression(Value)) {
8548         Parser.eatToEndOfStatement();
8549         return false;
8550       }
8551
8552       getParser().getStreamer().EmitValue(Value, Size);
8553
8554       if (getLexer().is(AsmToken::EndOfStatement))
8555         break;
8556
8557       // FIXME: Improve diagnostic.
8558       if (getLexer().isNot(AsmToken::Comma)) {
8559         Error(L, "unexpected token in directive");
8560         return false;
8561       }
8562       Parser.Lex();
8563     }
8564   }
8565
8566   Parser.Lex();
8567   return false;
8568 }
8569
8570 /// parseDirectiveThumb
8571 ///  ::= .thumb
8572 bool ARMAsmParser::parseDirectiveThumb(SMLoc L) {
8573   MCAsmParser &Parser = getParser();
8574   if (getLexer().isNot(AsmToken::EndOfStatement)) {
8575     Error(L, "unexpected token in directive");
8576     return false;
8577   }
8578   Parser.Lex();
8579
8580   if (!hasThumb()) {
8581     Error(L, "target does not support Thumb mode");
8582     return false;
8583   }
8584
8585   if (!isThumb())
8586     SwitchMode();
8587
8588   getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
8589   return false;
8590 }
8591
8592 /// parseDirectiveARM
8593 ///  ::= .arm
8594 bool ARMAsmParser::parseDirectiveARM(SMLoc L) {
8595   MCAsmParser &Parser = getParser();
8596   if (getLexer().isNot(AsmToken::EndOfStatement)) {
8597     Error(L, "unexpected token in directive");
8598     return false;
8599   }
8600   Parser.Lex();
8601
8602   if (!hasARM()) {
8603     Error(L, "target does not support ARM mode");
8604     return false;
8605   }
8606
8607   if (isThumb())
8608     SwitchMode();
8609
8610   getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
8611   return false;
8612 }
8613
8614 void ARMAsmParser::onLabelParsed(MCSymbol *Symbol) {
8615   if (NextSymbolIsThumb) {
8616     getParser().getStreamer().EmitThumbFunc(Symbol);
8617     NextSymbolIsThumb = false;
8618   }
8619 }
8620
8621 /// parseDirectiveThumbFunc
8622 ///  ::= .thumbfunc symbol_name
8623 bool ARMAsmParser::parseDirectiveThumbFunc(SMLoc L) {
8624   MCAsmParser &Parser = getParser();
8625   const auto Format = getContext().getObjectFileInfo()->getObjectFileType();
8626   bool IsMachO = Format == MCObjectFileInfo::IsMachO;
8627
8628   // Darwin asm has (optionally) function name after .thumb_func direction
8629   // ELF doesn't
8630   if (IsMachO) {
8631     const AsmToken &Tok = Parser.getTok();
8632     if (Tok.isNot(AsmToken::EndOfStatement)) {
8633       if (Tok.isNot(AsmToken::Identifier) && Tok.isNot(AsmToken::String)) {
8634         Error(L, "unexpected token in .thumb_func directive");
8635         return false;
8636       }
8637
8638       MCSymbol *Func =
8639           getParser().getContext().GetOrCreateSymbol(Tok.getIdentifier());
8640       getParser().getStreamer().EmitThumbFunc(Func);
8641       Parser.Lex(); // Consume the identifier token.
8642       return false;
8643     }
8644   }
8645
8646   if (getLexer().isNot(AsmToken::EndOfStatement)) {
8647     Error(Parser.getTok().getLoc(), "unexpected token in directive");
8648     Parser.eatToEndOfStatement();
8649     return false;
8650   }
8651
8652   NextSymbolIsThumb = true;
8653   return false;
8654 }
8655
8656 /// parseDirectiveSyntax
8657 ///  ::= .syntax unified | divided
8658 bool ARMAsmParser::parseDirectiveSyntax(SMLoc L) {
8659   MCAsmParser &Parser = getParser();
8660   const AsmToken &Tok = Parser.getTok();
8661   if (Tok.isNot(AsmToken::Identifier)) {
8662     Error(L, "unexpected token in .syntax directive");
8663     return false;
8664   }
8665
8666   StringRef Mode = Tok.getString();
8667   if (Mode == "unified" || Mode == "UNIFIED") {
8668     Parser.Lex();
8669   } else if (Mode == "divided" || Mode == "DIVIDED") {
8670     Error(L, "'.syntax divided' arm asssembly not supported");
8671     return false;
8672   } else {
8673     Error(L, "unrecognized syntax mode in .syntax directive");
8674     return false;
8675   }
8676
8677   if (getLexer().isNot(AsmToken::EndOfStatement)) {
8678     Error(Parser.getTok().getLoc(), "unexpected token in directive");
8679     return false;
8680   }
8681   Parser.Lex();
8682
8683   // TODO tell the MC streamer the mode
8684   // getParser().getStreamer().Emit???();
8685   return false;
8686 }
8687
8688 /// parseDirectiveCode
8689 ///  ::= .code 16 | 32
8690 bool ARMAsmParser::parseDirectiveCode(SMLoc L) {
8691   MCAsmParser &Parser = getParser();
8692   const AsmToken &Tok = Parser.getTok();
8693   if (Tok.isNot(AsmToken::Integer)) {
8694     Error(L, "unexpected token in .code directive");
8695     return false;
8696   }
8697   int64_t Val = Parser.getTok().getIntVal();
8698   if (Val != 16 && Val != 32) {
8699     Error(L, "invalid operand to .code directive");
8700     return false;
8701   }
8702   Parser.Lex();
8703
8704   if (getLexer().isNot(AsmToken::EndOfStatement)) {
8705     Error(Parser.getTok().getLoc(), "unexpected token in directive");
8706     return false;
8707   }
8708   Parser.Lex();
8709
8710   if (Val == 16) {
8711     if (!hasThumb()) {
8712       Error(L, "target does not support Thumb mode");
8713       return false;
8714     }
8715
8716     if (!isThumb())
8717       SwitchMode();
8718     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
8719   } else {
8720     if (!hasARM()) {
8721       Error(L, "target does not support ARM mode");
8722       return false;
8723     }
8724
8725     if (isThumb())
8726       SwitchMode();
8727     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
8728   }
8729
8730   return false;
8731 }
8732
8733 /// parseDirectiveReq
8734 ///  ::= name .req registername
8735 bool ARMAsmParser::parseDirectiveReq(StringRef Name, SMLoc L) {
8736   MCAsmParser &Parser = getParser();
8737   Parser.Lex(); // Eat the '.req' token.
8738   unsigned Reg;
8739   SMLoc SRegLoc, ERegLoc;
8740   if (ParseRegister(Reg, SRegLoc, ERegLoc)) {
8741     Parser.eatToEndOfStatement();
8742     Error(SRegLoc, "register name expected");
8743     return false;
8744   }
8745
8746   // Shouldn't be anything else.
8747   if (Parser.getTok().isNot(AsmToken::EndOfStatement)) {
8748     Parser.eatToEndOfStatement();
8749     Error(Parser.getTok().getLoc(), "unexpected input in .req directive.");
8750     return false;
8751   }
8752
8753   Parser.Lex(); // Consume the EndOfStatement
8754
8755   if (!RegisterReqs.insert(std::make_pair(Name, Reg)).second) {
8756     Error(SRegLoc, "redefinition of '" + Name + "' does not match original.");
8757     return false;
8758   }
8759
8760   return false;
8761 }
8762
8763 /// parseDirectiveUneq
8764 ///  ::= .unreq registername
8765 bool ARMAsmParser::parseDirectiveUnreq(SMLoc L) {
8766   MCAsmParser &Parser = getParser();
8767   if (Parser.getTok().isNot(AsmToken::Identifier)) {
8768     Parser.eatToEndOfStatement();
8769     Error(L, "unexpected input in .unreq directive.");
8770     return false;
8771   }
8772   RegisterReqs.erase(Parser.getTok().getIdentifier().lower());
8773   Parser.Lex(); // Eat the identifier.
8774   return false;
8775 }
8776
8777 /// parseDirectiveArch
8778 ///  ::= .arch token
8779 bool ARMAsmParser::parseDirectiveArch(SMLoc L) {
8780   StringRef Arch = getParser().parseStringToEndOfStatement().trim();
8781
8782   unsigned ID = StringSwitch<unsigned>(Arch)
8783 #define ARM_ARCH_NAME(NAME, ID, DEFAULT_CPU_NAME, DEFAULT_CPU_ARCH) \
8784     .Case(NAME, ARM::ID)
8785 #define ARM_ARCH_ALIAS(NAME, ID) \
8786     .Case(NAME, ARM::ID)
8787 #include "MCTargetDesc/ARMArchName.def"
8788     .Default(ARM::INVALID_ARCH);
8789
8790   if (ID == ARM::INVALID_ARCH) {
8791     Error(L, "Unknown arch name");
8792     return false;
8793   }
8794
8795   getTargetStreamer().emitArch(ID);
8796   return false;
8797 }
8798
8799 /// parseDirectiveEabiAttr
8800 ///  ::= .eabi_attribute int, int [, "str"]
8801 ///  ::= .eabi_attribute Tag_name, int [, "str"]
8802 bool ARMAsmParser::parseDirectiveEabiAttr(SMLoc L) {
8803   MCAsmParser &Parser = getParser();
8804   int64_t Tag;
8805   SMLoc TagLoc;
8806   TagLoc = Parser.getTok().getLoc();
8807   if (Parser.getTok().is(AsmToken::Identifier)) {
8808     StringRef Name = Parser.getTok().getIdentifier();
8809     Tag = ARMBuildAttrs::AttrTypeFromString(Name);
8810     if (Tag == -1) {
8811       Error(TagLoc, "attribute name not recognised: " + Name);
8812       Parser.eatToEndOfStatement();
8813       return false;
8814     }
8815     Parser.Lex();
8816   } else {
8817     const MCExpr *AttrExpr;
8818
8819     TagLoc = Parser.getTok().getLoc();
8820     if (Parser.parseExpression(AttrExpr)) {
8821       Parser.eatToEndOfStatement();
8822       return false;
8823     }
8824
8825     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(AttrExpr);
8826     if (!CE) {
8827       Error(TagLoc, "expected numeric constant");
8828       Parser.eatToEndOfStatement();
8829       return false;
8830     }
8831
8832     Tag = CE->getValue();
8833   }
8834
8835   if (Parser.getTok().isNot(AsmToken::Comma)) {
8836     Error(Parser.getTok().getLoc(), "comma expected");
8837     Parser.eatToEndOfStatement();
8838     return false;
8839   }
8840   Parser.Lex(); // skip comma
8841
8842   StringRef StringValue = "";
8843   bool IsStringValue = false;
8844
8845   int64_t IntegerValue = 0;
8846   bool IsIntegerValue = false;
8847
8848   if (Tag == ARMBuildAttrs::CPU_raw_name || Tag == ARMBuildAttrs::CPU_name)
8849     IsStringValue = true;
8850   else if (Tag == ARMBuildAttrs::compatibility) {
8851     IsStringValue = true;
8852     IsIntegerValue = true;
8853   } else if (Tag < 32 || Tag % 2 == 0)
8854     IsIntegerValue = true;
8855   else if (Tag % 2 == 1)
8856     IsStringValue = true;
8857   else
8858     llvm_unreachable("invalid tag type");
8859
8860   if (IsIntegerValue) {
8861     const MCExpr *ValueExpr;
8862     SMLoc ValueExprLoc = Parser.getTok().getLoc();
8863     if (Parser.parseExpression(ValueExpr)) {
8864       Parser.eatToEndOfStatement();
8865       return false;
8866     }
8867
8868     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ValueExpr);
8869     if (!CE) {
8870       Error(ValueExprLoc, "expected numeric constant");
8871       Parser.eatToEndOfStatement();
8872       return false;
8873     }
8874
8875     IntegerValue = CE->getValue();
8876   }
8877
8878   if (Tag == ARMBuildAttrs::compatibility) {
8879     if (Parser.getTok().isNot(AsmToken::Comma))
8880       IsStringValue = false;
8881     else
8882       Parser.Lex();
8883   }
8884
8885   if (IsStringValue) {
8886     if (Parser.getTok().isNot(AsmToken::String)) {
8887       Error(Parser.getTok().getLoc(), "bad string constant");
8888       Parser.eatToEndOfStatement();
8889       return false;
8890     }
8891
8892     StringValue = Parser.getTok().getStringContents();
8893     Parser.Lex();
8894   }
8895
8896   if (IsIntegerValue && IsStringValue) {
8897     assert(Tag == ARMBuildAttrs::compatibility);
8898     getTargetStreamer().emitIntTextAttribute(Tag, IntegerValue, StringValue);
8899   } else if (IsIntegerValue)
8900     getTargetStreamer().emitAttribute(Tag, IntegerValue);
8901   else if (IsStringValue)
8902     getTargetStreamer().emitTextAttribute(Tag, StringValue);
8903   return false;
8904 }
8905
8906 /// parseDirectiveCPU
8907 ///  ::= .cpu str
8908 bool ARMAsmParser::parseDirectiveCPU(SMLoc L) {
8909   StringRef CPU = getParser().parseStringToEndOfStatement().trim();
8910   getTargetStreamer().emitTextAttribute(ARMBuildAttrs::CPU_name, CPU);
8911   return false;
8912 }
8913
8914 // FIXME: This is duplicated in getARMFPUFeatures() in
8915 // tools/clang/lib/Driver/Tools.cpp
8916 static const struct {
8917   const unsigned Fpu;
8918   const uint64_t Enabled;
8919   const uint64_t Disabled;
8920 } Fpus[] = {
8921       {ARM::VFP, ARM::FeatureVFP2, ARM::FeatureNEON},
8922       {ARM::VFPV2, ARM::FeatureVFP2, ARM::FeatureNEON},
8923       {ARM::VFPV3, ARM::FeatureVFP3, ARM::FeatureNEON},
8924       {ARM::VFPV3_D16, ARM::FeatureVFP3 | ARM::FeatureD16, ARM::FeatureNEON},
8925       {ARM::VFPV4, ARM::FeatureVFP4, ARM::FeatureNEON},
8926       {ARM::VFPV4_D16, ARM::FeatureVFP4 | ARM::FeatureD16, ARM::FeatureNEON},
8927       {ARM::FPV5_D16, ARM::FeatureFPARMv8 | ARM::FeatureD16,
8928        ARM::FeatureNEON | ARM::FeatureCrypto},
8929       {ARM::FP_ARMV8, ARM::FeatureFPARMv8,
8930        ARM::FeatureNEON | ARM::FeatureCrypto},
8931       {ARM::NEON, ARM::FeatureNEON, 0},
8932       {ARM::NEON_VFPV4, ARM::FeatureVFP4 | ARM::FeatureNEON, 0},
8933       {ARM::NEON_FP_ARMV8, ARM::FeatureFPARMv8 | ARM::FeatureNEON,
8934        ARM::FeatureCrypto},
8935       {ARM::CRYPTO_NEON_FP_ARMV8,
8936        ARM::FeatureFPARMv8 | ARM::FeatureNEON | ARM::FeatureCrypto, 0},
8937       {ARM::SOFTVFP, 0, 0},
8938 };
8939
8940 /// parseDirectiveFPU
8941 ///  ::= .fpu str
8942 bool ARMAsmParser::parseDirectiveFPU(SMLoc L) {
8943   StringRef FPU = getParser().parseStringToEndOfStatement().trim();
8944
8945   unsigned ID = StringSwitch<unsigned>(FPU)
8946 #define ARM_FPU_NAME(NAME, ID) .Case(NAME, ARM::ID)
8947 #include "ARMFPUName.def"
8948     .Default(ARM::INVALID_FPU);
8949
8950   if (ID == ARM::INVALID_FPU) {
8951     Error(L, "Unknown FPU name");
8952     return false;
8953   }
8954
8955   for (const auto &Fpu : Fpus) {
8956     if (Fpu.Fpu != ID)
8957       continue;
8958
8959     // Need to toggle features that should be on but are off and that
8960     // should off but are on.
8961     uint64_t Toggle = (Fpu.Enabled & ~STI.getFeatureBits()) |
8962                       (Fpu.Disabled & STI.getFeatureBits());
8963     setAvailableFeatures(ComputeAvailableFeatures(STI.ToggleFeature(Toggle)));
8964     break;
8965   }
8966
8967   getTargetStreamer().emitFPU(ID);
8968   return false;
8969 }
8970
8971 /// parseDirectiveFnStart
8972 ///  ::= .fnstart
8973 bool ARMAsmParser::parseDirectiveFnStart(SMLoc L) {
8974   if (UC.hasFnStart()) {
8975     Error(L, ".fnstart starts before the end of previous one");
8976     UC.emitFnStartLocNotes();
8977     return false;
8978   }
8979
8980   // Reset the unwind directives parser state
8981   UC.reset();
8982
8983   getTargetStreamer().emitFnStart();
8984
8985   UC.recordFnStart(L);
8986   return false;
8987 }
8988
8989 /// parseDirectiveFnEnd
8990 ///  ::= .fnend
8991 bool ARMAsmParser::parseDirectiveFnEnd(SMLoc L) {
8992   // Check the ordering of unwind directives
8993   if (!UC.hasFnStart()) {
8994     Error(L, ".fnstart must precede .fnend directive");
8995     return false;
8996   }
8997
8998   // Reset the unwind directives parser state
8999   getTargetStreamer().emitFnEnd();
9000
9001   UC.reset();
9002   return false;
9003 }
9004
9005 /// parseDirectiveCantUnwind
9006 ///  ::= .cantunwind
9007 bool ARMAsmParser::parseDirectiveCantUnwind(SMLoc L) {
9008   UC.recordCantUnwind(L);
9009
9010   // Check the ordering of unwind directives
9011   if (!UC.hasFnStart()) {
9012     Error(L, ".fnstart must precede .cantunwind directive");
9013     return false;
9014   }
9015   if (UC.hasHandlerData()) {
9016     Error(L, ".cantunwind can't be used with .handlerdata directive");
9017     UC.emitHandlerDataLocNotes();
9018     return false;
9019   }
9020   if (UC.hasPersonality()) {
9021     Error(L, ".cantunwind can't be used with .personality directive");
9022     UC.emitPersonalityLocNotes();
9023     return false;
9024   }
9025
9026   getTargetStreamer().emitCantUnwind();
9027   return false;
9028 }
9029
9030 /// parseDirectivePersonality
9031 ///  ::= .personality name
9032 bool ARMAsmParser::parseDirectivePersonality(SMLoc L) {
9033   MCAsmParser &Parser = getParser();
9034   bool HasExistingPersonality = UC.hasPersonality();
9035
9036   UC.recordPersonality(L);
9037
9038   // Check the ordering of unwind directives
9039   if (!UC.hasFnStart()) {
9040     Error(L, ".fnstart must precede .personality directive");
9041     return false;
9042   }
9043   if (UC.cantUnwind()) {
9044     Error(L, ".personality can't be used with .cantunwind directive");
9045     UC.emitCantUnwindLocNotes();
9046     return false;
9047   }
9048   if (UC.hasHandlerData()) {
9049     Error(L, ".personality must precede .handlerdata directive");
9050     UC.emitHandlerDataLocNotes();
9051     return false;
9052   }
9053   if (HasExistingPersonality) {
9054     Parser.eatToEndOfStatement();
9055     Error(L, "multiple personality directives");
9056     UC.emitPersonalityLocNotes();
9057     return false;
9058   }
9059
9060   // Parse the name of the personality routine
9061   if (Parser.getTok().isNot(AsmToken::Identifier)) {
9062     Parser.eatToEndOfStatement();
9063     Error(L, "unexpected input in .personality directive.");
9064     return false;
9065   }
9066   StringRef Name(Parser.getTok().getIdentifier());
9067   Parser.Lex();
9068
9069   MCSymbol *PR = getParser().getContext().GetOrCreateSymbol(Name);
9070   getTargetStreamer().emitPersonality(PR);
9071   return false;
9072 }
9073
9074 /// parseDirectiveHandlerData
9075 ///  ::= .handlerdata
9076 bool ARMAsmParser::parseDirectiveHandlerData(SMLoc L) {
9077   UC.recordHandlerData(L);
9078
9079   // Check the ordering of unwind directives
9080   if (!UC.hasFnStart()) {
9081     Error(L, ".fnstart must precede .personality directive");
9082     return false;
9083   }
9084   if (UC.cantUnwind()) {
9085     Error(L, ".handlerdata can't be used with .cantunwind directive");
9086     UC.emitCantUnwindLocNotes();
9087     return false;
9088   }
9089
9090   getTargetStreamer().emitHandlerData();
9091   return false;
9092 }
9093
9094 /// parseDirectiveSetFP
9095 ///  ::= .setfp fpreg, spreg [, offset]
9096 bool ARMAsmParser::parseDirectiveSetFP(SMLoc L) {
9097   MCAsmParser &Parser = getParser();
9098   // Check the ordering of unwind directives
9099   if (!UC.hasFnStart()) {
9100     Error(L, ".fnstart must precede .setfp directive");
9101     return false;
9102   }
9103   if (UC.hasHandlerData()) {
9104     Error(L, ".setfp must precede .handlerdata directive");
9105     return false;
9106   }
9107
9108   // Parse fpreg
9109   SMLoc FPRegLoc = Parser.getTok().getLoc();
9110   int FPReg = tryParseRegister();
9111   if (FPReg == -1) {
9112     Error(FPRegLoc, "frame pointer register expected");
9113     return false;
9114   }
9115
9116   // Consume comma
9117   if (Parser.getTok().isNot(AsmToken::Comma)) {
9118     Error(Parser.getTok().getLoc(), "comma expected");
9119     return false;
9120   }
9121   Parser.Lex(); // skip comma
9122
9123   // Parse spreg
9124   SMLoc SPRegLoc = Parser.getTok().getLoc();
9125   int SPReg = tryParseRegister();
9126   if (SPReg == -1) {
9127     Error(SPRegLoc, "stack pointer register expected");
9128     return false;
9129   }
9130
9131   if (SPReg != ARM::SP && SPReg != UC.getFPReg()) {
9132     Error(SPRegLoc, "register should be either $sp or the latest fp register");
9133     return false;
9134   }
9135
9136   // Update the frame pointer register
9137   UC.saveFPReg(FPReg);
9138
9139   // Parse offset
9140   int64_t Offset = 0;
9141   if (Parser.getTok().is(AsmToken::Comma)) {
9142     Parser.Lex(); // skip comma
9143
9144     if (Parser.getTok().isNot(AsmToken::Hash) &&
9145         Parser.getTok().isNot(AsmToken::Dollar)) {
9146       Error(Parser.getTok().getLoc(), "'#' expected");
9147       return false;
9148     }
9149     Parser.Lex(); // skip hash token.
9150
9151     const MCExpr *OffsetExpr;
9152     SMLoc ExLoc = Parser.getTok().getLoc();
9153     SMLoc EndLoc;
9154     if (getParser().parseExpression(OffsetExpr, EndLoc)) {
9155       Error(ExLoc, "malformed setfp offset");
9156       return false;
9157     }
9158     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9159     if (!CE) {
9160       Error(ExLoc, "setfp offset must be an immediate");
9161       return false;
9162     }
9163
9164     Offset = CE->getValue();
9165   }
9166
9167   getTargetStreamer().emitSetFP(static_cast<unsigned>(FPReg),
9168                                 static_cast<unsigned>(SPReg), Offset);
9169   return false;
9170 }
9171
9172 /// parseDirective
9173 ///  ::= .pad offset
9174 bool ARMAsmParser::parseDirectivePad(SMLoc L) {
9175   MCAsmParser &Parser = getParser();
9176   // Check the ordering of unwind directives
9177   if (!UC.hasFnStart()) {
9178     Error(L, ".fnstart must precede .pad directive");
9179     return false;
9180   }
9181   if (UC.hasHandlerData()) {
9182     Error(L, ".pad must precede .handlerdata directive");
9183     return false;
9184   }
9185
9186   // Parse the offset
9187   if (Parser.getTok().isNot(AsmToken::Hash) &&
9188       Parser.getTok().isNot(AsmToken::Dollar)) {
9189     Error(Parser.getTok().getLoc(), "'#' expected");
9190     return false;
9191   }
9192   Parser.Lex(); // skip hash token.
9193
9194   const MCExpr *OffsetExpr;
9195   SMLoc ExLoc = Parser.getTok().getLoc();
9196   SMLoc EndLoc;
9197   if (getParser().parseExpression(OffsetExpr, EndLoc)) {
9198     Error(ExLoc, "malformed pad offset");
9199     return false;
9200   }
9201   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9202   if (!CE) {
9203     Error(ExLoc, "pad offset must be an immediate");
9204     return false;
9205   }
9206
9207   getTargetStreamer().emitPad(CE->getValue());
9208   return false;
9209 }
9210
9211 /// parseDirectiveRegSave
9212 ///  ::= .save  { registers }
9213 ///  ::= .vsave { registers }
9214 bool ARMAsmParser::parseDirectiveRegSave(SMLoc L, bool IsVector) {
9215   // Check the ordering of unwind directives
9216   if (!UC.hasFnStart()) {
9217     Error(L, ".fnstart must precede .save or .vsave directives");
9218     return false;
9219   }
9220   if (UC.hasHandlerData()) {
9221     Error(L, ".save or .vsave must precede .handlerdata directive");
9222     return false;
9223   }
9224
9225   // RAII object to make sure parsed operands are deleted.
9226   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> Operands;
9227
9228   // Parse the register list
9229   if (parseRegisterList(Operands))
9230     return false;
9231   ARMOperand &Op = (ARMOperand &)*Operands[0];
9232   if (!IsVector && !Op.isRegList()) {
9233     Error(L, ".save expects GPR registers");
9234     return false;
9235   }
9236   if (IsVector && !Op.isDPRRegList()) {
9237     Error(L, ".vsave expects DPR registers");
9238     return false;
9239   }
9240
9241   getTargetStreamer().emitRegSave(Op.getRegList(), IsVector);
9242   return false;
9243 }
9244
9245 /// parseDirectiveInst
9246 ///  ::= .inst opcode [, ...]
9247 ///  ::= .inst.n opcode [, ...]
9248 ///  ::= .inst.w opcode [, ...]
9249 bool ARMAsmParser::parseDirectiveInst(SMLoc Loc, char Suffix) {
9250   MCAsmParser &Parser = getParser();
9251   int Width;
9252
9253   if (isThumb()) {
9254     switch (Suffix) {
9255     case 'n':
9256       Width = 2;
9257       break;
9258     case 'w':
9259       Width = 4;
9260       break;
9261     default:
9262       Parser.eatToEndOfStatement();
9263       Error(Loc, "cannot determine Thumb instruction size, "
9264                  "use inst.n/inst.w instead");
9265       return false;
9266     }
9267   } else {
9268     if (Suffix) {
9269       Parser.eatToEndOfStatement();
9270       Error(Loc, "width suffixes are invalid in ARM mode");
9271       return false;
9272     }
9273     Width = 4;
9274   }
9275
9276   if (getLexer().is(AsmToken::EndOfStatement)) {
9277     Parser.eatToEndOfStatement();
9278     Error(Loc, "expected expression following directive");
9279     return false;
9280   }
9281
9282   for (;;) {
9283     const MCExpr *Expr;
9284
9285     if (getParser().parseExpression(Expr)) {
9286       Error(Loc, "expected expression");
9287       return false;
9288     }
9289
9290     const MCConstantExpr *Value = dyn_cast_or_null<MCConstantExpr>(Expr);
9291     if (!Value) {
9292       Error(Loc, "expected constant expression");
9293       return false;
9294     }
9295
9296     switch (Width) {
9297     case 2:
9298       if (Value->getValue() > 0xffff) {
9299         Error(Loc, "inst.n operand is too big, use inst.w instead");
9300         return false;
9301       }
9302       break;
9303     case 4:
9304       if (Value->getValue() > 0xffffffff) {
9305         Error(Loc,
9306               StringRef(Suffix ? "inst.w" : "inst") + " operand is too big");
9307         return false;
9308       }
9309       break;
9310     default:
9311       llvm_unreachable("only supported widths are 2 and 4");
9312     }
9313
9314     getTargetStreamer().emitInst(Value->getValue(), Suffix);
9315
9316     if (getLexer().is(AsmToken::EndOfStatement))
9317       break;
9318
9319     if (getLexer().isNot(AsmToken::Comma)) {
9320       Error(Loc, "unexpected token in directive");
9321       return false;
9322     }
9323
9324     Parser.Lex();
9325   }
9326
9327   Parser.Lex();
9328   return false;
9329 }
9330
9331 /// parseDirectiveLtorg
9332 ///  ::= .ltorg | .pool
9333 bool ARMAsmParser::parseDirectiveLtorg(SMLoc L) {
9334   getTargetStreamer().emitCurrentConstantPool();
9335   return false;
9336 }
9337
9338 bool ARMAsmParser::parseDirectiveEven(SMLoc L) {
9339   const MCSection *Section = getStreamer().getCurrentSection().first;
9340
9341   if (getLexer().isNot(AsmToken::EndOfStatement)) {
9342     TokError("unexpected token in directive");
9343     return false;
9344   }
9345
9346   if (!Section) {
9347     getStreamer().InitSections(false);
9348     Section = getStreamer().getCurrentSection().first;
9349   }
9350
9351   assert(Section && "must have section to emit alignment");
9352   if (Section->UseCodeAlign())
9353     getStreamer().EmitCodeAlignment(2);
9354   else
9355     getStreamer().EmitValueToAlignment(2);
9356
9357   return false;
9358 }
9359
9360 /// parseDirectivePersonalityIndex
9361 ///   ::= .personalityindex index
9362 bool ARMAsmParser::parseDirectivePersonalityIndex(SMLoc L) {
9363   MCAsmParser &Parser = getParser();
9364   bool HasExistingPersonality = UC.hasPersonality();
9365
9366   UC.recordPersonalityIndex(L);
9367
9368   if (!UC.hasFnStart()) {
9369     Parser.eatToEndOfStatement();
9370     Error(L, ".fnstart must precede .personalityindex directive");
9371     return false;
9372   }
9373   if (UC.cantUnwind()) {
9374     Parser.eatToEndOfStatement();
9375     Error(L, ".personalityindex cannot be used with .cantunwind");
9376     UC.emitCantUnwindLocNotes();
9377     return false;
9378   }
9379   if (UC.hasHandlerData()) {
9380     Parser.eatToEndOfStatement();
9381     Error(L, ".personalityindex must precede .handlerdata directive");
9382     UC.emitHandlerDataLocNotes();
9383     return false;
9384   }
9385   if (HasExistingPersonality) {
9386     Parser.eatToEndOfStatement();
9387     Error(L, "multiple personality directives");
9388     UC.emitPersonalityLocNotes();
9389     return false;
9390   }
9391
9392   const MCExpr *IndexExpression;
9393   SMLoc IndexLoc = Parser.getTok().getLoc();
9394   if (Parser.parseExpression(IndexExpression)) {
9395     Parser.eatToEndOfStatement();
9396     return false;
9397   }
9398
9399   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(IndexExpression);
9400   if (!CE) {
9401     Parser.eatToEndOfStatement();
9402     Error(IndexLoc, "index must be a constant number");
9403     return false;
9404   }
9405   if (CE->getValue() < 0 ||
9406       CE->getValue() >= ARM::EHABI::NUM_PERSONALITY_INDEX) {
9407     Parser.eatToEndOfStatement();
9408     Error(IndexLoc, "personality routine index should be in range [0-3]");
9409     return false;
9410   }
9411
9412   getTargetStreamer().emitPersonalityIndex(CE->getValue());
9413   return false;
9414 }
9415
9416 /// parseDirectiveUnwindRaw
9417 ///   ::= .unwind_raw offset, opcode [, opcode...]
9418 bool ARMAsmParser::parseDirectiveUnwindRaw(SMLoc L) {
9419   MCAsmParser &Parser = getParser();
9420   if (!UC.hasFnStart()) {
9421     Parser.eatToEndOfStatement();
9422     Error(L, ".fnstart must precede .unwind_raw directives");
9423     return false;
9424   }
9425
9426   int64_t StackOffset;
9427
9428   const MCExpr *OffsetExpr;
9429   SMLoc OffsetLoc = getLexer().getLoc();
9430   if (getLexer().is(AsmToken::EndOfStatement) ||
9431       getParser().parseExpression(OffsetExpr)) {
9432     Error(OffsetLoc, "expected expression");
9433     Parser.eatToEndOfStatement();
9434     return false;
9435   }
9436
9437   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9438   if (!CE) {
9439     Error(OffsetLoc, "offset must be a constant");
9440     Parser.eatToEndOfStatement();
9441     return false;
9442   }
9443
9444   StackOffset = CE->getValue();
9445
9446   if (getLexer().isNot(AsmToken::Comma)) {
9447     Error(getLexer().getLoc(), "expected comma");
9448     Parser.eatToEndOfStatement();
9449     return false;
9450   }
9451   Parser.Lex();
9452
9453   SmallVector<uint8_t, 16> Opcodes;
9454   for (;;) {
9455     const MCExpr *OE;
9456
9457     SMLoc OpcodeLoc = getLexer().getLoc();
9458     if (getLexer().is(AsmToken::EndOfStatement) || Parser.parseExpression(OE)) {
9459       Error(OpcodeLoc, "expected opcode expression");
9460       Parser.eatToEndOfStatement();
9461       return false;
9462     }
9463
9464     const MCConstantExpr *OC = dyn_cast<MCConstantExpr>(OE);
9465     if (!OC) {
9466       Error(OpcodeLoc, "opcode value must be a constant");
9467       Parser.eatToEndOfStatement();
9468       return false;
9469     }
9470
9471     const int64_t Opcode = OC->getValue();
9472     if (Opcode & ~0xff) {
9473       Error(OpcodeLoc, "invalid opcode");
9474       Parser.eatToEndOfStatement();
9475       return false;
9476     }
9477
9478     Opcodes.push_back(uint8_t(Opcode));
9479
9480     if (getLexer().is(AsmToken::EndOfStatement))
9481       break;
9482
9483     if (getLexer().isNot(AsmToken::Comma)) {
9484       Error(getLexer().getLoc(), "unexpected token in directive");
9485       Parser.eatToEndOfStatement();
9486       return false;
9487     }
9488
9489     Parser.Lex();
9490   }
9491
9492   getTargetStreamer().emitUnwindRaw(StackOffset, Opcodes);
9493
9494   Parser.Lex();
9495   return false;
9496 }
9497
9498 /// parseDirectiveTLSDescSeq
9499 ///   ::= .tlsdescseq tls-variable
9500 bool ARMAsmParser::parseDirectiveTLSDescSeq(SMLoc L) {
9501   MCAsmParser &Parser = getParser();
9502
9503   if (getLexer().isNot(AsmToken::Identifier)) {
9504     TokError("expected variable after '.tlsdescseq' directive");
9505     Parser.eatToEndOfStatement();
9506     return false;
9507   }
9508
9509   const MCSymbolRefExpr *SRE =
9510     MCSymbolRefExpr::Create(Parser.getTok().getIdentifier(),
9511                             MCSymbolRefExpr::VK_ARM_TLSDESCSEQ, getContext());
9512   Lex();
9513
9514   if (getLexer().isNot(AsmToken::EndOfStatement)) {
9515     Error(Parser.getTok().getLoc(), "unexpected token");
9516     Parser.eatToEndOfStatement();
9517     return false;
9518   }
9519
9520   getTargetStreamer().AnnotateTLSDescriptorSequence(SRE);
9521   return false;
9522 }
9523
9524 /// parseDirectiveMovSP
9525 ///  ::= .movsp reg [, #offset]
9526 bool ARMAsmParser::parseDirectiveMovSP(SMLoc L) {
9527   MCAsmParser &Parser = getParser();
9528   if (!UC.hasFnStart()) {
9529     Parser.eatToEndOfStatement();
9530     Error(L, ".fnstart must precede .movsp directives");
9531     return false;
9532   }
9533   if (UC.getFPReg() != ARM::SP) {
9534     Parser.eatToEndOfStatement();
9535     Error(L, "unexpected .movsp directive");
9536     return false;
9537   }
9538
9539   SMLoc SPRegLoc = Parser.getTok().getLoc();
9540   int SPReg = tryParseRegister();
9541   if (SPReg == -1) {
9542     Parser.eatToEndOfStatement();
9543     Error(SPRegLoc, "register expected");
9544     return false;
9545   }
9546
9547   if (SPReg == ARM::SP || SPReg == ARM::PC) {
9548     Parser.eatToEndOfStatement();
9549     Error(SPRegLoc, "sp and pc are not permitted in .movsp directive");
9550     return false;
9551   }
9552
9553   int64_t Offset = 0;
9554   if (Parser.getTok().is(AsmToken::Comma)) {
9555     Parser.Lex();
9556
9557     if (Parser.getTok().isNot(AsmToken::Hash)) {
9558       Error(Parser.getTok().getLoc(), "expected #constant");
9559       Parser.eatToEndOfStatement();
9560       return false;
9561     }
9562     Parser.Lex();
9563
9564     const MCExpr *OffsetExpr;
9565     SMLoc OffsetLoc = Parser.getTok().getLoc();
9566     if (Parser.parseExpression(OffsetExpr)) {
9567       Parser.eatToEndOfStatement();
9568       Error(OffsetLoc, "malformed offset expression");
9569       return false;
9570     }
9571
9572     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9573     if (!CE) {
9574       Parser.eatToEndOfStatement();
9575       Error(OffsetLoc, "offset must be an immediate constant");
9576       return false;
9577     }
9578
9579     Offset = CE->getValue();
9580   }
9581
9582   getTargetStreamer().emitMovSP(SPReg, Offset);
9583   UC.saveFPReg(SPReg);
9584
9585   return false;
9586 }
9587
9588 /// parseDirectiveObjectArch
9589 ///   ::= .object_arch name
9590 bool ARMAsmParser::parseDirectiveObjectArch(SMLoc L) {
9591   MCAsmParser &Parser = getParser();
9592   if (getLexer().isNot(AsmToken::Identifier)) {
9593     Error(getLexer().getLoc(), "unexpected token");
9594     Parser.eatToEndOfStatement();
9595     return false;
9596   }
9597
9598   StringRef Arch = Parser.getTok().getString();
9599   SMLoc ArchLoc = Parser.getTok().getLoc();
9600   getLexer().Lex();
9601
9602   unsigned ID = StringSwitch<unsigned>(Arch)
9603 #define ARM_ARCH_NAME(NAME, ID, DEFAULT_CPU_NAME, DEFAULT_CPU_ARCH) \
9604     .Case(NAME, ARM::ID)
9605 #define ARM_ARCH_ALIAS(NAME, ID) \
9606     .Case(NAME, ARM::ID)
9607 #include "MCTargetDesc/ARMArchName.def"
9608 #undef ARM_ARCH_NAME
9609 #undef ARM_ARCH_ALIAS
9610     .Default(ARM::INVALID_ARCH);
9611
9612   if (ID == ARM::INVALID_ARCH) {
9613     Error(ArchLoc, "unknown architecture '" + Arch + "'");
9614     Parser.eatToEndOfStatement();
9615     return false;
9616   }
9617
9618   getTargetStreamer().emitObjectArch(ID);
9619
9620   if (getLexer().isNot(AsmToken::EndOfStatement)) {
9621     Error(getLexer().getLoc(), "unexpected token");
9622     Parser.eatToEndOfStatement();
9623   }
9624
9625   return false;
9626 }
9627
9628 /// parseDirectiveAlign
9629 ///   ::= .align
9630 bool ARMAsmParser::parseDirectiveAlign(SMLoc L) {
9631   // NOTE: if this is not the end of the statement, fall back to the target
9632   // agnostic handling for this directive which will correctly handle this.
9633   if (getLexer().isNot(AsmToken::EndOfStatement))
9634     return true;
9635
9636   // '.align' is target specifically handled to mean 2**2 byte alignment.
9637   if (getStreamer().getCurrentSection().first->UseCodeAlign())
9638     getStreamer().EmitCodeAlignment(4, 0);
9639   else
9640     getStreamer().EmitValueToAlignment(4, 0, 1, 0);
9641
9642   return false;
9643 }
9644
9645 /// parseDirectiveThumbSet
9646 ///  ::= .thumb_set name, value
9647 bool ARMAsmParser::parseDirectiveThumbSet(SMLoc L) {
9648   MCAsmParser &Parser = getParser();
9649
9650   StringRef Name;
9651   if (Parser.parseIdentifier(Name)) {
9652     TokError("expected identifier after '.thumb_set'");
9653     Parser.eatToEndOfStatement();
9654     return false;
9655   }
9656
9657   if (getLexer().isNot(AsmToken::Comma)) {
9658     TokError("expected comma after name '" + Name + "'");
9659     Parser.eatToEndOfStatement();
9660     return false;
9661   }
9662   Lex();
9663
9664   const MCExpr *Value;
9665   if (Parser.parseExpression(Value)) {
9666     TokError("missing expression");
9667     Parser.eatToEndOfStatement();
9668     return false;
9669   }
9670
9671   if (getLexer().isNot(AsmToken::EndOfStatement)) {
9672     TokError("unexpected token");
9673     Parser.eatToEndOfStatement();
9674     return false;
9675   }
9676   Lex();
9677
9678   MCSymbol *Alias = getContext().GetOrCreateSymbol(Name);
9679   getTargetStreamer().emitThumbSet(Alias, Value);
9680   return false;
9681 }
9682
9683 /// Force static initialization.
9684 extern "C" void LLVMInitializeARMAsmParser() {
9685   RegisterMCAsmParser<ARMAsmParser> X(TheARMLETarget);
9686   RegisterMCAsmParser<ARMAsmParser> Y(TheARMBETarget);
9687   RegisterMCAsmParser<ARMAsmParser> A(TheThumbLETarget);
9688   RegisterMCAsmParser<ARMAsmParser> B(TheThumbBETarget);
9689 }
9690
9691 #define GET_REGISTER_MATCHER
9692 #define GET_SUBTARGET_FEATURE_NAME
9693 #define GET_MATCHER_IMPLEMENTATION
9694 #include "ARMGenAsmMatcher.inc"
9695
9696 static const struct {
9697   const char *Name;
9698   const unsigned ArchCheck;
9699   const uint64_t Features;
9700 } Extensions[] = {
9701   { "crc", Feature_HasV8, ARM::FeatureCRC },
9702   { "crypto",  Feature_HasV8,
9703     ARM::FeatureCrypto | ARM::FeatureNEON | ARM::FeatureFPARMv8 },
9704   { "fp", Feature_HasV8, ARM::FeatureFPARMv8 },
9705   { "idiv", Feature_HasV7 | Feature_IsNotMClass,
9706     ARM::FeatureHWDiv | ARM::FeatureHWDivARM },
9707   // FIXME: iWMMXT not supported
9708   { "iwmmxt", Feature_None, 0 },
9709   // FIXME: iWMMXT2 not supported
9710   { "iwmmxt2", Feature_None, 0 },
9711   // FIXME: Maverick not supported
9712   { "maverick", Feature_None, 0 },
9713   { "mp", Feature_HasV7 | Feature_IsNotMClass, ARM::FeatureMP },
9714   // FIXME: ARMv6-m OS Extensions feature not checked
9715   { "os", Feature_None, 0 },
9716   // FIXME: Also available in ARMv6-K
9717   { "sec", Feature_HasV7, ARM::FeatureTrustZone },
9718   { "simd", Feature_HasV8, ARM::FeatureNEON | ARM::FeatureFPARMv8 },
9719   // FIXME: Only available in A-class, isel not predicated
9720   { "virt", Feature_HasV7, ARM::FeatureVirtualization },
9721   // FIXME: xscale not supported
9722   { "xscale", Feature_None, 0 },
9723 };
9724
9725 /// parseDirectiveArchExtension
9726 ///   ::= .arch_extension [no]feature
9727 bool ARMAsmParser::parseDirectiveArchExtension(SMLoc L) {
9728   MCAsmParser &Parser = getParser();
9729
9730   if (getLexer().isNot(AsmToken::Identifier)) {
9731     Error(getLexer().getLoc(), "unexpected token");
9732     Parser.eatToEndOfStatement();
9733     return false;
9734   }
9735
9736   StringRef Name = Parser.getTok().getString();
9737   SMLoc ExtLoc = Parser.getTok().getLoc();
9738   getLexer().Lex();
9739
9740   bool EnableFeature = true;
9741   if (Name.startswith_lower("no")) {
9742     EnableFeature = false;
9743     Name = Name.substr(2);
9744   }
9745
9746   for (const auto &Extension : Extensions) {
9747     if (Extension.Name != Name)
9748       continue;
9749
9750     if (!Extension.Features)
9751       report_fatal_error("unsupported architectural extension: " + Name);
9752
9753     if ((getAvailableFeatures() & Extension.ArchCheck) != Extension.ArchCheck) {
9754       Error(ExtLoc, "architectural extension '" + Name + "' is not "
9755             "allowed for the current base architecture");
9756       return false;
9757     }
9758
9759     uint64_t ToggleFeatures = EnableFeature
9760                                   ? (~STI.getFeatureBits() & Extension.Features)
9761                                   : ( STI.getFeatureBits() & Extension.Features);
9762     uint64_t Features =
9763         ComputeAvailableFeatures(STI.ToggleFeature(ToggleFeatures));
9764     setAvailableFeatures(Features);
9765     return false;
9766   }
9767
9768   Error(ExtLoc, "unknown architectural extension: " + Name);
9769   Parser.eatToEndOfStatement();
9770   return false;
9771 }
9772
9773 // Define this matcher function after the auto-generated include so we
9774 // have the match class enum definitions.
9775 unsigned ARMAsmParser::validateTargetOperandClass(MCParsedAsmOperand &AsmOp,
9776                                                   unsigned Kind) {
9777   ARMOperand &Op = static_cast<ARMOperand &>(AsmOp);
9778   // If the kind is a token for a literal immediate, check if our asm
9779   // operand matches. This is for InstAliases which have a fixed-value
9780   // immediate in the syntax.
9781   switch (Kind) {
9782   default: break;
9783   case MCK__35_0:
9784     if (Op.isImm())
9785       if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm()))
9786         if (CE->getValue() == 0)
9787           return Match_Success;
9788     break;
9789   case MCK_ARMSOImm:
9790     if (Op.isImm()) {
9791       const MCExpr *SOExpr = Op.getImm();
9792       int64_t Value;
9793       if (!SOExpr->EvaluateAsAbsolute(Value))
9794         return Match_Success;
9795       assert((Value >= INT32_MIN && Value <= UINT32_MAX) &&
9796              "expression value must be representable in 32 bits");
9797     }
9798     break;
9799   case MCK_GPRPair:
9800     if (Op.isReg() &&
9801         MRI->getRegClass(ARM::GPRRegClassID).contains(Op.getReg()))
9802       return Match_Success;
9803     break;
9804   }
9805   return Match_InvalidOperand;
9806 }