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