ARM parsing/encoding for VCMP/VCMPE.
[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 "MCTargetDesc/ARMBaseInfo.h"
11 #include "MCTargetDesc/ARMAddressingModes.h"
12 #include "MCTargetDesc/ARMMCExpr.h"
13 #include "llvm/MC/MCParser/MCAsmLexer.h"
14 #include "llvm/MC/MCParser/MCAsmParser.h"
15 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
16 #include "llvm/MC/MCAsmInfo.h"
17 #include "llvm/MC/MCContext.h"
18 #include "llvm/MC/MCStreamer.h"
19 #include "llvm/MC/MCExpr.h"
20 #include "llvm/MC/MCInst.h"
21 #include "llvm/MC/MCInstrDesc.h"
22 #include "llvm/MC/MCRegisterInfo.h"
23 #include "llvm/MC/MCSubtargetInfo.h"
24 #include "llvm/MC/MCTargetAsmParser.h"
25 #include "llvm/Support/MathExtras.h"
26 #include "llvm/Support/SourceMgr.h"
27 #include "llvm/Support/TargetRegistry.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/ADT/BitVector.h"
30 #include "llvm/ADT/OwningPtr.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/ADT/SmallVector.h"
33 #include "llvm/ADT/StringExtras.h"
34 #include "llvm/ADT/StringSwitch.h"
35 #include "llvm/ADT/Twine.h"
36
37 using namespace llvm;
38
39 namespace {
40
41 class ARMOperand;
42
43 class ARMAsmParser : public MCTargetAsmParser {
44   MCSubtargetInfo &STI;
45   MCAsmParser &Parser;
46
47   struct {
48     ARMCC::CondCodes Cond;    // Condition for IT block.
49     unsigned Mask:4;          // Condition mask for instructions.
50                               // Starting at first 1 (from lsb).
51                               //   '1'  condition as indicated in IT.
52                               //   '0'  inverse of condition (else).
53                               // Count of instructions in IT block is
54                               // 4 - trailingzeroes(mask)
55
56     bool FirstCond;           // Explicit flag for when we're parsing the
57                               // First instruction in the IT block. It's
58                               // implied in the mask, so needs special
59                               // handling.
60
61     unsigned CurPosition;     // Current position in parsing of IT
62                               // block. In range [0,3]. Initialized
63                               // according to count of instructions in block.
64                               // ~0U if no active IT block.
65   } ITState;
66   bool inITBlock() { return ITState.CurPosition != ~0U;}
67   void forwardITPosition() {
68     if (!inITBlock()) return;
69     // Move to the next instruction in the IT block, if there is one. If not,
70     // mark the block as done.
71     unsigned TZ = CountTrailingZeros_32(ITState.Mask);
72     if (++ITState.CurPosition == 5 - TZ)
73       ITState.CurPosition = ~0U; // Done with the IT block after this.
74   }
75
76
77   MCAsmParser &getParser() const { return Parser; }
78   MCAsmLexer &getLexer() const { return Parser.getLexer(); }
79
80   void Warning(SMLoc L, const Twine &Msg) { Parser.Warning(L, Msg); }
81   bool Error(SMLoc L, const Twine &Msg) { return Parser.Error(L, Msg); }
82
83   int tryParseRegister();
84   bool tryParseRegisterWithWriteBack(SmallVectorImpl<MCParsedAsmOperand*> &);
85   int tryParseShiftRegister(SmallVectorImpl<MCParsedAsmOperand*> &);
86   bool parseRegisterList(SmallVectorImpl<MCParsedAsmOperand*> &);
87   bool parseMemory(SmallVectorImpl<MCParsedAsmOperand*> &);
88   bool parseOperand(SmallVectorImpl<MCParsedAsmOperand*> &, StringRef Mnemonic);
89   bool parsePrefix(ARMMCExpr::VariantKind &RefKind);
90   bool parseMemRegOffsetShift(ARM_AM::ShiftOpc &ShiftType,
91                               unsigned &ShiftAmount);
92   bool parseDirectiveWord(unsigned Size, SMLoc L);
93   bool parseDirectiveThumb(SMLoc L);
94   bool parseDirectiveThumbFunc(SMLoc L);
95   bool parseDirectiveCode(SMLoc L);
96   bool parseDirectiveSyntax(SMLoc L);
97
98   StringRef splitMnemonic(StringRef Mnemonic, unsigned &PredicationCode,
99                           bool &CarrySetting, unsigned &ProcessorIMod,
100                           StringRef &ITMask);
101   void getMnemonicAcceptInfo(StringRef Mnemonic, bool &CanAcceptCarrySet,
102                              bool &CanAcceptPredicationCode);
103
104   bool isThumb() const {
105     // FIXME: Can tablegen auto-generate this?
106     return (STI.getFeatureBits() & ARM::ModeThumb) != 0;
107   }
108   bool isThumbOne() const {
109     return isThumb() && (STI.getFeatureBits() & ARM::FeatureThumb2) == 0;
110   }
111   bool isThumbTwo() const {
112     return isThumb() && (STI.getFeatureBits() & ARM::FeatureThumb2);
113   }
114   bool hasV6Ops() const {
115     return STI.getFeatureBits() & ARM::HasV6Ops;
116   }
117   bool hasV7Ops() const {
118     return STI.getFeatureBits() & ARM::HasV7Ops;
119   }
120   void SwitchMode() {
121     unsigned FB = ComputeAvailableFeatures(STI.ToggleFeature(ARM::ModeThumb));
122     setAvailableFeatures(FB);
123   }
124   bool isMClass() const {
125     return STI.getFeatureBits() & ARM::FeatureMClass;
126   }
127
128   /// @name Auto-generated Match Functions
129   /// {
130
131 #define GET_ASSEMBLER_HEADER
132 #include "ARMGenAsmMatcher.inc"
133
134   /// }
135
136   OperandMatchResultTy parseITCondCode(SmallVectorImpl<MCParsedAsmOperand*>&);
137   OperandMatchResultTy parseCoprocNumOperand(
138     SmallVectorImpl<MCParsedAsmOperand*>&);
139   OperandMatchResultTy parseCoprocRegOperand(
140     SmallVectorImpl<MCParsedAsmOperand*>&);
141   OperandMatchResultTy parseMemBarrierOptOperand(
142     SmallVectorImpl<MCParsedAsmOperand*>&);
143   OperandMatchResultTy parseProcIFlagsOperand(
144     SmallVectorImpl<MCParsedAsmOperand*>&);
145   OperandMatchResultTy parseMSRMaskOperand(
146     SmallVectorImpl<MCParsedAsmOperand*>&);
147   OperandMatchResultTy parsePKHImm(SmallVectorImpl<MCParsedAsmOperand*> &O,
148                                    StringRef Op, int Low, int High);
149   OperandMatchResultTy parsePKHLSLImm(SmallVectorImpl<MCParsedAsmOperand*> &O) {
150     return parsePKHImm(O, "lsl", 0, 31);
151   }
152   OperandMatchResultTy parsePKHASRImm(SmallVectorImpl<MCParsedAsmOperand*> &O) {
153     return parsePKHImm(O, "asr", 1, 32);
154   }
155   OperandMatchResultTy parseSetEndImm(SmallVectorImpl<MCParsedAsmOperand*>&);
156   OperandMatchResultTy parseShifterImm(SmallVectorImpl<MCParsedAsmOperand*>&);
157   OperandMatchResultTy parseRotImm(SmallVectorImpl<MCParsedAsmOperand*>&);
158   OperandMatchResultTy parseBitfield(SmallVectorImpl<MCParsedAsmOperand*>&);
159   OperandMatchResultTy parsePostIdxReg(SmallVectorImpl<MCParsedAsmOperand*>&);
160   OperandMatchResultTy parseAM3Offset(SmallVectorImpl<MCParsedAsmOperand*>&);
161
162   // Asm Match Converter Methods
163   bool cvtT2LdrdPre(MCInst &Inst, unsigned Opcode,
164                     const SmallVectorImpl<MCParsedAsmOperand*> &);
165   bool cvtT2StrdPre(MCInst &Inst, unsigned Opcode,
166                     const SmallVectorImpl<MCParsedAsmOperand*> &);
167   bool cvtLdWriteBackRegT2AddrModeImm8(MCInst &Inst, unsigned Opcode,
168                                   const SmallVectorImpl<MCParsedAsmOperand*> &);
169   bool cvtStWriteBackRegT2AddrModeImm8(MCInst &Inst, unsigned Opcode,
170                                   const SmallVectorImpl<MCParsedAsmOperand*> &);
171   bool cvtLdWriteBackRegAddrMode2(MCInst &Inst, unsigned Opcode,
172                                   const SmallVectorImpl<MCParsedAsmOperand*> &);
173   bool cvtLdWriteBackRegAddrModeImm12(MCInst &Inst, unsigned Opcode,
174                                   const SmallVectorImpl<MCParsedAsmOperand*> &);
175   bool cvtStWriteBackRegAddrModeImm12(MCInst &Inst, unsigned Opcode,
176                                   const SmallVectorImpl<MCParsedAsmOperand*> &);
177   bool cvtStWriteBackRegAddrMode2(MCInst &Inst, unsigned Opcode,
178                                   const SmallVectorImpl<MCParsedAsmOperand*> &);
179   bool cvtStWriteBackRegAddrMode3(MCInst &Inst, unsigned Opcode,
180                                   const SmallVectorImpl<MCParsedAsmOperand*> &);
181   bool cvtLdExtTWriteBackImm(MCInst &Inst, unsigned Opcode,
182                              const SmallVectorImpl<MCParsedAsmOperand*> &);
183   bool cvtLdExtTWriteBackReg(MCInst &Inst, unsigned Opcode,
184                              const SmallVectorImpl<MCParsedAsmOperand*> &);
185   bool cvtStExtTWriteBackImm(MCInst &Inst, unsigned Opcode,
186                              const SmallVectorImpl<MCParsedAsmOperand*> &);
187   bool cvtStExtTWriteBackReg(MCInst &Inst, unsigned Opcode,
188                              const SmallVectorImpl<MCParsedAsmOperand*> &);
189   bool cvtLdrdPre(MCInst &Inst, unsigned Opcode,
190                   const SmallVectorImpl<MCParsedAsmOperand*> &);
191   bool cvtStrdPre(MCInst &Inst, unsigned Opcode,
192                   const SmallVectorImpl<MCParsedAsmOperand*> &);
193   bool cvtLdWriteBackRegAddrMode3(MCInst &Inst, unsigned Opcode,
194                                   const SmallVectorImpl<MCParsedAsmOperand*> &);
195   bool cvtThumbMultiply(MCInst &Inst, unsigned Opcode,
196                         const SmallVectorImpl<MCParsedAsmOperand*> &);
197
198   bool validateInstruction(MCInst &Inst,
199                            const SmallVectorImpl<MCParsedAsmOperand*> &Ops);
200   void processInstruction(MCInst &Inst,
201                           const SmallVectorImpl<MCParsedAsmOperand*> &Ops);
202   bool shouldOmitCCOutOperand(StringRef Mnemonic,
203                               SmallVectorImpl<MCParsedAsmOperand*> &Operands);
204
205 public:
206   enum ARMMatchResultTy {
207     Match_RequiresITBlock = FIRST_TARGET_MATCH_RESULT_TY,
208     Match_RequiresNotITBlock,
209     Match_RequiresV6,
210     Match_RequiresThumb2
211   };
212
213   ARMAsmParser(MCSubtargetInfo &_STI, MCAsmParser &_Parser)
214     : MCTargetAsmParser(), STI(_STI), Parser(_Parser) {
215     MCAsmParserExtension::Initialize(_Parser);
216
217     // Initialize the set of available features.
218     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
219
220     // Not in an ITBlock to start with.
221     ITState.CurPosition = ~0U;
222   }
223
224   // Implementation of the MCTargetAsmParser interface:
225   bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
226   bool ParseInstruction(StringRef Name, SMLoc NameLoc,
227                         SmallVectorImpl<MCParsedAsmOperand*> &Operands);
228   bool ParseDirective(AsmToken DirectiveID);
229
230   unsigned checkTargetMatchPredicate(MCInst &Inst);
231
232   bool MatchAndEmitInstruction(SMLoc IDLoc,
233                                SmallVectorImpl<MCParsedAsmOperand*> &Operands,
234                                MCStreamer &Out);
235 };
236 } // end anonymous namespace
237
238 namespace {
239
240 /// ARMOperand - Instances of this class represent a parsed ARM machine
241 /// instruction.
242 class ARMOperand : public MCParsedAsmOperand {
243   enum KindTy {
244     CondCode,
245     CCOut,
246     ITCondMask,
247     CoprocNum,
248     CoprocReg,
249     Immediate,
250     MemBarrierOpt,
251     Memory,
252     PostIndexRegister,
253     MSRMask,
254     ProcIFlags,
255     Register,
256     RegisterList,
257     DPRRegisterList,
258     SPRRegisterList,
259     ShiftedRegister,
260     ShiftedImmediate,
261     ShifterImmediate,
262     RotateImmediate,
263     BitfieldDescriptor,
264     Token
265   } Kind;
266
267   SMLoc StartLoc, EndLoc;
268   SmallVector<unsigned, 8> Registers;
269
270   union {
271     struct {
272       ARMCC::CondCodes Val;
273     } CC;
274
275     struct {
276       unsigned Val;
277     } Cop;
278
279     struct {
280       unsigned Mask:4;
281     } ITMask;
282
283     struct {
284       ARM_MB::MemBOpt Val;
285     } MBOpt;
286
287     struct {
288       ARM_PROC::IFlags Val;
289     } IFlags;
290
291     struct {
292       unsigned Val;
293     } MMask;
294
295     struct {
296       const char *Data;
297       unsigned Length;
298     } Tok;
299
300     struct {
301       unsigned RegNum;
302     } Reg;
303
304     struct {
305       const MCExpr *Val;
306     } Imm;
307
308     /// Combined record for all forms of ARM address expressions.
309     struct {
310       unsigned BaseRegNum;
311       // Offset is in OffsetReg or OffsetImm. If both are zero, no offset
312       // was specified.
313       const MCConstantExpr *OffsetImm;  // Offset immediate value
314       unsigned OffsetRegNum;    // Offset register num, when OffsetImm == NULL
315       ARM_AM::ShiftOpc ShiftType; // Shift type for OffsetReg
316       unsigned ShiftImm;      // shift for OffsetReg.
317       unsigned isNegative : 1;  // Negated OffsetReg? (~'U' bit)
318     } Mem;
319
320     struct {
321       unsigned RegNum;
322       bool isAdd;
323       ARM_AM::ShiftOpc ShiftTy;
324       unsigned ShiftImm;
325     } PostIdxReg;
326
327     struct {
328       bool isASR;
329       unsigned Imm;
330     } ShifterImm;
331     struct {
332       ARM_AM::ShiftOpc ShiftTy;
333       unsigned SrcReg;
334       unsigned ShiftReg;
335       unsigned ShiftImm;
336     } RegShiftedReg;
337     struct {
338       ARM_AM::ShiftOpc ShiftTy;
339       unsigned SrcReg;
340       unsigned ShiftImm;
341     } RegShiftedImm;
342     struct {
343       unsigned Imm;
344     } RotImm;
345     struct {
346       unsigned LSB;
347       unsigned Width;
348     } Bitfield;
349   };
350
351   ARMOperand(KindTy K) : MCParsedAsmOperand(), Kind(K) {}
352 public:
353   ARMOperand(const ARMOperand &o) : MCParsedAsmOperand() {
354     Kind = o.Kind;
355     StartLoc = o.StartLoc;
356     EndLoc = o.EndLoc;
357     switch (Kind) {
358     case CondCode:
359       CC = o.CC;
360       break;
361     case ITCondMask:
362       ITMask = o.ITMask;
363       break;
364     case Token:
365       Tok = o.Tok;
366       break;
367     case CCOut:
368     case Register:
369       Reg = o.Reg;
370       break;
371     case RegisterList:
372     case DPRRegisterList:
373     case SPRRegisterList:
374       Registers = o.Registers;
375       break;
376     case CoprocNum:
377     case CoprocReg:
378       Cop = o.Cop;
379       break;
380     case Immediate:
381       Imm = o.Imm;
382       break;
383     case MemBarrierOpt:
384       MBOpt = o.MBOpt;
385       break;
386     case Memory:
387       Mem = o.Mem;
388       break;
389     case PostIndexRegister:
390       PostIdxReg = o.PostIdxReg;
391       break;
392     case MSRMask:
393       MMask = o.MMask;
394       break;
395     case ProcIFlags:
396       IFlags = o.IFlags;
397       break;
398     case ShifterImmediate:
399       ShifterImm = o.ShifterImm;
400       break;
401     case ShiftedRegister:
402       RegShiftedReg = o.RegShiftedReg;
403       break;
404     case ShiftedImmediate:
405       RegShiftedImm = o.RegShiftedImm;
406       break;
407     case RotateImmediate:
408       RotImm = o.RotImm;
409       break;
410     case BitfieldDescriptor:
411       Bitfield = o.Bitfield;
412       break;
413     }
414   }
415
416   /// getStartLoc - Get the location of the first token of this operand.
417   SMLoc getStartLoc() const { return StartLoc; }
418   /// getEndLoc - Get the location of the last token of this operand.
419   SMLoc getEndLoc() const { return EndLoc; }
420
421   ARMCC::CondCodes getCondCode() const {
422     assert(Kind == CondCode && "Invalid access!");
423     return CC.Val;
424   }
425
426   unsigned getCoproc() const {
427     assert((Kind == CoprocNum || Kind == CoprocReg) && "Invalid access!");
428     return Cop.Val;
429   }
430
431   StringRef getToken() const {
432     assert(Kind == Token && "Invalid access!");
433     return StringRef(Tok.Data, Tok.Length);
434   }
435
436   unsigned getReg() const {
437     assert((Kind == Register || Kind == CCOut) && "Invalid access!");
438     return Reg.RegNum;
439   }
440
441   const SmallVectorImpl<unsigned> &getRegList() const {
442     assert((Kind == RegisterList || Kind == DPRRegisterList ||
443             Kind == SPRRegisterList) && "Invalid access!");
444     return Registers;
445   }
446
447   const MCExpr *getImm() const {
448     assert(Kind == Immediate && "Invalid access!");
449     return Imm.Val;
450   }
451
452   ARM_MB::MemBOpt getMemBarrierOpt() const {
453     assert(Kind == MemBarrierOpt && "Invalid access!");
454     return MBOpt.Val;
455   }
456
457   ARM_PROC::IFlags getProcIFlags() const {
458     assert(Kind == ProcIFlags && "Invalid access!");
459     return IFlags.Val;
460   }
461
462   unsigned getMSRMask() const {
463     assert(Kind == MSRMask && "Invalid access!");
464     return MMask.Val;
465   }
466
467   bool isCoprocNum() const { return Kind == CoprocNum; }
468   bool isCoprocReg() const { return Kind == CoprocReg; }
469   bool isCondCode() const { return Kind == CondCode; }
470   bool isCCOut() const { return Kind == CCOut; }
471   bool isITMask() const { return Kind == ITCondMask; }
472   bool isITCondCode() const { return Kind == CondCode; }
473   bool isImm() const { return Kind == Immediate; }
474   bool isImm8s4() const {
475     if (Kind != Immediate)
476       return false;
477     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
478     if (!CE) return false;
479     int64_t Value = CE->getValue();
480     return ((Value & 3) == 0) && Value >= -1020 && Value <= 1020;
481   }
482   bool isImm0_1020s4() const {
483     if (Kind != Immediate)
484       return false;
485     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
486     if (!CE) return false;
487     int64_t Value = CE->getValue();
488     return ((Value & 3) == 0) && Value >= 0 && Value <= 1020;
489   }
490   bool isImm0_508s4() const {
491     if (Kind != Immediate)
492       return false;
493     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
494     if (!CE) return false;
495     int64_t Value = CE->getValue();
496     return ((Value & 3) == 0) && Value >= 0 && Value <= 508;
497   }
498   bool isImm0_255() const {
499     if (Kind != Immediate)
500       return false;
501     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
502     if (!CE) return false;
503     int64_t Value = CE->getValue();
504     return Value >= 0 && Value < 256;
505   }
506   bool isImm0_7() const {
507     if (Kind != Immediate)
508       return false;
509     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
510     if (!CE) return false;
511     int64_t Value = CE->getValue();
512     return Value >= 0 && Value < 8;
513   }
514   bool isImm0_15() const {
515     if (Kind != Immediate)
516       return false;
517     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
518     if (!CE) return false;
519     int64_t Value = CE->getValue();
520     return Value >= 0 && Value < 16;
521   }
522   bool isImm0_31() const {
523     if (Kind != Immediate)
524       return false;
525     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
526     if (!CE) return false;
527     int64_t Value = CE->getValue();
528     return Value >= 0 && Value < 32;
529   }
530   bool isImm1_16() const {
531     if (Kind != Immediate)
532       return false;
533     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
534     if (!CE) return false;
535     int64_t Value = CE->getValue();
536     return Value > 0 && Value < 17;
537   }
538   bool isImm1_32() const {
539     if (Kind != Immediate)
540       return false;
541     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
542     if (!CE) return false;
543     int64_t Value = CE->getValue();
544     return Value > 0 && Value < 33;
545   }
546   bool isImm0_65535() const {
547     if (Kind != Immediate)
548       return false;
549     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
550     if (!CE) return false;
551     int64_t Value = CE->getValue();
552     return Value >= 0 && Value < 65536;
553   }
554   bool isImm0_65535Expr() const {
555     if (Kind != Immediate)
556       return false;
557     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
558     // If it's not a constant expression, it'll generate a fixup and be
559     // handled later.
560     if (!CE) return true;
561     int64_t Value = CE->getValue();
562     return Value >= 0 && Value < 65536;
563   }
564   bool isImm24bit() const {
565     if (Kind != Immediate)
566       return false;
567     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
568     if (!CE) return false;
569     int64_t Value = CE->getValue();
570     return Value >= 0 && Value <= 0xffffff;
571   }
572   bool isImmThumbSR() const {
573     if (Kind != Immediate)
574       return false;
575     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
576     if (!CE) return false;
577     int64_t Value = CE->getValue();
578     return Value > 0 && Value < 33;
579   }
580   bool isPKHLSLImm() const {
581     if (Kind != Immediate)
582       return false;
583     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
584     if (!CE) return false;
585     int64_t Value = CE->getValue();
586     return Value >= 0 && Value < 32;
587   }
588   bool isPKHASRImm() const {
589     if (Kind != Immediate)
590       return false;
591     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
592     if (!CE) return false;
593     int64_t Value = CE->getValue();
594     return Value > 0 && Value <= 32;
595   }
596   bool isARMSOImm() const {
597     if (Kind != Immediate)
598       return false;
599     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
600     if (!CE) return false;
601     int64_t Value = CE->getValue();
602     return ARM_AM::getSOImmVal(Value) != -1;
603   }
604   bool isT2SOImm() const {
605     if (Kind != Immediate)
606       return false;
607     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
608     if (!CE) return false;
609     int64_t Value = CE->getValue();
610     return ARM_AM::getT2SOImmVal(Value) != -1;
611   }
612   bool isSetEndImm() const {
613     if (Kind != Immediate)
614       return false;
615     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
616     if (!CE) return false;
617     int64_t Value = CE->getValue();
618     return Value == 1 || Value == 0;
619   }
620   bool isReg() const { return Kind == Register; }
621   bool isRegList() const { return Kind == RegisterList; }
622   bool isDPRRegList() const { return Kind == DPRRegisterList; }
623   bool isSPRRegList() const { return Kind == SPRRegisterList; }
624   bool isToken() const { return Kind == Token; }
625   bool isMemBarrierOpt() const { return Kind == MemBarrierOpt; }
626   bool isMemory() const { return Kind == Memory; }
627   bool isShifterImm() const { return Kind == ShifterImmediate; }
628   bool isRegShiftedReg() const { return Kind == ShiftedRegister; }
629   bool isRegShiftedImm() const { return Kind == ShiftedImmediate; }
630   bool isRotImm() const { return Kind == RotateImmediate; }
631   bool isBitfield() const { return Kind == BitfieldDescriptor; }
632   bool isPostIdxRegShifted() const { return Kind == PostIndexRegister; }
633   bool isPostIdxReg() const {
634     return Kind == PostIndexRegister && PostIdxReg.ShiftTy == ARM_AM::no_shift;
635   }
636   bool isMemNoOffset() const {
637     if (Kind != Memory)
638       return false;
639     // No offset of any kind.
640     return Mem.OffsetRegNum == 0 && Mem.OffsetImm == 0;
641   }
642   bool isAddrMode2() const {
643     if (Kind != Memory)
644       return false;
645     // Check for register offset.
646     if (Mem.OffsetRegNum) return true;
647     // Immediate offset in range [-4095, 4095].
648     if (!Mem.OffsetImm) return true;
649     int64_t Val = Mem.OffsetImm->getValue();
650     return Val > -4096 && Val < 4096;
651   }
652   bool isAM2OffsetImm() const {
653     if (Kind != Immediate)
654       return false;
655     // Immediate offset in range [-4095, 4095].
656     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
657     if (!CE) return false;
658     int64_t Val = CE->getValue();
659     return Val > -4096 && Val < 4096;
660   }
661   bool isAddrMode3() const {
662     if (Kind != Memory)
663       return false;
664     // No shifts are legal for AM3.
665     if (Mem.ShiftType != ARM_AM::no_shift) return false;
666     // Check for register offset.
667     if (Mem.OffsetRegNum) return true;
668     // Immediate offset in range [-255, 255].
669     if (!Mem.OffsetImm) return true;
670     int64_t Val = Mem.OffsetImm->getValue();
671     return Val > -256 && Val < 256;
672   }
673   bool isAM3Offset() const {
674     if (Kind != Immediate && Kind != PostIndexRegister)
675       return false;
676     if (Kind == PostIndexRegister)
677       return PostIdxReg.ShiftTy == ARM_AM::no_shift;
678     // Immediate offset in range [-255, 255].
679     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
680     if (!CE) return false;
681     int64_t Val = CE->getValue();
682     // Special case, #-0 is INT32_MIN.
683     return (Val > -256 && Val < 256) || Val == INT32_MIN;
684   }
685   bool isAddrMode5() const {
686     if (Kind != Memory)
687       return false;
688     // Check for register offset.
689     if (Mem.OffsetRegNum) return false;
690     // Immediate offset in range [-1020, 1020] and a multiple of 4.
691     if (!Mem.OffsetImm) return true;
692     int64_t Val = Mem.OffsetImm->getValue();
693     return (Val >= -1020 && Val <= 1020 && ((Val & 3) == 0)) ||
694            Val == INT32_MIN;
695   }
696   bool isMemTBB() const {
697     if (Kind != Memory || !Mem.OffsetRegNum || Mem.isNegative ||
698         Mem.ShiftType != ARM_AM::no_shift)
699       return false;
700     return true;
701   }
702   bool isMemTBH() const {
703     if (Kind != Memory || !Mem.OffsetRegNum || Mem.isNegative ||
704         Mem.ShiftType != ARM_AM::lsl || Mem.ShiftImm != 1)
705       return false;
706     return true;
707   }
708   bool isMemRegOffset() const {
709     if (Kind != Memory || !Mem.OffsetRegNum)
710       return false;
711     return true;
712   }
713   bool isT2MemRegOffset() const {
714     if (Kind != Memory || !Mem.OffsetRegNum || Mem.isNegative)
715       return false;
716     // Only lsl #{0, 1, 2, 3} allowed.
717     if (Mem.ShiftType == ARM_AM::no_shift)
718       return true;
719     if (Mem.ShiftType != ARM_AM::lsl || Mem.ShiftImm > 3)
720       return false;
721     return true;
722   }
723   bool isMemThumbRR() const {
724     // Thumb reg+reg addressing is simple. Just two registers, a base and
725     // an offset. No shifts, negations or any other complicating factors.
726     if (Kind != Memory || !Mem.OffsetRegNum || Mem.isNegative ||
727         Mem.ShiftType != ARM_AM::no_shift)
728       return false;
729     return isARMLowRegister(Mem.BaseRegNum) &&
730       (!Mem.OffsetRegNum || isARMLowRegister(Mem.OffsetRegNum));
731   }
732   bool isMemThumbRIs4() const {
733     if (Kind != Memory || Mem.OffsetRegNum != 0 ||
734         !isARMLowRegister(Mem.BaseRegNum))
735       return false;
736     // Immediate offset, multiple of 4 in range [0, 124].
737     if (!Mem.OffsetImm) return true;
738     int64_t Val = Mem.OffsetImm->getValue();
739     return Val >= 0 && Val <= 124 && (Val % 4) == 0;
740   }
741   bool isMemThumbRIs2() const {
742     if (Kind != Memory || Mem.OffsetRegNum != 0 ||
743         !isARMLowRegister(Mem.BaseRegNum))
744       return false;
745     // Immediate offset, multiple of 4 in range [0, 62].
746     if (!Mem.OffsetImm) return true;
747     int64_t Val = Mem.OffsetImm->getValue();
748     return Val >= 0 && Val <= 62 && (Val % 2) == 0;
749   }
750   bool isMemThumbRIs1() const {
751     if (Kind != Memory || Mem.OffsetRegNum != 0 ||
752         !isARMLowRegister(Mem.BaseRegNum))
753       return false;
754     // Immediate offset in range [0, 31].
755     if (!Mem.OffsetImm) return true;
756     int64_t Val = Mem.OffsetImm->getValue();
757     return Val >= 0 && Val <= 31;
758   }
759   bool isMemThumbSPI() const {
760     if (Kind != Memory || Mem.OffsetRegNum != 0 || Mem.BaseRegNum != ARM::SP)
761       return false;
762     // Immediate offset, multiple of 4 in range [0, 1020].
763     if (!Mem.OffsetImm) return true;
764     int64_t Val = Mem.OffsetImm->getValue();
765     return Val >= 0 && Val <= 1020 && (Val % 4) == 0;
766   }
767   bool isMemImm8s4Offset() const {
768     if (Kind != Memory || Mem.OffsetRegNum != 0)
769       return false;
770     // Immediate offset a multiple of 4 in range [-1020, 1020].
771     if (!Mem.OffsetImm) return true;
772     int64_t Val = Mem.OffsetImm->getValue();
773     return Val >= -1020 && Val <= 1020 && (Val & 3) == 0;
774   }
775   bool isMemImm0_1020s4Offset() const {
776     if (Kind != Memory || Mem.OffsetRegNum != 0)
777       return false;
778     // Immediate offset a multiple of 4 in range [0, 1020].
779     if (!Mem.OffsetImm) return true;
780     int64_t Val = Mem.OffsetImm->getValue();
781     return Val >= 0 && Val <= 1020 && (Val & 3) == 0;
782   }
783   bool isMemImm8Offset() const {
784     if (Kind != Memory || Mem.OffsetRegNum != 0)
785       return false;
786     // Immediate offset in range [-255, 255].
787     if (!Mem.OffsetImm) return true;
788     int64_t Val = Mem.OffsetImm->getValue();
789     return (Val == INT32_MIN) || (Val > -256 && Val < 256);
790   }
791   bool isMemPosImm8Offset() const {
792     if (Kind != Memory || Mem.OffsetRegNum != 0)
793       return false;
794     // Immediate offset in range [0, 255].
795     if (!Mem.OffsetImm) return true;
796     int64_t Val = Mem.OffsetImm->getValue();
797     return Val >= 0 && Val < 256;
798   }
799   bool isMemNegImm8Offset() const {
800     if (Kind != Memory || Mem.OffsetRegNum != 0)
801       return false;
802     // Immediate offset in range [-255, -1].
803     if (!Mem.OffsetImm) return true;
804     int64_t Val = Mem.OffsetImm->getValue();
805     return Val > -256 && Val < 0;
806   }
807   bool isMemUImm12Offset() const {
808     // If we have an immediate that's not a constant, treat it as a label
809     // reference needing a fixup. If it is a constant, it's something else
810     // and we reject it.
811     if (Kind == Immediate && !isa<MCConstantExpr>(getImm()))
812       return true;
813
814     if (Kind != Memory || Mem.OffsetRegNum != 0)
815       return false;
816     // Immediate offset in range [0, 4095].
817     if (!Mem.OffsetImm) return true;
818     int64_t Val = Mem.OffsetImm->getValue();
819     return (Val >= 0 && Val < 4096);
820   }
821   bool isMemImm12Offset() const {
822     // If we have an immediate that's not a constant, treat it as a label
823     // reference needing a fixup. If it is a constant, it's something else
824     // and we reject it.
825     if (Kind == Immediate && !isa<MCConstantExpr>(getImm()))
826       return true;
827
828     if (Kind != Memory || Mem.OffsetRegNum != 0)
829       return false;
830     // Immediate offset in range [-4095, 4095].
831     if (!Mem.OffsetImm) return true;
832     int64_t Val = Mem.OffsetImm->getValue();
833     return (Val > -4096 && Val < 4096) || (Val == INT32_MIN);
834   }
835   bool isPostIdxImm8() const {
836     if (Kind != Immediate)
837       return false;
838     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
839     if (!CE) return false;
840     int64_t Val = CE->getValue();
841     return (Val > -256 && Val < 256) || (Val == INT32_MIN);
842   }
843
844   bool isMSRMask() const { return Kind == MSRMask; }
845   bool isProcIFlags() const { return Kind == ProcIFlags; }
846
847   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
848     // Add as immediates when possible.  Null MCExpr = 0.
849     if (Expr == 0)
850       Inst.addOperand(MCOperand::CreateImm(0));
851     else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
852       Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
853     else
854       Inst.addOperand(MCOperand::CreateExpr(Expr));
855   }
856
857   void addCondCodeOperands(MCInst &Inst, unsigned N) const {
858     assert(N == 2 && "Invalid number of operands!");
859     Inst.addOperand(MCOperand::CreateImm(unsigned(getCondCode())));
860     unsigned RegNum = getCondCode() == ARMCC::AL ? 0: ARM::CPSR;
861     Inst.addOperand(MCOperand::CreateReg(RegNum));
862   }
863
864   void addCoprocNumOperands(MCInst &Inst, unsigned N) const {
865     assert(N == 1 && "Invalid number of operands!");
866     Inst.addOperand(MCOperand::CreateImm(getCoproc()));
867   }
868
869   void addITMaskOperands(MCInst &Inst, unsigned N) const {
870     assert(N == 1 && "Invalid number of operands!");
871     Inst.addOperand(MCOperand::CreateImm(ITMask.Mask));
872   }
873
874   void addITCondCodeOperands(MCInst &Inst, unsigned N) const {
875     assert(N == 1 && "Invalid number of operands!");
876     Inst.addOperand(MCOperand::CreateImm(unsigned(getCondCode())));
877   }
878
879   void addCoprocRegOperands(MCInst &Inst, unsigned N) const {
880     assert(N == 1 && "Invalid number of operands!");
881     Inst.addOperand(MCOperand::CreateImm(getCoproc()));
882   }
883
884   void addCCOutOperands(MCInst &Inst, unsigned N) const {
885     assert(N == 1 && "Invalid number of operands!");
886     Inst.addOperand(MCOperand::CreateReg(getReg()));
887   }
888
889   void addRegOperands(MCInst &Inst, unsigned N) const {
890     assert(N == 1 && "Invalid number of operands!");
891     Inst.addOperand(MCOperand::CreateReg(getReg()));
892   }
893
894   void addRegShiftedRegOperands(MCInst &Inst, unsigned N) const {
895     assert(N == 3 && "Invalid number of operands!");
896     assert(isRegShiftedReg() && "addRegShiftedRegOperands() on non RegShiftedReg!");
897     Inst.addOperand(MCOperand::CreateReg(RegShiftedReg.SrcReg));
898     Inst.addOperand(MCOperand::CreateReg(RegShiftedReg.ShiftReg));
899     Inst.addOperand(MCOperand::CreateImm(
900       ARM_AM::getSORegOpc(RegShiftedReg.ShiftTy, RegShiftedReg.ShiftImm)));
901   }
902
903   void addRegShiftedImmOperands(MCInst &Inst, unsigned N) const {
904     assert(N == 2 && "Invalid number of operands!");
905     assert(isRegShiftedImm() && "addRegShiftedImmOperands() on non RegShiftedImm!");
906     Inst.addOperand(MCOperand::CreateReg(RegShiftedImm.SrcReg));
907     Inst.addOperand(MCOperand::CreateImm(
908       ARM_AM::getSORegOpc(RegShiftedImm.ShiftTy, RegShiftedImm.ShiftImm)));
909   }
910
911   void addShifterImmOperands(MCInst &Inst, unsigned N) const {
912     assert(N == 1 && "Invalid number of operands!");
913     Inst.addOperand(MCOperand::CreateImm((ShifterImm.isASR << 5) |
914                                          ShifterImm.Imm));
915   }
916
917   void addRegListOperands(MCInst &Inst, unsigned N) const {
918     assert(N == 1 && "Invalid number of operands!");
919     const SmallVectorImpl<unsigned> &RegList = getRegList();
920     for (SmallVectorImpl<unsigned>::const_iterator
921            I = RegList.begin(), E = RegList.end(); I != E; ++I)
922       Inst.addOperand(MCOperand::CreateReg(*I));
923   }
924
925   void addDPRRegListOperands(MCInst &Inst, unsigned N) const {
926     addRegListOperands(Inst, N);
927   }
928
929   void addSPRRegListOperands(MCInst &Inst, unsigned N) const {
930     addRegListOperands(Inst, N);
931   }
932
933   void addRotImmOperands(MCInst &Inst, unsigned N) const {
934     assert(N == 1 && "Invalid number of operands!");
935     // Encoded as val>>3. The printer handles display as 8, 16, 24.
936     Inst.addOperand(MCOperand::CreateImm(RotImm.Imm >> 3));
937   }
938
939   void addBitfieldOperands(MCInst &Inst, unsigned N) const {
940     assert(N == 1 && "Invalid number of operands!");
941     // Munge the lsb/width into a bitfield mask.
942     unsigned lsb = Bitfield.LSB;
943     unsigned width = Bitfield.Width;
944     // Make a 32-bit mask w/ the referenced bits clear and all other bits set.
945     uint32_t Mask = ~(((uint32_t)0xffffffff >> lsb) << (32 - width) >>
946                       (32 - (lsb + width)));
947     Inst.addOperand(MCOperand::CreateImm(Mask));
948   }
949
950   void addImmOperands(MCInst &Inst, unsigned N) const {
951     assert(N == 1 && "Invalid number of operands!");
952     addExpr(Inst, getImm());
953   }
954
955   void addImm8s4Operands(MCInst &Inst, unsigned N) const {
956     assert(N == 1 && "Invalid number of operands!");
957     // FIXME: We really want to scale the value here, but the LDRD/STRD
958     // instruction don't encode operands that way yet.
959     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
960     Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
961   }
962
963   void addImm0_1020s4Operands(MCInst &Inst, unsigned N) const {
964     assert(N == 1 && "Invalid number of operands!");
965     // The immediate is scaled by four in the encoding and is stored
966     // in the MCInst as such. Lop off the low two bits here.
967     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
968     Inst.addOperand(MCOperand::CreateImm(CE->getValue() / 4));
969   }
970
971   void addImm0_508s4Operands(MCInst &Inst, unsigned N) const {
972     assert(N == 1 && "Invalid number of operands!");
973     // The immediate is scaled by four in the encoding and is stored
974     // in the MCInst as such. Lop off the low two bits here.
975     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
976     Inst.addOperand(MCOperand::CreateImm(CE->getValue() / 4));
977   }
978
979   void addImm0_255Operands(MCInst &Inst, unsigned N) const {
980     assert(N == 1 && "Invalid number of operands!");
981     addExpr(Inst, getImm());
982   }
983
984   void addImm0_7Operands(MCInst &Inst, unsigned N) const {
985     assert(N == 1 && "Invalid number of operands!");
986     addExpr(Inst, getImm());
987   }
988
989   void addImm0_15Operands(MCInst &Inst, unsigned N) const {
990     assert(N == 1 && "Invalid number of operands!");
991     addExpr(Inst, getImm());
992   }
993
994   void addImm0_31Operands(MCInst &Inst, unsigned N) const {
995     assert(N == 1 && "Invalid number of operands!");
996     addExpr(Inst, getImm());
997   }
998
999   void addImm1_16Operands(MCInst &Inst, unsigned N) const {
1000     assert(N == 1 && "Invalid number of operands!");
1001     // The constant encodes as the immediate-1, and we store in the instruction
1002     // the bits as encoded, so subtract off one here.
1003     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1004     Inst.addOperand(MCOperand::CreateImm(CE->getValue() - 1));
1005   }
1006
1007   void addImm1_32Operands(MCInst &Inst, unsigned N) const {
1008     assert(N == 1 && "Invalid number of operands!");
1009     // The constant encodes as the immediate-1, and we store in the instruction
1010     // the bits as encoded, so subtract off one here.
1011     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1012     Inst.addOperand(MCOperand::CreateImm(CE->getValue() - 1));
1013   }
1014
1015   void addImm0_65535Operands(MCInst &Inst, unsigned N) const {
1016     assert(N == 1 && "Invalid number of operands!");
1017     addExpr(Inst, getImm());
1018   }
1019
1020   void addImm0_65535ExprOperands(MCInst &Inst, unsigned N) const {
1021     assert(N == 1 && "Invalid number of operands!");
1022     addExpr(Inst, getImm());
1023   }
1024
1025   void addImm24bitOperands(MCInst &Inst, unsigned N) const {
1026     assert(N == 1 && "Invalid number of operands!");
1027     addExpr(Inst, getImm());
1028   }
1029
1030   void addImmThumbSROperands(MCInst &Inst, unsigned N) const {
1031     assert(N == 1 && "Invalid number of operands!");
1032     // The constant encodes as the immediate, except for 32, which encodes as
1033     // zero.
1034     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1035     unsigned Imm = CE->getValue();
1036     Inst.addOperand(MCOperand::CreateImm((Imm == 32 ? 0 : Imm)));
1037   }
1038
1039   void addPKHLSLImmOperands(MCInst &Inst, unsigned N) const {
1040     assert(N == 1 && "Invalid number of operands!");
1041     addExpr(Inst, getImm());
1042   }
1043
1044   void addPKHASRImmOperands(MCInst &Inst, unsigned N) const {
1045     assert(N == 1 && "Invalid number of operands!");
1046     // An ASR value of 32 encodes as 0, so that's how we want to add it to
1047     // the instruction as well.
1048     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1049     int Val = CE->getValue();
1050     Inst.addOperand(MCOperand::CreateImm(Val == 32 ? 0 : Val));
1051   }
1052
1053   void addARMSOImmOperands(MCInst &Inst, unsigned N) const {
1054     assert(N == 1 && "Invalid number of operands!");
1055     addExpr(Inst, getImm());
1056   }
1057
1058   void addT2SOImmOperands(MCInst &Inst, unsigned N) const {
1059     assert(N == 1 && "Invalid number of operands!");
1060     addExpr(Inst, getImm());
1061   }
1062
1063   void addSetEndImmOperands(MCInst &Inst, unsigned N) const {
1064     assert(N == 1 && "Invalid number of operands!");
1065     addExpr(Inst, getImm());
1066   }
1067
1068   void addMemBarrierOptOperands(MCInst &Inst, unsigned N) const {
1069     assert(N == 1 && "Invalid number of operands!");
1070     Inst.addOperand(MCOperand::CreateImm(unsigned(getMemBarrierOpt())));
1071   }
1072
1073   void addMemNoOffsetOperands(MCInst &Inst, unsigned N) const {
1074     assert(N == 1 && "Invalid number of operands!");
1075     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1076   }
1077
1078   void addAddrMode2Operands(MCInst &Inst, unsigned N) const {
1079     assert(N == 3 && "Invalid number of operands!");
1080     int32_t Val = Mem.OffsetImm ? Mem.OffsetImm->getValue() : 0;
1081     if (!Mem.OffsetRegNum) {
1082       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
1083       // Special case for #-0
1084       if (Val == INT32_MIN) Val = 0;
1085       if (Val < 0) Val = -Val;
1086       Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
1087     } else {
1088       // For register offset, we encode the shift type and negation flag
1089       // here.
1090       Val = ARM_AM::getAM2Opc(Mem.isNegative ? ARM_AM::sub : ARM_AM::add,
1091                               Mem.ShiftImm, Mem.ShiftType);
1092     }
1093     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1094     Inst.addOperand(MCOperand::CreateReg(Mem.OffsetRegNum));
1095     Inst.addOperand(MCOperand::CreateImm(Val));
1096   }
1097
1098   void addAM2OffsetImmOperands(MCInst &Inst, unsigned N) const {
1099     assert(N == 2 && "Invalid number of operands!");
1100     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1101     assert(CE && "non-constant AM2OffsetImm operand!");
1102     int32_t Val = CE->getValue();
1103     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
1104     // Special case for #-0
1105     if (Val == INT32_MIN) Val = 0;
1106     if (Val < 0) Val = -Val;
1107     Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
1108     Inst.addOperand(MCOperand::CreateReg(0));
1109     Inst.addOperand(MCOperand::CreateImm(Val));
1110   }
1111
1112   void addAddrMode3Operands(MCInst &Inst, unsigned N) const {
1113     assert(N == 3 && "Invalid number of operands!");
1114     int32_t Val = Mem.OffsetImm ? Mem.OffsetImm->getValue() : 0;
1115     if (!Mem.OffsetRegNum) {
1116       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
1117       // Special case for #-0
1118       if (Val == INT32_MIN) Val = 0;
1119       if (Val < 0) Val = -Val;
1120       Val = ARM_AM::getAM3Opc(AddSub, Val);
1121     } else {
1122       // For register offset, we encode the shift type and negation flag
1123       // here.
1124       Val = ARM_AM::getAM3Opc(Mem.isNegative ? ARM_AM::sub : ARM_AM::add, 0);
1125     }
1126     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1127     Inst.addOperand(MCOperand::CreateReg(Mem.OffsetRegNum));
1128     Inst.addOperand(MCOperand::CreateImm(Val));
1129   }
1130
1131   void addAM3OffsetOperands(MCInst &Inst, unsigned N) const {
1132     assert(N == 2 && "Invalid number of operands!");
1133     if (Kind == PostIndexRegister) {
1134       int32_t Val =
1135         ARM_AM::getAM3Opc(PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub, 0);
1136       Inst.addOperand(MCOperand::CreateReg(PostIdxReg.RegNum));
1137       Inst.addOperand(MCOperand::CreateImm(Val));
1138       return;
1139     }
1140
1141     // Constant offset.
1142     const MCConstantExpr *CE = static_cast<const MCConstantExpr*>(getImm());
1143     int32_t Val = CE->getValue();
1144     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
1145     // Special case for #-0
1146     if (Val == INT32_MIN) Val = 0;
1147     if (Val < 0) Val = -Val;
1148     Val = ARM_AM::getAM3Opc(AddSub, Val);
1149     Inst.addOperand(MCOperand::CreateReg(0));
1150     Inst.addOperand(MCOperand::CreateImm(Val));
1151   }
1152
1153   void addAddrMode5Operands(MCInst &Inst, unsigned N) const {
1154     assert(N == 2 && "Invalid number of operands!");
1155     // The lower two bits are always zero and as such are not encoded.
1156     int32_t Val = Mem.OffsetImm ? Mem.OffsetImm->getValue() / 4 : 0;
1157     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
1158     // Special case for #-0
1159     if (Val == INT32_MIN) Val = 0;
1160     if (Val < 0) Val = -Val;
1161     Val = ARM_AM::getAM5Opc(AddSub, Val);
1162     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1163     Inst.addOperand(MCOperand::CreateImm(Val));
1164   }
1165
1166   void addMemImm8s4OffsetOperands(MCInst &Inst, unsigned N) const {
1167     assert(N == 2 && "Invalid number of operands!");
1168     int64_t Val = Mem.OffsetImm ? Mem.OffsetImm->getValue() : 0;
1169     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1170     Inst.addOperand(MCOperand::CreateImm(Val));
1171   }
1172
1173   void addMemImm0_1020s4OffsetOperands(MCInst &Inst, unsigned N) const {
1174     assert(N == 2 && "Invalid number of operands!");
1175     // The lower two bits are always zero and as such are not encoded.
1176     int32_t Val = Mem.OffsetImm ? Mem.OffsetImm->getValue() / 4 : 0;
1177     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1178     Inst.addOperand(MCOperand::CreateImm(Val));
1179   }
1180
1181   void addMemImm8OffsetOperands(MCInst &Inst, unsigned N) const {
1182     assert(N == 2 && "Invalid number of operands!");
1183     int64_t Val = Mem.OffsetImm ? Mem.OffsetImm->getValue() : 0;
1184     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1185     Inst.addOperand(MCOperand::CreateImm(Val));
1186   }
1187
1188   void addMemPosImm8OffsetOperands(MCInst &Inst, unsigned N) const {
1189     addMemImm8OffsetOperands(Inst, N);
1190   }
1191
1192   void addMemNegImm8OffsetOperands(MCInst &Inst, unsigned N) const {
1193     addMemImm8OffsetOperands(Inst, N);
1194   }
1195
1196   void addMemUImm12OffsetOperands(MCInst &Inst, unsigned N) const {
1197     assert(N == 2 && "Invalid number of operands!");
1198     // If this is an immediate, it's a label reference.
1199     if (Kind == Immediate) {
1200       addExpr(Inst, getImm());
1201       Inst.addOperand(MCOperand::CreateImm(0));
1202       return;
1203     }
1204
1205     // Otherwise, it's a normal memory reg+offset.
1206     int64_t Val = Mem.OffsetImm ? Mem.OffsetImm->getValue() : 0;
1207     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1208     Inst.addOperand(MCOperand::CreateImm(Val));
1209   }
1210
1211   void addMemImm12OffsetOperands(MCInst &Inst, unsigned N) const {
1212     assert(N == 2 && "Invalid number of operands!");
1213     // If this is an immediate, it's a label reference.
1214     if (Kind == Immediate) {
1215       addExpr(Inst, getImm());
1216       Inst.addOperand(MCOperand::CreateImm(0));
1217       return;
1218     }
1219
1220     // Otherwise, it's a normal memory reg+offset.
1221     int64_t Val = Mem.OffsetImm ? Mem.OffsetImm->getValue() : 0;
1222     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1223     Inst.addOperand(MCOperand::CreateImm(Val));
1224   }
1225
1226   void addMemTBBOperands(MCInst &Inst, unsigned N) const {
1227     assert(N == 2 && "Invalid number of operands!");
1228     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1229     Inst.addOperand(MCOperand::CreateReg(Mem.OffsetRegNum));
1230   }
1231
1232   void addMemTBHOperands(MCInst &Inst, unsigned N) const {
1233     assert(N == 2 && "Invalid number of operands!");
1234     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1235     Inst.addOperand(MCOperand::CreateReg(Mem.OffsetRegNum));
1236   }
1237
1238   void addMemRegOffsetOperands(MCInst &Inst, unsigned N) const {
1239     assert(N == 3 && "Invalid number of operands!");
1240     unsigned Val = ARM_AM::getAM2Opc(Mem.isNegative ? ARM_AM::sub : ARM_AM::add,
1241                                      Mem.ShiftImm, Mem.ShiftType);
1242     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1243     Inst.addOperand(MCOperand::CreateReg(Mem.OffsetRegNum));
1244     Inst.addOperand(MCOperand::CreateImm(Val));
1245   }
1246
1247   void addT2MemRegOffsetOperands(MCInst &Inst, unsigned N) const {
1248     assert(N == 3 && "Invalid number of operands!");
1249     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1250     Inst.addOperand(MCOperand::CreateReg(Mem.OffsetRegNum));
1251     Inst.addOperand(MCOperand::CreateImm(Mem.ShiftImm));
1252   }
1253
1254   void addMemThumbRROperands(MCInst &Inst, unsigned N) const {
1255     assert(N == 2 && "Invalid number of operands!");
1256     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1257     Inst.addOperand(MCOperand::CreateReg(Mem.OffsetRegNum));
1258   }
1259
1260   void addMemThumbRIs4Operands(MCInst &Inst, unsigned N) const {
1261     assert(N == 2 && "Invalid number of operands!");
1262     int64_t Val = Mem.OffsetImm ? (Mem.OffsetImm->getValue() / 4) : 0;
1263     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1264     Inst.addOperand(MCOperand::CreateImm(Val));
1265   }
1266
1267   void addMemThumbRIs2Operands(MCInst &Inst, unsigned N) const {
1268     assert(N == 2 && "Invalid number of operands!");
1269     int64_t Val = Mem.OffsetImm ? (Mem.OffsetImm->getValue() / 2) : 0;
1270     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1271     Inst.addOperand(MCOperand::CreateImm(Val));
1272   }
1273
1274   void addMemThumbRIs1Operands(MCInst &Inst, unsigned N) const {
1275     assert(N == 2 && "Invalid number of operands!");
1276     int64_t Val = Mem.OffsetImm ? (Mem.OffsetImm->getValue()) : 0;
1277     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1278     Inst.addOperand(MCOperand::CreateImm(Val));
1279   }
1280
1281   void addMemThumbSPIOperands(MCInst &Inst, unsigned N) const {
1282     assert(N == 2 && "Invalid number of operands!");
1283     int64_t Val = Mem.OffsetImm ? (Mem.OffsetImm->getValue() / 4) : 0;
1284     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1285     Inst.addOperand(MCOperand::CreateImm(Val));
1286   }
1287
1288   void addPostIdxImm8Operands(MCInst &Inst, unsigned N) const {
1289     assert(N == 1 && "Invalid number of operands!");
1290     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1291     assert(CE && "non-constant post-idx-imm8 operand!");
1292     int Imm = CE->getValue();
1293     bool isAdd = Imm >= 0;
1294     if (Imm == INT32_MIN) Imm = 0;
1295     Imm = (Imm < 0 ? -Imm : Imm) | (int)isAdd << 8;
1296     Inst.addOperand(MCOperand::CreateImm(Imm));
1297   }
1298
1299   void addPostIdxRegOperands(MCInst &Inst, unsigned N) const {
1300     assert(N == 2 && "Invalid number of operands!");
1301     Inst.addOperand(MCOperand::CreateReg(PostIdxReg.RegNum));
1302     Inst.addOperand(MCOperand::CreateImm(PostIdxReg.isAdd));
1303   }
1304
1305   void addPostIdxRegShiftedOperands(MCInst &Inst, unsigned N) const {
1306     assert(N == 2 && "Invalid number of operands!");
1307     Inst.addOperand(MCOperand::CreateReg(PostIdxReg.RegNum));
1308     // The sign, shift type, and shift amount are encoded in a single operand
1309     // using the AM2 encoding helpers.
1310     ARM_AM::AddrOpc opc = PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub;
1311     unsigned Imm = ARM_AM::getAM2Opc(opc, PostIdxReg.ShiftImm,
1312                                      PostIdxReg.ShiftTy);
1313     Inst.addOperand(MCOperand::CreateImm(Imm));
1314   }
1315
1316   void addMSRMaskOperands(MCInst &Inst, unsigned N) const {
1317     assert(N == 1 && "Invalid number of operands!");
1318     Inst.addOperand(MCOperand::CreateImm(unsigned(getMSRMask())));
1319   }
1320
1321   void addProcIFlagsOperands(MCInst &Inst, unsigned N) const {
1322     assert(N == 1 && "Invalid number of operands!");
1323     Inst.addOperand(MCOperand::CreateImm(unsigned(getProcIFlags())));
1324   }
1325
1326   virtual void print(raw_ostream &OS) const;
1327
1328   static ARMOperand *CreateITMask(unsigned Mask, SMLoc S) {
1329     ARMOperand *Op = new ARMOperand(ITCondMask);
1330     Op->ITMask.Mask = Mask;
1331     Op->StartLoc = S;
1332     Op->EndLoc = S;
1333     return Op;
1334   }
1335
1336   static ARMOperand *CreateCondCode(ARMCC::CondCodes CC, SMLoc S) {
1337     ARMOperand *Op = new ARMOperand(CondCode);
1338     Op->CC.Val = CC;
1339     Op->StartLoc = S;
1340     Op->EndLoc = S;
1341     return Op;
1342   }
1343
1344   static ARMOperand *CreateCoprocNum(unsigned CopVal, SMLoc S) {
1345     ARMOperand *Op = new ARMOperand(CoprocNum);
1346     Op->Cop.Val = CopVal;
1347     Op->StartLoc = S;
1348     Op->EndLoc = S;
1349     return Op;
1350   }
1351
1352   static ARMOperand *CreateCoprocReg(unsigned CopVal, SMLoc S) {
1353     ARMOperand *Op = new ARMOperand(CoprocReg);
1354     Op->Cop.Val = CopVal;
1355     Op->StartLoc = S;
1356     Op->EndLoc = S;
1357     return Op;
1358   }
1359
1360   static ARMOperand *CreateCCOut(unsigned RegNum, SMLoc S) {
1361     ARMOperand *Op = new ARMOperand(CCOut);
1362     Op->Reg.RegNum = RegNum;
1363     Op->StartLoc = S;
1364     Op->EndLoc = S;
1365     return Op;
1366   }
1367
1368   static ARMOperand *CreateToken(StringRef Str, SMLoc S) {
1369     ARMOperand *Op = new ARMOperand(Token);
1370     Op->Tok.Data = Str.data();
1371     Op->Tok.Length = Str.size();
1372     Op->StartLoc = S;
1373     Op->EndLoc = S;
1374     return Op;
1375   }
1376
1377   static ARMOperand *CreateReg(unsigned RegNum, SMLoc S, SMLoc E) {
1378     ARMOperand *Op = new ARMOperand(Register);
1379     Op->Reg.RegNum = RegNum;
1380     Op->StartLoc = S;
1381     Op->EndLoc = E;
1382     return Op;
1383   }
1384
1385   static ARMOperand *CreateShiftedRegister(ARM_AM::ShiftOpc ShTy,
1386                                            unsigned SrcReg,
1387                                            unsigned ShiftReg,
1388                                            unsigned ShiftImm,
1389                                            SMLoc S, SMLoc E) {
1390     ARMOperand *Op = new ARMOperand(ShiftedRegister);
1391     Op->RegShiftedReg.ShiftTy = ShTy;
1392     Op->RegShiftedReg.SrcReg = SrcReg;
1393     Op->RegShiftedReg.ShiftReg = ShiftReg;
1394     Op->RegShiftedReg.ShiftImm = ShiftImm;
1395     Op->StartLoc = S;
1396     Op->EndLoc = E;
1397     return Op;
1398   }
1399
1400   static ARMOperand *CreateShiftedImmediate(ARM_AM::ShiftOpc ShTy,
1401                                             unsigned SrcReg,
1402                                             unsigned ShiftImm,
1403                                             SMLoc S, SMLoc E) {
1404     ARMOperand *Op = new ARMOperand(ShiftedImmediate);
1405     Op->RegShiftedImm.ShiftTy = ShTy;
1406     Op->RegShiftedImm.SrcReg = SrcReg;
1407     Op->RegShiftedImm.ShiftImm = ShiftImm;
1408     Op->StartLoc = S;
1409     Op->EndLoc = E;
1410     return Op;
1411   }
1412
1413   static ARMOperand *CreateShifterImm(bool isASR, unsigned Imm,
1414                                    SMLoc S, SMLoc E) {
1415     ARMOperand *Op = new ARMOperand(ShifterImmediate);
1416     Op->ShifterImm.isASR = isASR;
1417     Op->ShifterImm.Imm = Imm;
1418     Op->StartLoc = S;
1419     Op->EndLoc = E;
1420     return Op;
1421   }
1422
1423   static ARMOperand *CreateRotImm(unsigned Imm, SMLoc S, SMLoc E) {
1424     ARMOperand *Op = new ARMOperand(RotateImmediate);
1425     Op->RotImm.Imm = Imm;
1426     Op->StartLoc = S;
1427     Op->EndLoc = E;
1428     return Op;
1429   }
1430
1431   static ARMOperand *CreateBitfield(unsigned LSB, unsigned Width,
1432                                     SMLoc S, SMLoc E) {
1433     ARMOperand *Op = new ARMOperand(BitfieldDescriptor);
1434     Op->Bitfield.LSB = LSB;
1435     Op->Bitfield.Width = Width;
1436     Op->StartLoc = S;
1437     Op->EndLoc = E;
1438     return Op;
1439   }
1440
1441   static ARMOperand *
1442   CreateRegList(const SmallVectorImpl<std::pair<unsigned, SMLoc> > &Regs,
1443                 SMLoc StartLoc, SMLoc EndLoc) {
1444     KindTy Kind = RegisterList;
1445
1446     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Regs.front().first))
1447       Kind = DPRRegisterList;
1448     else if (ARMMCRegisterClasses[ARM::SPRRegClassID].
1449              contains(Regs.front().first))
1450       Kind = SPRRegisterList;
1451
1452     ARMOperand *Op = new ARMOperand(Kind);
1453     for (SmallVectorImpl<std::pair<unsigned, SMLoc> >::const_iterator
1454            I = Regs.begin(), E = Regs.end(); I != E; ++I)
1455       Op->Registers.push_back(I->first);
1456     array_pod_sort(Op->Registers.begin(), Op->Registers.end());
1457     Op->StartLoc = StartLoc;
1458     Op->EndLoc = EndLoc;
1459     return Op;
1460   }
1461
1462   static ARMOperand *CreateImm(const MCExpr *Val, SMLoc S, SMLoc E) {
1463     ARMOperand *Op = new ARMOperand(Immediate);
1464     Op->Imm.Val = Val;
1465     Op->StartLoc = S;
1466     Op->EndLoc = E;
1467     return Op;
1468   }
1469
1470   static ARMOperand *CreateMem(unsigned BaseRegNum,
1471                                const MCConstantExpr *OffsetImm,
1472                                unsigned OffsetRegNum,
1473                                ARM_AM::ShiftOpc ShiftType,
1474                                unsigned ShiftImm,
1475                                bool isNegative,
1476                                SMLoc S, SMLoc E) {
1477     ARMOperand *Op = new ARMOperand(Memory);
1478     Op->Mem.BaseRegNum = BaseRegNum;
1479     Op->Mem.OffsetImm = OffsetImm;
1480     Op->Mem.OffsetRegNum = OffsetRegNum;
1481     Op->Mem.ShiftType = ShiftType;
1482     Op->Mem.ShiftImm = ShiftImm;
1483     Op->Mem.isNegative = isNegative;
1484     Op->StartLoc = S;
1485     Op->EndLoc = E;
1486     return Op;
1487   }
1488
1489   static ARMOperand *CreatePostIdxReg(unsigned RegNum, bool isAdd,
1490                                       ARM_AM::ShiftOpc ShiftTy,
1491                                       unsigned ShiftImm,
1492                                       SMLoc S, SMLoc E) {
1493     ARMOperand *Op = new ARMOperand(PostIndexRegister);
1494     Op->PostIdxReg.RegNum = RegNum;
1495     Op->PostIdxReg.isAdd = isAdd;
1496     Op->PostIdxReg.ShiftTy = ShiftTy;
1497     Op->PostIdxReg.ShiftImm = ShiftImm;
1498     Op->StartLoc = S;
1499     Op->EndLoc = E;
1500     return Op;
1501   }
1502
1503   static ARMOperand *CreateMemBarrierOpt(ARM_MB::MemBOpt Opt, SMLoc S) {
1504     ARMOperand *Op = new ARMOperand(MemBarrierOpt);
1505     Op->MBOpt.Val = Opt;
1506     Op->StartLoc = S;
1507     Op->EndLoc = S;
1508     return Op;
1509   }
1510
1511   static ARMOperand *CreateProcIFlags(ARM_PROC::IFlags IFlags, SMLoc S) {
1512     ARMOperand *Op = new ARMOperand(ProcIFlags);
1513     Op->IFlags.Val = IFlags;
1514     Op->StartLoc = S;
1515     Op->EndLoc = S;
1516     return Op;
1517   }
1518
1519   static ARMOperand *CreateMSRMask(unsigned MMask, SMLoc S) {
1520     ARMOperand *Op = new ARMOperand(MSRMask);
1521     Op->MMask.Val = MMask;
1522     Op->StartLoc = S;
1523     Op->EndLoc = S;
1524     return Op;
1525   }
1526 };
1527
1528 } // end anonymous namespace.
1529
1530 void ARMOperand::print(raw_ostream &OS) const {
1531   switch (Kind) {
1532   case CondCode:
1533     OS << "<ARMCC::" << ARMCondCodeToString(getCondCode()) << ">";
1534     break;
1535   case CCOut:
1536     OS << "<ccout " << getReg() << ">";
1537     break;
1538   case ITCondMask: {
1539     static char MaskStr[][6] = { "()", "(t)", "(e)", "(tt)", "(et)", "(te)",
1540       "(ee)", "(ttt)", "(ett)", "(tet)", "(eet)", "(tte)", "(ete)",
1541       "(tee)", "(eee)" };
1542     assert((ITMask.Mask & 0xf) == ITMask.Mask);
1543     OS << "<it-mask " << MaskStr[ITMask.Mask] << ">";
1544     break;
1545   }
1546   case CoprocNum:
1547     OS << "<coprocessor number: " << getCoproc() << ">";
1548     break;
1549   case CoprocReg:
1550     OS << "<coprocessor register: " << getCoproc() << ">";
1551     break;
1552   case MSRMask:
1553     OS << "<mask: " << getMSRMask() << ">";
1554     break;
1555   case Immediate:
1556     getImm()->print(OS);
1557     break;
1558   case MemBarrierOpt:
1559     OS << "<ARM_MB::" << MemBOptToString(getMemBarrierOpt()) << ">";
1560     break;
1561   case Memory:
1562     OS << "<memory "
1563        << " base:" << Mem.BaseRegNum;
1564     OS << ">";
1565     break;
1566   case PostIndexRegister:
1567     OS << "post-idx register " << (PostIdxReg.isAdd ? "" : "-")
1568        << PostIdxReg.RegNum;
1569     if (PostIdxReg.ShiftTy != ARM_AM::no_shift)
1570       OS << ARM_AM::getShiftOpcStr(PostIdxReg.ShiftTy) << " "
1571          << PostIdxReg.ShiftImm;
1572     OS << ">";
1573     break;
1574   case ProcIFlags: {
1575     OS << "<ARM_PROC::";
1576     unsigned IFlags = getProcIFlags();
1577     for (int i=2; i >= 0; --i)
1578       if (IFlags & (1 << i))
1579         OS << ARM_PROC::IFlagsToString(1 << i);
1580     OS << ">";
1581     break;
1582   }
1583   case Register:
1584     OS << "<register " << getReg() << ">";
1585     break;
1586   case ShifterImmediate:
1587     OS << "<shift " << (ShifterImm.isASR ? "asr" : "lsl")
1588        << " #" << ShifterImm.Imm << ">";
1589     break;
1590   case ShiftedRegister:
1591     OS << "<so_reg_reg "
1592        << RegShiftedReg.SrcReg
1593        << ARM_AM::getShiftOpcStr(ARM_AM::getSORegShOp(RegShiftedReg.ShiftImm))
1594        << ", " << RegShiftedReg.ShiftReg << ", "
1595        << ARM_AM::getSORegOffset(RegShiftedReg.ShiftImm)
1596        << ">";
1597     break;
1598   case ShiftedImmediate:
1599     OS << "<so_reg_imm "
1600        << RegShiftedImm.SrcReg
1601        << ARM_AM::getShiftOpcStr(ARM_AM::getSORegShOp(RegShiftedImm.ShiftImm))
1602        << ", " << ARM_AM::getSORegOffset(RegShiftedImm.ShiftImm)
1603        << ">";
1604     break;
1605   case RotateImmediate:
1606     OS << "<ror " << " #" << (RotImm.Imm * 8) << ">";
1607     break;
1608   case BitfieldDescriptor:
1609     OS << "<bitfield " << "lsb: " << Bitfield.LSB
1610        << ", width: " << Bitfield.Width << ">";
1611     break;
1612   case RegisterList:
1613   case DPRRegisterList:
1614   case SPRRegisterList: {
1615     OS << "<register_list ";
1616
1617     const SmallVectorImpl<unsigned> &RegList = getRegList();
1618     for (SmallVectorImpl<unsigned>::const_iterator
1619            I = RegList.begin(), E = RegList.end(); I != E; ) {
1620       OS << *I;
1621       if (++I < E) OS << ", ";
1622     }
1623
1624     OS << ">";
1625     break;
1626   }
1627   case Token:
1628     OS << "'" << getToken() << "'";
1629     break;
1630   }
1631 }
1632
1633 /// @name Auto-generated Match Functions
1634 /// {
1635
1636 static unsigned MatchRegisterName(StringRef Name);
1637
1638 /// }
1639
1640 bool ARMAsmParser::ParseRegister(unsigned &RegNo,
1641                                  SMLoc &StartLoc, SMLoc &EndLoc) {
1642   RegNo = tryParseRegister();
1643
1644   return (RegNo == (unsigned)-1);
1645 }
1646
1647 /// Try to parse a register name.  The token must be an Identifier when called,
1648 /// and if it is a register name the token is eaten and the register number is
1649 /// returned.  Otherwise return -1.
1650 ///
1651 int ARMAsmParser::tryParseRegister() {
1652   const AsmToken &Tok = Parser.getTok();
1653   if (Tok.isNot(AsmToken::Identifier)) return -1;
1654
1655   // FIXME: Validate register for the current architecture; we have to do
1656   // validation later, so maybe there is no need for this here.
1657   std::string upperCase = Tok.getString().str();
1658   std::string lowerCase = LowercaseString(upperCase);
1659   unsigned RegNum = MatchRegisterName(lowerCase);
1660   if (!RegNum) {
1661     RegNum = StringSwitch<unsigned>(lowerCase)
1662       .Case("r13", ARM::SP)
1663       .Case("r14", ARM::LR)
1664       .Case("r15", ARM::PC)
1665       .Case("ip", ARM::R12)
1666       .Default(0);
1667   }
1668   if (!RegNum) return -1;
1669
1670   Parser.Lex(); // Eat identifier token.
1671   return RegNum;
1672 }
1673
1674 // Try to parse a shifter  (e.g., "lsl <amt>"). On success, return 0.
1675 // If a recoverable error occurs, return 1. If an irrecoverable error
1676 // occurs, return -1. An irrecoverable error is one where tokens have been
1677 // consumed in the process of trying to parse the shifter (i.e., when it is
1678 // indeed a shifter operand, but malformed).
1679 int ARMAsmParser::tryParseShiftRegister(
1680                                SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1681   SMLoc S = Parser.getTok().getLoc();
1682   const AsmToken &Tok = Parser.getTok();
1683   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
1684
1685   std::string upperCase = Tok.getString().str();
1686   std::string lowerCase = LowercaseString(upperCase);
1687   ARM_AM::ShiftOpc ShiftTy = StringSwitch<ARM_AM::ShiftOpc>(lowerCase)
1688       .Case("lsl", ARM_AM::lsl)
1689       .Case("lsr", ARM_AM::lsr)
1690       .Case("asr", ARM_AM::asr)
1691       .Case("ror", ARM_AM::ror)
1692       .Case("rrx", ARM_AM::rrx)
1693       .Default(ARM_AM::no_shift);
1694
1695   if (ShiftTy == ARM_AM::no_shift)
1696     return 1;
1697
1698   Parser.Lex(); // Eat the operator.
1699
1700   // The source register for the shift has already been added to the
1701   // operand list, so we need to pop it off and combine it into the shifted
1702   // register operand instead.
1703   OwningPtr<ARMOperand> PrevOp((ARMOperand*)Operands.pop_back_val());
1704   if (!PrevOp->isReg())
1705     return Error(PrevOp->getStartLoc(), "shift must be of a register");
1706   int SrcReg = PrevOp->getReg();
1707   int64_t Imm = 0;
1708   int ShiftReg = 0;
1709   if (ShiftTy == ARM_AM::rrx) {
1710     // RRX Doesn't have an explicit shift amount. The encoder expects
1711     // the shift register to be the same as the source register. Seems odd,
1712     // but OK.
1713     ShiftReg = SrcReg;
1714   } else {
1715     // Figure out if this is shifted by a constant or a register (for non-RRX).
1716     if (Parser.getTok().is(AsmToken::Hash)) {
1717       Parser.Lex(); // Eat hash.
1718       SMLoc ImmLoc = Parser.getTok().getLoc();
1719       const MCExpr *ShiftExpr = 0;
1720       if (getParser().ParseExpression(ShiftExpr)) {
1721         Error(ImmLoc, "invalid immediate shift value");
1722         return -1;
1723       }
1724       // The expression must be evaluatable as an immediate.
1725       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftExpr);
1726       if (!CE) {
1727         Error(ImmLoc, "invalid immediate shift value");
1728         return -1;
1729       }
1730       // Range check the immediate.
1731       // lsl, ror: 0 <= imm <= 31
1732       // lsr, asr: 0 <= imm <= 32
1733       Imm = CE->getValue();
1734       if (Imm < 0 ||
1735           ((ShiftTy == ARM_AM::lsl || ShiftTy == ARM_AM::ror) && Imm > 31) ||
1736           ((ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr) && Imm > 32)) {
1737         Error(ImmLoc, "immediate shift value out of range");
1738         return -1;
1739       }
1740     } else if (Parser.getTok().is(AsmToken::Identifier)) {
1741       ShiftReg = tryParseRegister();
1742       SMLoc L = Parser.getTok().getLoc();
1743       if (ShiftReg == -1) {
1744         Error (L, "expected immediate or register in shift operand");
1745         return -1;
1746       }
1747     } else {
1748       Error (Parser.getTok().getLoc(),
1749                     "expected immediate or register in shift operand");
1750       return -1;
1751     }
1752   }
1753
1754   if (ShiftReg && ShiftTy != ARM_AM::rrx)
1755     Operands.push_back(ARMOperand::CreateShiftedRegister(ShiftTy, SrcReg,
1756                                                          ShiftReg, Imm,
1757                                                S, Parser.getTok().getLoc()));
1758   else
1759     Operands.push_back(ARMOperand::CreateShiftedImmediate(ShiftTy, SrcReg, Imm,
1760                                                S, Parser.getTok().getLoc()));
1761
1762   return 0;
1763 }
1764
1765
1766 /// Try to parse a register name.  The token must be an Identifier when called.
1767 /// If it's a register, an AsmOperand is created. Another AsmOperand is created
1768 /// if there is a "writeback". 'true' if it's not a register.
1769 ///
1770 /// TODO this is likely to change to allow different register types and or to
1771 /// parse for a specific register type.
1772 bool ARMAsmParser::
1773 tryParseRegisterWithWriteBack(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1774   SMLoc S = Parser.getTok().getLoc();
1775   int RegNo = tryParseRegister();
1776   if (RegNo == -1)
1777     return true;
1778
1779   Operands.push_back(ARMOperand::CreateReg(RegNo, S, Parser.getTok().getLoc()));
1780
1781   const AsmToken &ExclaimTok = Parser.getTok();
1782   if (ExclaimTok.is(AsmToken::Exclaim)) {
1783     Operands.push_back(ARMOperand::CreateToken(ExclaimTok.getString(),
1784                                                ExclaimTok.getLoc()));
1785     Parser.Lex(); // Eat exclaim token
1786   }
1787
1788   return false;
1789 }
1790
1791 /// MatchCoprocessorOperandName - Try to parse an coprocessor related
1792 /// instruction with a symbolic operand name. Example: "p1", "p7", "c3",
1793 /// "c5", ...
1794 static int MatchCoprocessorOperandName(StringRef Name, char CoprocOp) {
1795   // Use the same layout as the tablegen'erated register name matcher. Ugly,
1796   // but efficient.
1797   switch (Name.size()) {
1798   default: break;
1799   case 2:
1800     if (Name[0] != CoprocOp)
1801       return -1;
1802     switch (Name[1]) {
1803     default:  return -1;
1804     case '0': return 0;
1805     case '1': return 1;
1806     case '2': return 2;
1807     case '3': return 3;
1808     case '4': return 4;
1809     case '5': return 5;
1810     case '6': return 6;
1811     case '7': return 7;
1812     case '8': return 8;
1813     case '9': return 9;
1814     }
1815     break;
1816   case 3:
1817     if (Name[0] != CoprocOp || Name[1] != '1')
1818       return -1;
1819     switch (Name[2]) {
1820     default:  return -1;
1821     case '0': return 10;
1822     case '1': return 11;
1823     case '2': return 12;
1824     case '3': return 13;
1825     case '4': return 14;
1826     case '5': return 15;
1827     }
1828     break;
1829   }
1830
1831   return -1;
1832 }
1833
1834 /// parseITCondCode - Try to parse a condition code for an IT instruction.
1835 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
1836 parseITCondCode(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1837   SMLoc S = Parser.getTok().getLoc();
1838   const AsmToken &Tok = Parser.getTok();
1839   if (!Tok.is(AsmToken::Identifier))
1840     return MatchOperand_NoMatch;
1841   unsigned CC = StringSwitch<unsigned>(Tok.getString())
1842     .Case("eq", ARMCC::EQ)
1843     .Case("ne", ARMCC::NE)
1844     .Case("hs", ARMCC::HS)
1845     .Case("cs", ARMCC::HS)
1846     .Case("lo", ARMCC::LO)
1847     .Case("cc", ARMCC::LO)
1848     .Case("mi", ARMCC::MI)
1849     .Case("pl", ARMCC::PL)
1850     .Case("vs", ARMCC::VS)
1851     .Case("vc", ARMCC::VC)
1852     .Case("hi", ARMCC::HI)
1853     .Case("ls", ARMCC::LS)
1854     .Case("ge", ARMCC::GE)
1855     .Case("lt", ARMCC::LT)
1856     .Case("gt", ARMCC::GT)
1857     .Case("le", ARMCC::LE)
1858     .Case("al", ARMCC::AL)
1859     .Default(~0U);
1860   if (CC == ~0U)
1861     return MatchOperand_NoMatch;
1862   Parser.Lex(); // Eat the token.
1863
1864   Operands.push_back(ARMOperand::CreateCondCode(ARMCC::CondCodes(CC), S));
1865
1866   return MatchOperand_Success;
1867 }
1868
1869 /// parseCoprocNumOperand - Try to parse an coprocessor number operand. The
1870 /// token must be an Identifier when called, and if it is a coprocessor
1871 /// number, the token is eaten and the operand is added to the operand list.
1872 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
1873 parseCoprocNumOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1874   SMLoc S = Parser.getTok().getLoc();
1875   const AsmToken &Tok = Parser.getTok();
1876   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
1877
1878   int Num = MatchCoprocessorOperandName(Tok.getString(), 'p');
1879   if (Num == -1)
1880     return MatchOperand_NoMatch;
1881
1882   Parser.Lex(); // Eat identifier token.
1883   Operands.push_back(ARMOperand::CreateCoprocNum(Num, S));
1884   return MatchOperand_Success;
1885 }
1886
1887 /// parseCoprocRegOperand - Try to parse an coprocessor register operand. The
1888 /// token must be an Identifier when called, and if it is a coprocessor
1889 /// number, the token is eaten and the operand is added to the operand list.
1890 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
1891 parseCoprocRegOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1892   SMLoc S = Parser.getTok().getLoc();
1893   const AsmToken &Tok = Parser.getTok();
1894   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
1895
1896   int Reg = MatchCoprocessorOperandName(Tok.getString(), 'c');
1897   if (Reg == -1)
1898     return MatchOperand_NoMatch;
1899
1900   Parser.Lex(); // Eat identifier token.
1901   Operands.push_back(ARMOperand::CreateCoprocReg(Reg, S));
1902   return MatchOperand_Success;
1903 }
1904
1905 // For register list parsing, we need to map from raw GPR register numbering
1906 // to the enumeration values. The enumeration values aren't sorted by
1907 // register number due to our using "sp", "lr" and "pc" as canonical names.
1908 static unsigned getNextRegister(unsigned Reg) {
1909   // If this is a GPR, we need to do it manually, otherwise we can rely
1910   // on the sort ordering of the enumeration since the other reg-classes
1911   // are sane.
1912   if (!ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
1913     return Reg + 1;
1914   switch(Reg) {
1915   default: assert(0 && "Invalid GPR number!");
1916   case ARM::R0:  return ARM::R1;  case ARM::R1:  return ARM::R2;
1917   case ARM::R2:  return ARM::R3;  case ARM::R3:  return ARM::R4;
1918   case ARM::R4:  return ARM::R5;  case ARM::R5:  return ARM::R6;
1919   case ARM::R6:  return ARM::R7;  case ARM::R7:  return ARM::R8;
1920   case ARM::R8:  return ARM::R9;  case ARM::R9:  return ARM::R10;
1921   case ARM::R10: return ARM::R11; case ARM::R11: return ARM::R12;
1922   case ARM::R12: return ARM::SP;  case ARM::SP:  return ARM::LR;
1923   case ARM::LR:  return ARM::PC;  case ARM::PC:  return ARM::R0;
1924   }
1925 }
1926
1927 /// Parse a register list.
1928 bool ARMAsmParser::
1929 parseRegisterList(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1930   assert(Parser.getTok().is(AsmToken::LCurly) &&
1931          "Token is not a Left Curly Brace");
1932   SMLoc S = Parser.getTok().getLoc();
1933   Parser.Lex(); // Eat '{' token.
1934   SMLoc RegLoc = Parser.getTok().getLoc();
1935
1936   // Check the first register in the list to see what register class
1937   // this is a list of.
1938   int Reg = tryParseRegister();
1939   if (Reg == -1)
1940     return Error(RegLoc, "register expected");
1941
1942   MCRegisterClass *RC;
1943   if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
1944     RC = &ARMMCRegisterClasses[ARM::GPRRegClassID];
1945   else if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg))
1946     RC = &ARMMCRegisterClasses[ARM::DPRRegClassID];
1947   else if (ARMMCRegisterClasses[ARM::SPRRegClassID].contains(Reg))
1948     RC = &ARMMCRegisterClasses[ARM::SPRRegClassID];
1949   else
1950     return Error(RegLoc, "invalid register in register list");
1951
1952   // The reglist instructions have at most 16 registers, so reserve
1953   // space for that many.
1954   SmallVector<std::pair<unsigned, SMLoc>, 16> Registers;
1955   // Store the first register.
1956   Registers.push_back(std::pair<unsigned, SMLoc>(Reg, RegLoc));
1957
1958   // This starts immediately after the first register token in the list,
1959   // so we can see either a comma or a minus (range separator) as a legal
1960   // next token.
1961   while (Parser.getTok().is(AsmToken::Comma) ||
1962          Parser.getTok().is(AsmToken::Minus)) {
1963     if (Parser.getTok().is(AsmToken::Minus)) {
1964       Parser.Lex(); // Eat the comma.
1965       SMLoc EndLoc = Parser.getTok().getLoc();
1966       int EndReg = tryParseRegister();
1967       if (EndReg == -1)
1968         return Error(EndLoc, "register expected");
1969       // If the register is the same as the start reg, there's nothing
1970       // more to do.
1971       if (Reg == EndReg)
1972         continue;
1973       // The register must be in the same register class as the first.
1974       if (!RC->contains(EndReg))
1975         return Error(EndLoc, "invalid register in register list");
1976       // Ranges must go from low to high.
1977       if (getARMRegisterNumbering(Reg) > getARMRegisterNumbering(EndReg))
1978         return Error(EndLoc, "bad range in register list");
1979
1980       // Add all the registers in the range to the register list.
1981       while (Reg != EndReg) {
1982         Reg = getNextRegister(Reg);
1983         Registers.push_back(std::pair<unsigned, SMLoc>(Reg, RegLoc));
1984       }
1985       continue;
1986     }
1987     Parser.Lex(); // Eat the comma.
1988     RegLoc = Parser.getTok().getLoc();
1989     int OldReg = Reg;
1990     Reg = tryParseRegister();
1991     if (Reg == -1)
1992       return Error(RegLoc, "register expected");
1993     // The register must be in the same register class as the first.
1994     if (!RC->contains(Reg))
1995       return Error(RegLoc, "invalid register in register list");
1996     // List must be monotonically increasing.
1997     if (getARMRegisterNumbering(Reg) <= getARMRegisterNumbering(OldReg))
1998       return Error(RegLoc, "register list not in ascending order");
1999     // VFP register lists must also be contiguous.
2000     // It's OK to use the enumeration values directly here rather, as the
2001     // VFP register classes have the enum sorted properly.
2002     if (RC != &ARMMCRegisterClasses[ARM::GPRRegClassID] &&
2003         Reg != OldReg + 1)
2004       return Error(RegLoc, "non-contiguous register range");
2005     Registers.push_back(std::pair<unsigned, SMLoc>(Reg, RegLoc));
2006   }
2007
2008   SMLoc E = Parser.getTok().getLoc();
2009   if (Parser.getTok().isNot(AsmToken::RCurly))
2010     return Error(E, "'}' expected");
2011   Parser.Lex(); // Eat '}' token.
2012
2013   Operands.push_back(ARMOperand::CreateRegList(Registers, S, E));
2014   return false;
2015 }
2016
2017 /// parseMemBarrierOptOperand - Try to parse DSB/DMB data barrier options.
2018 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
2019 parseMemBarrierOptOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2020   SMLoc S = Parser.getTok().getLoc();
2021   const AsmToken &Tok = Parser.getTok();
2022   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
2023   StringRef OptStr = Tok.getString();
2024
2025   unsigned Opt = StringSwitch<unsigned>(OptStr.slice(0, OptStr.size()))
2026     .Case("sy",    ARM_MB::SY)
2027     .Case("st",    ARM_MB::ST)
2028     .Case("sh",    ARM_MB::ISH)
2029     .Case("ish",   ARM_MB::ISH)
2030     .Case("shst",  ARM_MB::ISHST)
2031     .Case("ishst", ARM_MB::ISHST)
2032     .Case("nsh",   ARM_MB::NSH)
2033     .Case("un",    ARM_MB::NSH)
2034     .Case("nshst", ARM_MB::NSHST)
2035     .Case("unst",  ARM_MB::NSHST)
2036     .Case("osh",   ARM_MB::OSH)
2037     .Case("oshst", ARM_MB::OSHST)
2038     .Default(~0U);
2039
2040   if (Opt == ~0U)
2041     return MatchOperand_NoMatch;
2042
2043   Parser.Lex(); // Eat identifier token.
2044   Operands.push_back(ARMOperand::CreateMemBarrierOpt((ARM_MB::MemBOpt)Opt, S));
2045   return MatchOperand_Success;
2046 }
2047
2048 /// parseProcIFlagsOperand - Try to parse iflags from CPS instruction.
2049 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
2050 parseProcIFlagsOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2051   SMLoc S = Parser.getTok().getLoc();
2052   const AsmToken &Tok = Parser.getTok();
2053   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
2054   StringRef IFlagsStr = Tok.getString();
2055
2056   unsigned IFlags = 0;
2057   for (int i = 0, e = IFlagsStr.size(); i != e; ++i) {
2058     unsigned Flag = StringSwitch<unsigned>(IFlagsStr.substr(i, 1))
2059     .Case("a", ARM_PROC::A)
2060     .Case("i", ARM_PROC::I)
2061     .Case("f", ARM_PROC::F)
2062     .Default(~0U);
2063
2064     // If some specific iflag is already set, it means that some letter is
2065     // present more than once, this is not acceptable.
2066     if (Flag == ~0U || (IFlags & Flag))
2067       return MatchOperand_NoMatch;
2068
2069     IFlags |= Flag;
2070   }
2071
2072   Parser.Lex(); // Eat identifier token.
2073   Operands.push_back(ARMOperand::CreateProcIFlags((ARM_PROC::IFlags)IFlags, S));
2074   return MatchOperand_Success;
2075 }
2076
2077 /// parseMSRMaskOperand - Try to parse mask flags from MSR instruction.
2078 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
2079 parseMSRMaskOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2080   SMLoc S = Parser.getTok().getLoc();
2081   const AsmToken &Tok = Parser.getTok();
2082   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
2083   StringRef Mask = Tok.getString();
2084
2085   if (isMClass()) {
2086     // See ARMv6-M 10.1.1
2087     unsigned FlagsVal = StringSwitch<unsigned>(Mask)
2088       .Case("apsr", 0)
2089       .Case("iapsr", 1)
2090       .Case("eapsr", 2)
2091       .Case("xpsr", 3)
2092       .Case("ipsr", 5)
2093       .Case("epsr", 6)
2094       .Case("iepsr", 7)
2095       .Case("msp", 8)
2096       .Case("psp", 9)
2097       .Case("primask", 16)
2098       .Case("basepri", 17)
2099       .Case("basepri_max", 18)
2100       .Case("faultmask", 19)
2101       .Case("control", 20)
2102       .Default(~0U);
2103     
2104     if (FlagsVal == ~0U)
2105       return MatchOperand_NoMatch;
2106
2107     if (!hasV7Ops() && FlagsVal >= 17 && FlagsVal <= 19)
2108       // basepri, basepri_max and faultmask only valid for V7m.
2109       return MatchOperand_NoMatch;
2110     
2111     Parser.Lex(); // Eat identifier token.
2112     Operands.push_back(ARMOperand::CreateMSRMask(FlagsVal, S));
2113     return MatchOperand_Success;
2114   }
2115
2116   // Split spec_reg from flag, example: CPSR_sxf => "CPSR" and "sxf"
2117   size_t Start = 0, Next = Mask.find('_');
2118   StringRef Flags = "";
2119   std::string SpecReg = LowercaseString(Mask.slice(Start, Next));
2120   if (Next != StringRef::npos)
2121     Flags = Mask.slice(Next+1, Mask.size());
2122
2123   // FlagsVal contains the complete mask:
2124   // 3-0: Mask
2125   // 4: Special Reg (cpsr, apsr => 0; spsr => 1)
2126   unsigned FlagsVal = 0;
2127
2128   if (SpecReg == "apsr") {
2129     FlagsVal = StringSwitch<unsigned>(Flags)
2130     .Case("nzcvq",  0x8) // same as CPSR_f
2131     .Case("g",      0x4) // same as CPSR_s
2132     .Case("nzcvqg", 0xc) // same as CPSR_fs
2133     .Default(~0U);
2134
2135     if (FlagsVal == ~0U) {
2136       if (!Flags.empty())
2137         return MatchOperand_NoMatch;
2138       else
2139         FlagsVal = 8; // No flag
2140     }
2141   } else if (SpecReg == "cpsr" || SpecReg == "spsr") {
2142     if (Flags == "all") // cpsr_all is an alias for cpsr_fc
2143       Flags = "fc";
2144     for (int i = 0, e = Flags.size(); i != e; ++i) {
2145       unsigned Flag = StringSwitch<unsigned>(Flags.substr(i, 1))
2146       .Case("c", 1)
2147       .Case("x", 2)
2148       .Case("s", 4)
2149       .Case("f", 8)
2150       .Default(~0U);
2151
2152       // If some specific flag is already set, it means that some letter is
2153       // present more than once, this is not acceptable.
2154       if (FlagsVal == ~0U || (FlagsVal & Flag))
2155         return MatchOperand_NoMatch;
2156       FlagsVal |= Flag;
2157     }
2158   } else // No match for special register.
2159     return MatchOperand_NoMatch;
2160
2161   // Special register without flags are equivalent to "fc" flags.
2162   if (!FlagsVal)
2163     FlagsVal = 0x9;
2164
2165   // Bit 4: Special Reg (cpsr, apsr => 0; spsr => 1)
2166   if (SpecReg == "spsr")
2167     FlagsVal |= 16;
2168
2169   Parser.Lex(); // Eat identifier token.
2170   Operands.push_back(ARMOperand::CreateMSRMask(FlagsVal, S));
2171   return MatchOperand_Success;
2172 }
2173
2174 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
2175 parsePKHImm(SmallVectorImpl<MCParsedAsmOperand*> &Operands, StringRef Op,
2176             int Low, int High) {
2177   const AsmToken &Tok = Parser.getTok();
2178   if (Tok.isNot(AsmToken::Identifier)) {
2179     Error(Parser.getTok().getLoc(), Op + " operand expected.");
2180     return MatchOperand_ParseFail;
2181   }
2182   StringRef ShiftName = Tok.getString();
2183   std::string LowerOp = LowercaseString(Op);
2184   std::string UpperOp = UppercaseString(Op);
2185   if (ShiftName != LowerOp && ShiftName != UpperOp) {
2186     Error(Parser.getTok().getLoc(), Op + " operand expected.");
2187     return MatchOperand_ParseFail;
2188   }
2189   Parser.Lex(); // Eat shift type token.
2190
2191   // There must be a '#' and a shift amount.
2192   if (Parser.getTok().isNot(AsmToken::Hash)) {
2193     Error(Parser.getTok().getLoc(), "'#' expected");
2194     return MatchOperand_ParseFail;
2195   }
2196   Parser.Lex(); // Eat hash token.
2197
2198   const MCExpr *ShiftAmount;
2199   SMLoc Loc = Parser.getTok().getLoc();
2200   if (getParser().ParseExpression(ShiftAmount)) {
2201     Error(Loc, "illegal expression");
2202     return MatchOperand_ParseFail;
2203   }
2204   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
2205   if (!CE) {
2206     Error(Loc, "constant expression expected");
2207     return MatchOperand_ParseFail;
2208   }
2209   int Val = CE->getValue();
2210   if (Val < Low || Val > High) {
2211     Error(Loc, "immediate value out of range");
2212     return MatchOperand_ParseFail;
2213   }
2214
2215   Operands.push_back(ARMOperand::CreateImm(CE, Loc, Parser.getTok().getLoc()));
2216
2217   return MatchOperand_Success;
2218 }
2219
2220 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
2221 parseSetEndImm(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2222   const AsmToken &Tok = Parser.getTok();
2223   SMLoc S = Tok.getLoc();
2224   if (Tok.isNot(AsmToken::Identifier)) {
2225     Error(Tok.getLoc(), "'be' or 'le' operand expected");
2226     return MatchOperand_ParseFail;
2227   }
2228   int Val = StringSwitch<int>(Tok.getString())
2229     .Case("be", 1)
2230     .Case("le", 0)
2231     .Default(-1);
2232   Parser.Lex(); // Eat the token.
2233
2234   if (Val == -1) {
2235     Error(Tok.getLoc(), "'be' or 'le' operand expected");
2236     return MatchOperand_ParseFail;
2237   }
2238   Operands.push_back(ARMOperand::CreateImm(MCConstantExpr::Create(Val,
2239                                                                   getContext()),
2240                                            S, Parser.getTok().getLoc()));
2241   return MatchOperand_Success;
2242 }
2243
2244 /// parseShifterImm - Parse the shifter immediate operand for SSAT/USAT
2245 /// instructions. Legal values are:
2246 ///     lsl #n  'n' in [0,31]
2247 ///     asr #n  'n' in [1,32]
2248 ///             n == 32 encoded as n == 0.
2249 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
2250 parseShifterImm(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2251   const AsmToken &Tok = Parser.getTok();
2252   SMLoc S = Tok.getLoc();
2253   if (Tok.isNot(AsmToken::Identifier)) {
2254     Error(S, "shift operator 'asr' or 'lsl' expected");
2255     return MatchOperand_ParseFail;
2256   }
2257   StringRef ShiftName = Tok.getString();
2258   bool isASR;
2259   if (ShiftName == "lsl" || ShiftName == "LSL")
2260     isASR = false;
2261   else if (ShiftName == "asr" || ShiftName == "ASR")
2262     isASR = true;
2263   else {
2264     Error(S, "shift operator 'asr' or 'lsl' expected");
2265     return MatchOperand_ParseFail;
2266   }
2267   Parser.Lex(); // Eat the operator.
2268
2269   // A '#' and a shift amount.
2270   if (Parser.getTok().isNot(AsmToken::Hash)) {
2271     Error(Parser.getTok().getLoc(), "'#' expected");
2272     return MatchOperand_ParseFail;
2273   }
2274   Parser.Lex(); // Eat hash token.
2275
2276   const MCExpr *ShiftAmount;
2277   SMLoc E = Parser.getTok().getLoc();
2278   if (getParser().ParseExpression(ShiftAmount)) {
2279     Error(E, "malformed shift expression");
2280     return MatchOperand_ParseFail;
2281   }
2282   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
2283   if (!CE) {
2284     Error(E, "shift amount must be an immediate");
2285     return MatchOperand_ParseFail;
2286   }
2287
2288   int64_t Val = CE->getValue();
2289   if (isASR) {
2290     // Shift amount must be in [1,32]
2291     if (Val < 1 || Val > 32) {
2292       Error(E, "'asr' shift amount must be in range [1,32]");
2293       return MatchOperand_ParseFail;
2294     }
2295     // asr #32 encoded as asr #0, but is not allowed in Thumb2 mode.
2296     if (isThumb() && Val == 32) {
2297       Error(E, "'asr #32' shift amount not allowed in Thumb mode");
2298       return MatchOperand_ParseFail;
2299     }
2300     if (Val == 32) Val = 0;
2301   } else {
2302     // Shift amount must be in [1,32]
2303     if (Val < 0 || Val > 31) {
2304       Error(E, "'lsr' shift amount must be in range [0,31]");
2305       return MatchOperand_ParseFail;
2306     }
2307   }
2308
2309   E = Parser.getTok().getLoc();
2310   Operands.push_back(ARMOperand::CreateShifterImm(isASR, Val, S, E));
2311
2312   return MatchOperand_Success;
2313 }
2314
2315 /// parseRotImm - Parse the shifter immediate operand for SXTB/UXTB family
2316 /// of instructions. Legal values are:
2317 ///     ror #n  'n' in {0, 8, 16, 24}
2318 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
2319 parseRotImm(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2320   const AsmToken &Tok = Parser.getTok();
2321   SMLoc S = Tok.getLoc();
2322   if (Tok.isNot(AsmToken::Identifier))
2323     return MatchOperand_NoMatch;
2324   StringRef ShiftName = Tok.getString();
2325   if (ShiftName != "ror" && ShiftName != "ROR")
2326     return MatchOperand_NoMatch;
2327   Parser.Lex(); // Eat the operator.
2328
2329   // A '#' and a rotate amount.
2330   if (Parser.getTok().isNot(AsmToken::Hash)) {
2331     Error(Parser.getTok().getLoc(), "'#' expected");
2332     return MatchOperand_ParseFail;
2333   }
2334   Parser.Lex(); // Eat hash token.
2335
2336   const MCExpr *ShiftAmount;
2337   SMLoc E = Parser.getTok().getLoc();
2338   if (getParser().ParseExpression(ShiftAmount)) {
2339     Error(E, "malformed rotate expression");
2340     return MatchOperand_ParseFail;
2341   }
2342   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
2343   if (!CE) {
2344     Error(E, "rotate amount must be an immediate");
2345     return MatchOperand_ParseFail;
2346   }
2347
2348   int64_t Val = CE->getValue();
2349   // Shift amount must be in {0, 8, 16, 24} (0 is undocumented extension)
2350   // normally, zero is represented in asm by omitting the rotate operand
2351   // entirely.
2352   if (Val != 8 && Val != 16 && Val != 24 && Val != 0) {
2353     Error(E, "'ror' rotate amount must be 8, 16, or 24");
2354     return MatchOperand_ParseFail;
2355   }
2356
2357   E = Parser.getTok().getLoc();
2358   Operands.push_back(ARMOperand::CreateRotImm(Val, S, E));
2359
2360   return MatchOperand_Success;
2361 }
2362
2363 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
2364 parseBitfield(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2365   SMLoc S = Parser.getTok().getLoc();
2366   // The bitfield descriptor is really two operands, the LSB and the width.
2367   if (Parser.getTok().isNot(AsmToken::Hash)) {
2368     Error(Parser.getTok().getLoc(), "'#' expected");
2369     return MatchOperand_ParseFail;
2370   }
2371   Parser.Lex(); // Eat hash token.
2372
2373   const MCExpr *LSBExpr;
2374   SMLoc E = Parser.getTok().getLoc();
2375   if (getParser().ParseExpression(LSBExpr)) {
2376     Error(E, "malformed immediate expression");
2377     return MatchOperand_ParseFail;
2378   }
2379   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LSBExpr);
2380   if (!CE) {
2381     Error(E, "'lsb' operand must be an immediate");
2382     return MatchOperand_ParseFail;
2383   }
2384
2385   int64_t LSB = CE->getValue();
2386   // The LSB must be in the range [0,31]
2387   if (LSB < 0 || LSB > 31) {
2388     Error(E, "'lsb' operand must be in the range [0,31]");
2389     return MatchOperand_ParseFail;
2390   }
2391   E = Parser.getTok().getLoc();
2392
2393   // Expect another immediate operand.
2394   if (Parser.getTok().isNot(AsmToken::Comma)) {
2395     Error(Parser.getTok().getLoc(), "too few operands");
2396     return MatchOperand_ParseFail;
2397   }
2398   Parser.Lex(); // Eat hash token.
2399   if (Parser.getTok().isNot(AsmToken::Hash)) {
2400     Error(Parser.getTok().getLoc(), "'#' expected");
2401     return MatchOperand_ParseFail;
2402   }
2403   Parser.Lex(); // Eat hash token.
2404
2405   const MCExpr *WidthExpr;
2406   if (getParser().ParseExpression(WidthExpr)) {
2407     Error(E, "malformed immediate expression");
2408     return MatchOperand_ParseFail;
2409   }
2410   CE = dyn_cast<MCConstantExpr>(WidthExpr);
2411   if (!CE) {
2412     Error(E, "'width' operand must be an immediate");
2413     return MatchOperand_ParseFail;
2414   }
2415
2416   int64_t Width = CE->getValue();
2417   // The LSB must be in the range [1,32-lsb]
2418   if (Width < 1 || Width > 32 - LSB) {
2419     Error(E, "'width' operand must be in the range [1,32-lsb]");
2420     return MatchOperand_ParseFail;
2421   }
2422   E = Parser.getTok().getLoc();
2423
2424   Operands.push_back(ARMOperand::CreateBitfield(LSB, Width, S, E));
2425
2426   return MatchOperand_Success;
2427 }
2428
2429 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
2430 parsePostIdxReg(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2431   // Check for a post-index addressing register operand. Specifically:
2432   // postidx_reg := '+' register {, shift}
2433   //              | '-' register {, shift}
2434   //              | register {, shift}
2435
2436   // This method must return MatchOperand_NoMatch without consuming any tokens
2437   // in the case where there is no match, as other alternatives take other
2438   // parse methods.
2439   AsmToken Tok = Parser.getTok();
2440   SMLoc S = Tok.getLoc();
2441   bool haveEaten = false;
2442   bool isAdd = true;
2443   int Reg = -1;
2444   if (Tok.is(AsmToken::Plus)) {
2445     Parser.Lex(); // Eat the '+' token.
2446     haveEaten = true;
2447   } else if (Tok.is(AsmToken::Minus)) {
2448     Parser.Lex(); // Eat the '-' token.
2449     isAdd = false;
2450     haveEaten = true;
2451   }
2452   if (Parser.getTok().is(AsmToken::Identifier))
2453     Reg = tryParseRegister();
2454   if (Reg == -1) {
2455     if (!haveEaten)
2456       return MatchOperand_NoMatch;
2457     Error(Parser.getTok().getLoc(), "register expected");
2458     return MatchOperand_ParseFail;
2459   }
2460   SMLoc E = Parser.getTok().getLoc();
2461
2462   ARM_AM::ShiftOpc ShiftTy = ARM_AM::no_shift;
2463   unsigned ShiftImm = 0;
2464   if (Parser.getTok().is(AsmToken::Comma)) {
2465     Parser.Lex(); // Eat the ','.
2466     if (parseMemRegOffsetShift(ShiftTy, ShiftImm))
2467       return MatchOperand_ParseFail;
2468   }
2469
2470   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ShiftTy,
2471                                                   ShiftImm, S, E));
2472
2473   return MatchOperand_Success;
2474 }
2475
2476 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
2477 parseAM3Offset(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2478   // Check for a post-index addressing register operand. Specifically:
2479   // am3offset := '+' register
2480   //              | '-' register
2481   //              | register
2482   //              | # imm
2483   //              | # + imm
2484   //              | # - imm
2485
2486   // This method must return MatchOperand_NoMatch without consuming any tokens
2487   // in the case where there is no match, as other alternatives take other
2488   // parse methods.
2489   AsmToken Tok = Parser.getTok();
2490   SMLoc S = Tok.getLoc();
2491
2492   // Do immediates first, as we always parse those if we have a '#'.
2493   if (Parser.getTok().is(AsmToken::Hash)) {
2494     Parser.Lex(); // Eat the '#'.
2495     // Explicitly look for a '-', as we need to encode negative zero
2496     // differently.
2497     bool isNegative = Parser.getTok().is(AsmToken::Minus);
2498     const MCExpr *Offset;
2499     if (getParser().ParseExpression(Offset))
2500       return MatchOperand_ParseFail;
2501     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
2502     if (!CE) {
2503       Error(S, "constant expression expected");
2504       return MatchOperand_ParseFail;
2505     }
2506     SMLoc E = Tok.getLoc();
2507     // Negative zero is encoded as the flag value INT32_MIN.
2508     int32_t Val = CE->getValue();
2509     if (isNegative && Val == 0)
2510       Val = INT32_MIN;
2511
2512     Operands.push_back(
2513       ARMOperand::CreateImm(MCConstantExpr::Create(Val, getContext()), S, E));
2514
2515     return MatchOperand_Success;
2516   }
2517
2518
2519   bool haveEaten = false;
2520   bool isAdd = true;
2521   int Reg = -1;
2522   if (Tok.is(AsmToken::Plus)) {
2523     Parser.Lex(); // Eat the '+' token.
2524     haveEaten = true;
2525   } else if (Tok.is(AsmToken::Minus)) {
2526     Parser.Lex(); // Eat the '-' token.
2527     isAdd = false;
2528     haveEaten = true;
2529   }
2530   if (Parser.getTok().is(AsmToken::Identifier))
2531     Reg = tryParseRegister();
2532   if (Reg == -1) {
2533     if (!haveEaten)
2534       return MatchOperand_NoMatch;
2535     Error(Parser.getTok().getLoc(), "register expected");
2536     return MatchOperand_ParseFail;
2537   }
2538   SMLoc E = Parser.getTok().getLoc();
2539
2540   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ARM_AM::no_shift,
2541                                                   0, S, E));
2542
2543   return MatchOperand_Success;
2544 }
2545
2546 /// cvtT2LdrdPre - Convert parsed operands to MCInst.
2547 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2548 /// when they refer multiple MIOperands inside a single one.
2549 bool ARMAsmParser::
2550 cvtT2LdrdPre(MCInst &Inst, unsigned Opcode,
2551              const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2552   // Rt, Rt2
2553   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2554   ((ARMOperand*)Operands[3])->addRegOperands(Inst, 1);
2555   // Create a writeback register dummy placeholder.
2556   Inst.addOperand(MCOperand::CreateReg(0));
2557   // addr
2558   ((ARMOperand*)Operands[4])->addMemImm8s4OffsetOperands(Inst, 2);
2559   // pred
2560   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2561   return true;
2562 }
2563
2564 /// cvtT2StrdPre - Convert parsed operands to MCInst.
2565 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2566 /// when they refer multiple MIOperands inside a single one.
2567 bool ARMAsmParser::
2568 cvtT2StrdPre(MCInst &Inst, unsigned Opcode,
2569              const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2570   // Create a writeback register dummy placeholder.
2571   Inst.addOperand(MCOperand::CreateReg(0));
2572   // Rt, Rt2
2573   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2574   ((ARMOperand*)Operands[3])->addRegOperands(Inst, 1);
2575   // addr
2576   ((ARMOperand*)Operands[4])->addMemImm8s4OffsetOperands(Inst, 2);
2577   // pred
2578   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2579   return true;
2580 }
2581
2582 /// cvtLdWriteBackRegT2AddrModeImm8 - Convert parsed operands to MCInst.
2583 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2584 /// when they refer multiple MIOperands inside a single one.
2585 bool ARMAsmParser::
2586 cvtLdWriteBackRegT2AddrModeImm8(MCInst &Inst, unsigned Opcode,
2587                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2588   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2589
2590   // Create a writeback register dummy placeholder.
2591   Inst.addOperand(MCOperand::CreateImm(0));
2592
2593   ((ARMOperand*)Operands[3])->addMemImm8OffsetOperands(Inst, 2);
2594   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2595   return true;
2596 }
2597
2598 /// cvtStWriteBackRegT2AddrModeImm8 - Convert parsed operands to MCInst.
2599 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2600 /// when they refer multiple MIOperands inside a single one.
2601 bool ARMAsmParser::
2602 cvtStWriteBackRegT2AddrModeImm8(MCInst &Inst, unsigned Opcode,
2603                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2604   // Create a writeback register dummy placeholder.
2605   Inst.addOperand(MCOperand::CreateImm(0));
2606   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2607   ((ARMOperand*)Operands[3])->addMemImm8OffsetOperands(Inst, 2);
2608   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2609   return true;
2610 }
2611
2612 /// cvtLdWriteBackRegAddrMode2 - Convert parsed operands to MCInst.
2613 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2614 /// when they refer multiple MIOperands inside a single one.
2615 bool ARMAsmParser::
2616 cvtLdWriteBackRegAddrMode2(MCInst &Inst, unsigned Opcode,
2617                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2618   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2619
2620   // Create a writeback register dummy placeholder.
2621   Inst.addOperand(MCOperand::CreateImm(0));
2622
2623   ((ARMOperand*)Operands[3])->addAddrMode2Operands(Inst, 3);
2624   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2625   return true;
2626 }
2627
2628 /// cvtLdWriteBackRegAddrModeImm12 - Convert parsed operands to MCInst.
2629 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2630 /// when they refer multiple MIOperands inside a single one.
2631 bool ARMAsmParser::
2632 cvtLdWriteBackRegAddrModeImm12(MCInst &Inst, unsigned Opcode,
2633                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2634   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2635
2636   // Create a writeback register dummy placeholder.
2637   Inst.addOperand(MCOperand::CreateImm(0));
2638
2639   ((ARMOperand*)Operands[3])->addMemImm12OffsetOperands(Inst, 2);
2640   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2641   return true;
2642 }
2643
2644
2645 /// cvtStWriteBackRegAddrModeImm12 - Convert parsed operands to MCInst.
2646 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2647 /// when they refer multiple MIOperands inside a single one.
2648 bool ARMAsmParser::
2649 cvtStWriteBackRegAddrModeImm12(MCInst &Inst, unsigned Opcode,
2650                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2651   // Create a writeback register dummy placeholder.
2652   Inst.addOperand(MCOperand::CreateImm(0));
2653   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2654   ((ARMOperand*)Operands[3])->addMemImm12OffsetOperands(Inst, 2);
2655   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2656   return true;
2657 }
2658
2659 /// cvtStWriteBackRegAddrMode2 - Convert parsed operands to MCInst.
2660 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2661 /// when they refer multiple MIOperands inside a single one.
2662 bool ARMAsmParser::
2663 cvtStWriteBackRegAddrMode2(MCInst &Inst, unsigned Opcode,
2664                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2665   // Create a writeback register dummy placeholder.
2666   Inst.addOperand(MCOperand::CreateImm(0));
2667   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2668   ((ARMOperand*)Operands[3])->addAddrMode2Operands(Inst, 3);
2669   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2670   return true;
2671 }
2672
2673 /// cvtStWriteBackRegAddrMode3 - Convert parsed operands to MCInst.
2674 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2675 /// when they refer multiple MIOperands inside a single one.
2676 bool ARMAsmParser::
2677 cvtStWriteBackRegAddrMode3(MCInst &Inst, unsigned Opcode,
2678                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2679   // Create a writeback register dummy placeholder.
2680   Inst.addOperand(MCOperand::CreateImm(0));
2681   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2682   ((ARMOperand*)Operands[3])->addAddrMode3Operands(Inst, 3);
2683   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2684   return true;
2685 }
2686
2687 /// cvtLdExtTWriteBackImm - Convert parsed operands to MCInst.
2688 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2689 /// when they refer multiple MIOperands inside a single one.
2690 bool ARMAsmParser::
2691 cvtLdExtTWriteBackImm(MCInst &Inst, unsigned Opcode,
2692                       const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2693   // Rt
2694   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2695   // Create a writeback register dummy placeholder.
2696   Inst.addOperand(MCOperand::CreateImm(0));
2697   // addr
2698   ((ARMOperand*)Operands[3])->addMemNoOffsetOperands(Inst, 1);
2699   // offset
2700   ((ARMOperand*)Operands[4])->addPostIdxImm8Operands(Inst, 1);
2701   // pred
2702   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2703   return true;
2704 }
2705
2706 /// cvtLdExtTWriteBackReg - Convert parsed operands to MCInst.
2707 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2708 /// when they refer multiple MIOperands inside a single one.
2709 bool ARMAsmParser::
2710 cvtLdExtTWriteBackReg(MCInst &Inst, unsigned Opcode,
2711                       const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2712   // Rt
2713   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2714   // Create a writeback register dummy placeholder.
2715   Inst.addOperand(MCOperand::CreateImm(0));
2716   // addr
2717   ((ARMOperand*)Operands[3])->addMemNoOffsetOperands(Inst, 1);
2718   // offset
2719   ((ARMOperand*)Operands[4])->addPostIdxRegOperands(Inst, 2);
2720   // pred
2721   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2722   return true;
2723 }
2724
2725 /// cvtStExtTWriteBackImm - Convert parsed operands to MCInst.
2726 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2727 /// when they refer multiple MIOperands inside a single one.
2728 bool ARMAsmParser::
2729 cvtStExtTWriteBackImm(MCInst &Inst, unsigned Opcode,
2730                       const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2731   // Create a writeback register dummy placeholder.
2732   Inst.addOperand(MCOperand::CreateImm(0));
2733   // Rt
2734   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2735   // addr
2736   ((ARMOperand*)Operands[3])->addMemNoOffsetOperands(Inst, 1);
2737   // offset
2738   ((ARMOperand*)Operands[4])->addPostIdxImm8Operands(Inst, 1);
2739   // pred
2740   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2741   return true;
2742 }
2743
2744 /// cvtStExtTWriteBackReg - Convert parsed operands to MCInst.
2745 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2746 /// when they refer multiple MIOperands inside a single one.
2747 bool ARMAsmParser::
2748 cvtStExtTWriteBackReg(MCInst &Inst, unsigned Opcode,
2749                       const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2750   // Create a writeback register dummy placeholder.
2751   Inst.addOperand(MCOperand::CreateImm(0));
2752   // Rt
2753   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2754   // addr
2755   ((ARMOperand*)Operands[3])->addMemNoOffsetOperands(Inst, 1);
2756   // offset
2757   ((ARMOperand*)Operands[4])->addPostIdxRegOperands(Inst, 2);
2758   // pred
2759   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2760   return true;
2761 }
2762
2763 /// cvtLdrdPre - Convert parsed operands to MCInst.
2764 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2765 /// when they refer multiple MIOperands inside a single one.
2766 bool ARMAsmParser::
2767 cvtLdrdPre(MCInst &Inst, unsigned Opcode,
2768            const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2769   // Rt, Rt2
2770   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2771   ((ARMOperand*)Operands[3])->addRegOperands(Inst, 1);
2772   // Create a writeback register dummy placeholder.
2773   Inst.addOperand(MCOperand::CreateImm(0));
2774   // addr
2775   ((ARMOperand*)Operands[4])->addAddrMode3Operands(Inst, 3);
2776   // pred
2777   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2778   return true;
2779 }
2780
2781 /// cvtStrdPre - Convert parsed operands to MCInst.
2782 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2783 /// when they refer multiple MIOperands inside a single one.
2784 bool ARMAsmParser::
2785 cvtStrdPre(MCInst &Inst, unsigned Opcode,
2786            const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2787   // Create a writeback register dummy placeholder.
2788   Inst.addOperand(MCOperand::CreateImm(0));
2789   // Rt, Rt2
2790   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2791   ((ARMOperand*)Operands[3])->addRegOperands(Inst, 1);
2792   // addr
2793   ((ARMOperand*)Operands[4])->addAddrMode3Operands(Inst, 3);
2794   // pred
2795   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2796   return true;
2797 }
2798
2799 /// cvtLdWriteBackRegAddrMode3 - Convert parsed operands to MCInst.
2800 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2801 /// when they refer multiple MIOperands inside a single one.
2802 bool ARMAsmParser::
2803 cvtLdWriteBackRegAddrMode3(MCInst &Inst, unsigned Opcode,
2804                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2805   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2806   // Create a writeback register dummy placeholder.
2807   Inst.addOperand(MCOperand::CreateImm(0));
2808   ((ARMOperand*)Operands[3])->addAddrMode3Operands(Inst, 3);
2809   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2810   return true;
2811 }
2812
2813 /// cvtThumbMultiple- Convert parsed operands to MCInst.
2814 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2815 /// when they refer multiple MIOperands inside a single one.
2816 bool ARMAsmParser::
2817 cvtThumbMultiply(MCInst &Inst, unsigned Opcode,
2818            const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2819   // The second source operand must be the same register as the destination
2820   // operand.
2821   if (Operands.size() == 6 &&
2822       (((ARMOperand*)Operands[3])->getReg() !=
2823        ((ARMOperand*)Operands[5])->getReg()) &&
2824       (((ARMOperand*)Operands[3])->getReg() !=
2825        ((ARMOperand*)Operands[4])->getReg())) {
2826     Error(Operands[3]->getStartLoc(),
2827           "destination register must match source register");
2828     return false;
2829   }
2830   ((ARMOperand*)Operands[3])->addRegOperands(Inst, 1);
2831   ((ARMOperand*)Operands[1])->addCCOutOperands(Inst, 1);
2832   ((ARMOperand*)Operands[4])->addRegOperands(Inst, 1);
2833   // If we have a three-operand form, use that, else the second source operand
2834   // is just the destination operand again.
2835   if (Operands.size() == 6)
2836     ((ARMOperand*)Operands[5])->addRegOperands(Inst, 1);
2837   else
2838     Inst.addOperand(Inst.getOperand(0));
2839   ((ARMOperand*)Operands[2])->addCondCodeOperands(Inst, 2);
2840
2841   return true;
2842 }
2843
2844 /// Parse an ARM memory expression, return false if successful else return true
2845 /// or an error.  The first token must be a '[' when called.
2846 bool ARMAsmParser::
2847 parseMemory(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2848   SMLoc S, E;
2849   assert(Parser.getTok().is(AsmToken::LBrac) &&
2850          "Token is not a Left Bracket");
2851   S = Parser.getTok().getLoc();
2852   Parser.Lex(); // Eat left bracket token.
2853
2854   const AsmToken &BaseRegTok = Parser.getTok();
2855   int BaseRegNum = tryParseRegister();
2856   if (BaseRegNum == -1)
2857     return Error(BaseRegTok.getLoc(), "register expected");
2858
2859   // The next token must either be a comma or a closing bracket.
2860   const AsmToken &Tok = Parser.getTok();
2861   if (!Tok.is(AsmToken::Comma) && !Tok.is(AsmToken::RBrac))
2862     return Error(Tok.getLoc(), "malformed memory operand");
2863
2864   if (Tok.is(AsmToken::RBrac)) {
2865     E = Tok.getLoc();
2866     Parser.Lex(); // Eat right bracket token.
2867
2868     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, 0, 0, ARM_AM::no_shift,
2869                                              0, false, S, E));
2870
2871     // If there's a pre-indexing writeback marker, '!', just add it as a token
2872     // operand. It's rather odd, but syntactically valid.
2873     if (Parser.getTok().is(AsmToken::Exclaim)) {
2874       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
2875       Parser.Lex(); // Eat the '!'.
2876     }
2877
2878     return false;
2879   }
2880
2881   assert(Tok.is(AsmToken::Comma) && "Lost comma in memory operand?!");
2882   Parser.Lex(); // Eat the comma.
2883
2884   // If we have a '#' it's an immediate offset, else assume it's a register
2885   // offset.
2886   if (Parser.getTok().is(AsmToken::Hash)) {
2887     Parser.Lex(); // Eat the '#'.
2888     E = Parser.getTok().getLoc();
2889
2890     bool isNegative = getParser().getTok().is(AsmToken::Minus);
2891     const MCExpr *Offset;
2892     if (getParser().ParseExpression(Offset))
2893      return true;
2894
2895     // The expression has to be a constant. Memory references with relocations
2896     // don't come through here, as they use the <label> forms of the relevant
2897     // instructions.
2898     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
2899     if (!CE)
2900       return Error (E, "constant expression expected");
2901
2902     // If the constant was #-0, represent it as INT32_MIN.
2903     int32_t Val = CE->getValue();
2904     if (isNegative && Val == 0)
2905       CE = MCConstantExpr::Create(INT32_MIN, getContext());
2906
2907     // Now we should have the closing ']'
2908     E = Parser.getTok().getLoc();
2909     if (Parser.getTok().isNot(AsmToken::RBrac))
2910       return Error(E, "']' expected");
2911     Parser.Lex(); // Eat right bracket token.
2912
2913     // Don't worry about range checking the value here. That's handled by
2914     // the is*() predicates.
2915     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, CE, 0,
2916                                              ARM_AM::no_shift, 0, false, S,E));
2917
2918     // If there's a pre-indexing writeback marker, '!', just add it as a token
2919     // operand.
2920     if (Parser.getTok().is(AsmToken::Exclaim)) {
2921       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
2922       Parser.Lex(); // Eat the '!'.
2923     }
2924
2925     return false;
2926   }
2927
2928   // The register offset is optionally preceded by a '+' or '-'
2929   bool isNegative = false;
2930   if (Parser.getTok().is(AsmToken::Minus)) {
2931     isNegative = true;
2932     Parser.Lex(); // Eat the '-'.
2933   } else if (Parser.getTok().is(AsmToken::Plus)) {
2934     // Nothing to do.
2935     Parser.Lex(); // Eat the '+'.
2936   }
2937
2938   E = Parser.getTok().getLoc();
2939   int OffsetRegNum = tryParseRegister();
2940   if (OffsetRegNum == -1)
2941     return Error(E, "register expected");
2942
2943   // If there's a shift operator, handle it.
2944   ARM_AM::ShiftOpc ShiftType = ARM_AM::no_shift;
2945   unsigned ShiftImm = 0;
2946   if (Parser.getTok().is(AsmToken::Comma)) {
2947     Parser.Lex(); // Eat the ','.
2948     if (parseMemRegOffsetShift(ShiftType, ShiftImm))
2949       return true;
2950   }
2951
2952   // Now we should have the closing ']'
2953   E = Parser.getTok().getLoc();
2954   if (Parser.getTok().isNot(AsmToken::RBrac))
2955     return Error(E, "']' expected");
2956   Parser.Lex(); // Eat right bracket token.
2957
2958   Operands.push_back(ARMOperand::CreateMem(BaseRegNum, 0, OffsetRegNum,
2959                                            ShiftType, ShiftImm, isNegative,
2960                                            S, E));
2961
2962   // If there's a pre-indexing writeback marker, '!', just add it as a token
2963   // operand.
2964   if (Parser.getTok().is(AsmToken::Exclaim)) {
2965     Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
2966     Parser.Lex(); // Eat the '!'.
2967   }
2968
2969   return false;
2970 }
2971
2972 /// parseMemRegOffsetShift - one of these two:
2973 ///   ( lsl | lsr | asr | ror ) , # shift_amount
2974 ///   rrx
2975 /// return true if it parses a shift otherwise it returns false.
2976 bool ARMAsmParser::parseMemRegOffsetShift(ARM_AM::ShiftOpc &St,
2977                                           unsigned &Amount) {
2978   SMLoc Loc = Parser.getTok().getLoc();
2979   const AsmToken &Tok = Parser.getTok();
2980   if (Tok.isNot(AsmToken::Identifier))
2981     return true;
2982   StringRef ShiftName = Tok.getString();
2983   if (ShiftName == "lsl" || ShiftName == "LSL")
2984     St = ARM_AM::lsl;
2985   else if (ShiftName == "lsr" || ShiftName == "LSR")
2986     St = ARM_AM::lsr;
2987   else if (ShiftName == "asr" || ShiftName == "ASR")
2988     St = ARM_AM::asr;
2989   else if (ShiftName == "ror" || ShiftName == "ROR")
2990     St = ARM_AM::ror;
2991   else if (ShiftName == "rrx" || ShiftName == "RRX")
2992     St = ARM_AM::rrx;
2993   else
2994     return Error(Loc, "illegal shift operator");
2995   Parser.Lex(); // Eat shift type token.
2996
2997   // rrx stands alone.
2998   Amount = 0;
2999   if (St != ARM_AM::rrx) {
3000     Loc = Parser.getTok().getLoc();
3001     // A '#' and a shift amount.
3002     const AsmToken &HashTok = Parser.getTok();
3003     if (HashTok.isNot(AsmToken::Hash))
3004       return Error(HashTok.getLoc(), "'#' expected");
3005     Parser.Lex(); // Eat hash token.
3006
3007     const MCExpr *Expr;
3008     if (getParser().ParseExpression(Expr))
3009       return true;
3010     // Range check the immediate.
3011     // lsl, ror: 0 <= imm <= 31
3012     // lsr, asr: 0 <= imm <= 32
3013     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
3014     if (!CE)
3015       return Error(Loc, "shift amount must be an immediate");
3016     int64_t Imm = CE->getValue();
3017     if (Imm < 0 ||
3018         ((St == ARM_AM::lsl || St == ARM_AM::ror) && Imm > 31) ||
3019         ((St == ARM_AM::lsr || St == ARM_AM::asr) && Imm > 32))
3020       return Error(Loc, "immediate shift value out of range");
3021     Amount = Imm;
3022   }
3023
3024   return false;
3025 }
3026
3027 /// Parse a arm instruction operand.  For now this parses the operand regardless
3028 /// of the mnemonic.
3029 bool ARMAsmParser::parseOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands,
3030                                 StringRef Mnemonic) {
3031   SMLoc S, E;
3032
3033   // Check if the current operand has a custom associated parser, if so, try to
3034   // custom parse the operand, or fallback to the general approach.
3035   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
3036   if (ResTy == MatchOperand_Success)
3037     return false;
3038   // If there wasn't a custom match, try the generic matcher below. Otherwise,
3039   // there was a match, but an error occurred, in which case, just return that
3040   // the operand parsing failed.
3041   if (ResTy == MatchOperand_ParseFail)
3042     return true;
3043
3044   switch (getLexer().getKind()) {
3045   default:
3046     Error(Parser.getTok().getLoc(), "unexpected token in operand");
3047     return true;
3048   case AsmToken::Identifier: {
3049     // If this is VMRS, check for the apsr_nzcv operand.
3050     if (!tryParseRegisterWithWriteBack(Operands))
3051       return false;
3052     int Res = tryParseShiftRegister(Operands);
3053     if (Res == 0) // success
3054       return false;
3055     else if (Res == -1) // irrecoverable error
3056       return true;
3057     if (Mnemonic == "vmrs" && Parser.getTok().getString() == "apsr_nzcv") {
3058       S = Parser.getTok().getLoc();
3059       Parser.Lex();
3060       Operands.push_back(ARMOperand::CreateToken("apsr_nzcv", S));
3061       return false;
3062     }
3063
3064     // Fall though for the Identifier case that is not a register or a
3065     // special name.
3066   }
3067   case AsmToken::Integer: // things like 1f and 2b as a branch targets
3068   case AsmToken::Dot: {   // . as a branch target
3069     // This was not a register so parse other operands that start with an
3070     // identifier (like labels) as expressions and create them as immediates.
3071     const MCExpr *IdVal;
3072     S = Parser.getTok().getLoc();
3073     if (getParser().ParseExpression(IdVal))
3074       return true;
3075     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
3076     Operands.push_back(ARMOperand::CreateImm(IdVal, S, E));
3077     return false;
3078   }
3079   case AsmToken::LBrac:
3080     return parseMemory(Operands);
3081   case AsmToken::LCurly:
3082     return parseRegisterList(Operands);
3083   case AsmToken::Hash: {
3084     // #42 -> immediate.
3085     // TODO: ":lower16:" and ":upper16:" modifiers after # before immediate
3086     S = Parser.getTok().getLoc();
3087     Parser.Lex();
3088     bool isNegative = Parser.getTok().is(AsmToken::Minus);
3089     const MCExpr *ImmVal;
3090     if (getParser().ParseExpression(ImmVal))
3091       return true;
3092     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ImmVal);
3093     if (!CE) {
3094       Error(S, "constant expression expected");
3095       return MatchOperand_ParseFail;
3096     }
3097     int32_t Val = CE->getValue();
3098     if (isNegative && Val == 0)
3099       ImmVal = MCConstantExpr::Create(INT32_MIN, getContext());
3100     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
3101     Operands.push_back(ARMOperand::CreateImm(ImmVal, S, E));
3102     return false;
3103   }
3104   case AsmToken::Colon: {
3105     // ":lower16:" and ":upper16:" expression prefixes
3106     // FIXME: Check it's an expression prefix,
3107     // e.g. (FOO - :lower16:BAR) isn't legal.
3108     ARMMCExpr::VariantKind RefKind;
3109     if (parsePrefix(RefKind))
3110       return true;
3111
3112     const MCExpr *SubExprVal;
3113     if (getParser().ParseExpression(SubExprVal))
3114       return true;
3115
3116     const MCExpr *ExprVal = ARMMCExpr::Create(RefKind, SubExprVal,
3117                                                    getContext());
3118     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
3119     Operands.push_back(ARMOperand::CreateImm(ExprVal, S, E));
3120     return false;
3121   }
3122   }
3123 }
3124
3125 // parsePrefix - Parse ARM 16-bit relocations expression prefix, i.e.
3126 //  :lower16: and :upper16:.
3127 bool ARMAsmParser::parsePrefix(ARMMCExpr::VariantKind &RefKind) {
3128   RefKind = ARMMCExpr::VK_ARM_None;
3129
3130   // :lower16: and :upper16: modifiers
3131   assert(getLexer().is(AsmToken::Colon) && "expected a :");
3132   Parser.Lex(); // Eat ':'
3133
3134   if (getLexer().isNot(AsmToken::Identifier)) {
3135     Error(Parser.getTok().getLoc(), "expected prefix identifier in operand");
3136     return true;
3137   }
3138
3139   StringRef IDVal = Parser.getTok().getIdentifier();
3140   if (IDVal == "lower16") {
3141     RefKind = ARMMCExpr::VK_ARM_LO16;
3142   } else if (IDVal == "upper16") {
3143     RefKind = ARMMCExpr::VK_ARM_HI16;
3144   } else {
3145     Error(Parser.getTok().getLoc(), "unexpected prefix in operand");
3146     return true;
3147   }
3148   Parser.Lex();
3149
3150   if (getLexer().isNot(AsmToken::Colon)) {
3151     Error(Parser.getTok().getLoc(), "unexpected token after prefix");
3152     return true;
3153   }
3154   Parser.Lex(); // Eat the last ':'
3155   return false;
3156 }
3157
3158 /// \brief Given a mnemonic, split out possible predication code and carry
3159 /// setting letters to form a canonical mnemonic and flags.
3160 //
3161 // FIXME: Would be nice to autogen this.
3162 // FIXME: This is a bit of a maze of special cases.
3163 StringRef ARMAsmParser::splitMnemonic(StringRef Mnemonic,
3164                                       unsigned &PredicationCode,
3165                                       bool &CarrySetting,
3166                                       unsigned &ProcessorIMod,
3167                                       StringRef &ITMask) {
3168   PredicationCode = ARMCC::AL;
3169   CarrySetting = false;
3170   ProcessorIMod = 0;
3171
3172   // Ignore some mnemonics we know aren't predicated forms.
3173   //
3174   // FIXME: Would be nice to autogen this.
3175   if ((Mnemonic == "movs" && isThumb()) ||
3176       Mnemonic == "teq"   || Mnemonic == "vceq"   || Mnemonic == "svc"   ||
3177       Mnemonic == "mls"   || Mnemonic == "smmls"  || Mnemonic == "vcls"  ||
3178       Mnemonic == "vmls"  || Mnemonic == "vnmls"  || Mnemonic == "vacge" ||
3179       Mnemonic == "vcge"  || Mnemonic == "vclt"   || Mnemonic == "vacgt" ||
3180       Mnemonic == "vcgt"  || Mnemonic == "vcle"   || Mnemonic == "smlal" ||
3181       Mnemonic == "umaal" || Mnemonic == "umlal"  || Mnemonic == "vabal" ||
3182       Mnemonic == "vmlal" || Mnemonic == "vpadal" || Mnemonic == "vqdmlal")
3183     return Mnemonic;
3184
3185   // First, split out any predication code. Ignore mnemonics we know aren't
3186   // predicated but do have a carry-set and so weren't caught above.
3187   if (Mnemonic != "adcs" && Mnemonic != "bics" && Mnemonic != "movs" &&
3188       Mnemonic != "muls" && Mnemonic != "smlals" && Mnemonic != "smulls" &&
3189       Mnemonic != "umlals" && Mnemonic != "umulls" && Mnemonic != "lsls" &&
3190       Mnemonic != "sbcs" && Mnemonic != "rscs") {
3191     unsigned CC = StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2))
3192       .Case("eq", ARMCC::EQ)
3193       .Case("ne", ARMCC::NE)
3194       .Case("hs", ARMCC::HS)
3195       .Case("cs", ARMCC::HS)
3196       .Case("lo", ARMCC::LO)
3197       .Case("cc", ARMCC::LO)
3198       .Case("mi", ARMCC::MI)
3199       .Case("pl", ARMCC::PL)
3200       .Case("vs", ARMCC::VS)
3201       .Case("vc", ARMCC::VC)
3202       .Case("hi", ARMCC::HI)
3203       .Case("ls", ARMCC::LS)
3204       .Case("ge", ARMCC::GE)
3205       .Case("lt", ARMCC::LT)
3206       .Case("gt", ARMCC::GT)
3207       .Case("le", ARMCC::LE)
3208       .Case("al", ARMCC::AL)
3209       .Default(~0U);
3210     if (CC != ~0U) {
3211       Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 2);
3212       PredicationCode = CC;
3213     }
3214   }
3215
3216   // Next, determine if we have a carry setting bit. We explicitly ignore all
3217   // the instructions we know end in 's'.
3218   if (Mnemonic.endswith("s") &&
3219       !(Mnemonic == "cps" || Mnemonic == "mls" ||
3220         Mnemonic == "mrs" || Mnemonic == "smmls" || Mnemonic == "vabs" ||
3221         Mnemonic == "vcls" || Mnemonic == "vmls" || Mnemonic == "vmrs" ||
3222         Mnemonic == "vnmls" || Mnemonic == "vqabs" || Mnemonic == "vrecps" ||
3223         Mnemonic == "vrsqrts" || Mnemonic == "srs" ||
3224         (Mnemonic == "movs" && isThumb()))) {
3225     Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 1);
3226     CarrySetting = true;
3227   }
3228
3229   // The "cps" instruction can have a interrupt mode operand which is glued into
3230   // the mnemonic. Check if this is the case, split it and parse the imod op
3231   if (Mnemonic.startswith("cps")) {
3232     // Split out any imod code.
3233     unsigned IMod =
3234       StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2, 2))
3235       .Case("ie", ARM_PROC::IE)
3236       .Case("id", ARM_PROC::ID)
3237       .Default(~0U);
3238     if (IMod != ~0U) {
3239       Mnemonic = Mnemonic.slice(0, Mnemonic.size()-2);
3240       ProcessorIMod = IMod;
3241     }
3242   }
3243
3244   // The "it" instruction has the condition mask on the end of the mnemonic.
3245   if (Mnemonic.startswith("it")) {
3246     ITMask = Mnemonic.slice(2, Mnemonic.size());
3247     Mnemonic = Mnemonic.slice(0, 2);
3248   }
3249
3250   return Mnemonic;
3251 }
3252
3253 /// \brief Given a canonical mnemonic, determine if the instruction ever allows
3254 /// inclusion of carry set or predication code operands.
3255 //
3256 // FIXME: It would be nice to autogen this.
3257 void ARMAsmParser::
3258 getMnemonicAcceptInfo(StringRef Mnemonic, bool &CanAcceptCarrySet,
3259                       bool &CanAcceptPredicationCode) {
3260   if (Mnemonic == "and" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
3261       Mnemonic == "rrx" || Mnemonic == "ror" || Mnemonic == "sub" ||
3262       Mnemonic == "add" || Mnemonic == "adc" ||
3263       Mnemonic == "mul" || Mnemonic == "bic" || Mnemonic == "asr" ||
3264       Mnemonic == "orr" || Mnemonic == "mvn" ||
3265       Mnemonic == "rsb" || Mnemonic == "rsc" || Mnemonic == "orn" ||
3266       Mnemonic == "sbc" || Mnemonic == "eor" || Mnemonic == "neg" ||
3267       (!isThumb() && (Mnemonic == "smull" || Mnemonic == "mov" ||
3268                       Mnemonic == "mla" || Mnemonic == "smlal" ||
3269                       Mnemonic == "umlal" || Mnemonic == "umull"))) {
3270     CanAcceptCarrySet = true;
3271   } else
3272     CanAcceptCarrySet = false;
3273
3274   if (Mnemonic == "cbnz" || Mnemonic == "setend" || Mnemonic == "dmb" ||
3275       Mnemonic == "cps" || Mnemonic == "mcr2" || Mnemonic == "it" ||
3276       Mnemonic == "mcrr2" || Mnemonic == "cbz" || Mnemonic == "cdp2" ||
3277       Mnemonic == "trap" || Mnemonic == "mrc2" || Mnemonic == "mrrc2" ||
3278       Mnemonic == "dsb" || Mnemonic == "isb" || Mnemonic == "setend" ||
3279       (Mnemonic == "clrex" && !isThumb()) ||
3280       (Mnemonic == "nop" && isThumbOne()) ||
3281       ((Mnemonic == "pld" || Mnemonic == "pli" || Mnemonic == "pldw") &&
3282        !isThumb()) ||
3283       ((Mnemonic.startswith("rfe") || Mnemonic.startswith("srs")) &&
3284        !isThumb()) ||
3285       Mnemonic.startswith("cps") || (Mnemonic == "movs" && isThumbOne())) {
3286     CanAcceptPredicationCode = false;
3287   } else
3288     CanAcceptPredicationCode = true;
3289
3290   if (isThumb()) {
3291     if (Mnemonic == "bkpt" || Mnemonic == "mcr" || Mnemonic == "mcrr" ||
3292         Mnemonic == "mrc" || Mnemonic == "mrrc" || Mnemonic == "cdp")
3293       CanAcceptPredicationCode = false;
3294   }
3295 }
3296
3297 bool ARMAsmParser::shouldOmitCCOutOperand(StringRef Mnemonic,
3298                                SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
3299   // FIXME: This is all horribly hacky. We really need a better way to deal
3300   // with optional operands like this in the matcher table.
3301
3302   // The 'mov' mnemonic is special. One variant has a cc_out operand, while
3303   // another does not. Specifically, the MOVW instruction does not. So we
3304   // special case it here and remove the defaulted (non-setting) cc_out
3305   // operand if that's the instruction we're trying to match.
3306   //
3307   // We do this as post-processing of the explicit operands rather than just
3308   // conditionally adding the cc_out in the first place because we need
3309   // to check the type of the parsed immediate operand.
3310   if (Mnemonic == "mov" && Operands.size() > 4 && !isThumb() &&
3311       !static_cast<ARMOperand*>(Operands[4])->isARMSOImm() &&
3312       static_cast<ARMOperand*>(Operands[4])->isImm0_65535Expr() &&
3313       static_cast<ARMOperand*>(Operands[1])->getReg() == 0)
3314     return true;
3315
3316   // Register-register 'add' for thumb does not have a cc_out operand
3317   // when there are only two register operands.
3318   if (isThumb() && Mnemonic == "add" && Operands.size() == 5 &&
3319       static_cast<ARMOperand*>(Operands[3])->isReg() &&
3320       static_cast<ARMOperand*>(Operands[4])->isReg() &&
3321       static_cast<ARMOperand*>(Operands[1])->getReg() == 0)
3322     return true;
3323   // Register-register 'add' for thumb does not have a cc_out operand
3324   // when it's an ADD Rdm, SP, {Rdm|#imm0_255} instruction. We do
3325   // have to check the immediate range here since Thumb2 has a variant
3326   // that can handle a different range and has a cc_out operand.
3327   if (((isThumb() && Mnemonic == "add") ||
3328        (isThumbTwo() && Mnemonic == "sub")) &&
3329       Operands.size() == 6 &&
3330       static_cast<ARMOperand*>(Operands[3])->isReg() &&
3331       static_cast<ARMOperand*>(Operands[4])->isReg() &&
3332       static_cast<ARMOperand*>(Operands[4])->getReg() == ARM::SP &&
3333       static_cast<ARMOperand*>(Operands[1])->getReg() == 0 &&
3334       (static_cast<ARMOperand*>(Operands[5])->isReg() ||
3335        static_cast<ARMOperand*>(Operands[5])->isImm0_1020s4()))
3336     return true;
3337   // For Thumb2, add/sub immediate does not have a cc_out operand for the
3338   // imm0_4095 variant. That's the least-preferred variant when
3339   // selecting via the generic "add" mnemonic, so to know that we
3340   // should remove the cc_out operand, we have to explicitly check that
3341   // it's not one of the other variants. Ugh.
3342   if (isThumbTwo() && (Mnemonic == "add" || Mnemonic == "sub") &&
3343       Operands.size() == 6 &&
3344       static_cast<ARMOperand*>(Operands[3])->isReg() &&
3345       static_cast<ARMOperand*>(Operands[4])->isReg() &&
3346       static_cast<ARMOperand*>(Operands[5])->isImm()) {
3347     // Nest conditions rather than one big 'if' statement for readability.
3348     //
3349     // If either register is a high reg, it's either one of the SP
3350     // variants (handled above) or a 32-bit encoding, so we just
3351     // check against T3.
3352     if ((!isARMLowRegister(static_cast<ARMOperand*>(Operands[3])->getReg()) ||
3353          !isARMLowRegister(static_cast<ARMOperand*>(Operands[4])->getReg())) &&
3354         static_cast<ARMOperand*>(Operands[5])->isT2SOImm())
3355       return false;
3356     // If both registers are low, we're in an IT block, and the immediate is
3357     // in range, we should use encoding T1 instead, which has a cc_out.
3358     if (inITBlock() &&
3359         isARMLowRegister(static_cast<ARMOperand*>(Operands[3])->getReg()) &&
3360         isARMLowRegister(static_cast<ARMOperand*>(Operands[4])->getReg()) &&
3361         static_cast<ARMOperand*>(Operands[5])->isImm0_7())
3362       return false;
3363
3364     // Otherwise, we use encoding T4, which does not have a cc_out
3365     // operand.
3366     return true;
3367   }
3368
3369   // The thumb2 multiply instruction doesn't have a CCOut register, so
3370   // if we have a "mul" mnemonic in Thumb mode, check if we'll be able to
3371   // use the 16-bit encoding or not.
3372   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 6 &&
3373       static_cast<ARMOperand*>(Operands[1])->getReg() == 0 &&
3374       static_cast<ARMOperand*>(Operands[3])->isReg() &&
3375       static_cast<ARMOperand*>(Operands[4])->isReg() &&
3376       static_cast<ARMOperand*>(Operands[5])->isReg() &&
3377       // If the registers aren't low regs, the destination reg isn't the
3378       // same as one of the source regs, or the cc_out operand is zero
3379       // outside of an IT block, we have to use the 32-bit encoding, so
3380       // remove the cc_out operand.
3381       (!isARMLowRegister(static_cast<ARMOperand*>(Operands[3])->getReg()) ||
3382        !isARMLowRegister(static_cast<ARMOperand*>(Operands[4])->getReg()) ||
3383        !inITBlock() ||
3384        (static_cast<ARMOperand*>(Operands[3])->getReg() !=
3385         static_cast<ARMOperand*>(Operands[5])->getReg() &&
3386         static_cast<ARMOperand*>(Operands[3])->getReg() !=
3387         static_cast<ARMOperand*>(Operands[4])->getReg())))
3388     return true;
3389
3390
3391
3392   // Register-register 'add/sub' for thumb does not have a cc_out operand
3393   // when it's an ADD/SUB SP, #imm. Be lenient on count since there's also
3394   // the "add/sub SP, SP, #imm" version. If the follow-up operands aren't
3395   // right, this will result in better diagnostics (which operand is off)
3396   // anyway.
3397   if (isThumb() && (Mnemonic == "add" || Mnemonic == "sub") &&
3398       (Operands.size() == 5 || Operands.size() == 6) &&
3399       static_cast<ARMOperand*>(Operands[3])->isReg() &&
3400       static_cast<ARMOperand*>(Operands[3])->getReg() == ARM::SP &&
3401       static_cast<ARMOperand*>(Operands[1])->getReg() == 0)
3402     return true;
3403
3404   return false;
3405 }
3406
3407 /// Parse an arm instruction mnemonic followed by its operands.
3408 bool ARMAsmParser::ParseInstruction(StringRef Name, SMLoc NameLoc,
3409                                SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
3410   // Create the leading tokens for the mnemonic, split by '.' characters.
3411   size_t Start = 0, Next = Name.find('.');
3412   StringRef Mnemonic = Name.slice(Start, Next);
3413
3414   // Split out the predication code and carry setting flag from the mnemonic.
3415   unsigned PredicationCode;
3416   unsigned ProcessorIMod;
3417   bool CarrySetting;
3418   StringRef ITMask;
3419   Mnemonic = splitMnemonic(Mnemonic, PredicationCode, CarrySetting,
3420                            ProcessorIMod, ITMask);
3421
3422   // In Thumb1, only the branch (B) instruction can be predicated.
3423   if (isThumbOne() && PredicationCode != ARMCC::AL && Mnemonic != "b") {
3424     Parser.EatToEndOfStatement();
3425     return Error(NameLoc, "conditional execution not supported in Thumb1");
3426   }
3427
3428   Operands.push_back(ARMOperand::CreateToken(Mnemonic, NameLoc));
3429
3430   // Handle the IT instruction ITMask. Convert it to a bitmask. This
3431   // is the mask as it will be for the IT encoding if the conditional
3432   // encoding has a '1' as it's bit0 (i.e. 't' ==> '1'). In the case
3433   // where the conditional bit0 is zero, the instruction post-processing
3434   // will adjust the mask accordingly.
3435   if (Mnemonic == "it") {
3436     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + 2);
3437     if (ITMask.size() > 3) {
3438       Parser.EatToEndOfStatement();
3439       return Error(Loc, "too many conditions on IT instruction");
3440     }
3441     unsigned Mask = 8;
3442     for (unsigned i = ITMask.size(); i != 0; --i) {
3443       char pos = ITMask[i - 1];
3444       if (pos != 't' && pos != 'e') {
3445         Parser.EatToEndOfStatement();
3446         return Error(Loc, "illegal IT block condition mask '" + ITMask + "'");
3447       }
3448       Mask >>= 1;
3449       if (ITMask[i - 1] == 't')
3450         Mask |= 8;
3451     }
3452     Operands.push_back(ARMOperand::CreateITMask(Mask, Loc));
3453   }
3454
3455   // FIXME: This is all a pretty gross hack. We should automatically handle
3456   // optional operands like this via tblgen.
3457
3458   // Next, add the CCOut and ConditionCode operands, if needed.
3459   //
3460   // For mnemonics which can ever incorporate a carry setting bit or predication
3461   // code, our matching model involves us always generating CCOut and
3462   // ConditionCode operands to match the mnemonic "as written" and then we let
3463   // the matcher deal with finding the right instruction or generating an
3464   // appropriate error.
3465   bool CanAcceptCarrySet, CanAcceptPredicationCode;
3466   getMnemonicAcceptInfo(Mnemonic, CanAcceptCarrySet, CanAcceptPredicationCode);
3467
3468   // If we had a carry-set on an instruction that can't do that, issue an
3469   // error.
3470   if (!CanAcceptCarrySet && CarrySetting) {
3471     Parser.EatToEndOfStatement();
3472     return Error(NameLoc, "instruction '" + Mnemonic +
3473                  "' can not set flags, but 's' suffix specified");
3474   }
3475   // If we had a predication code on an instruction that can't do that, issue an
3476   // error.
3477   if (!CanAcceptPredicationCode && PredicationCode != ARMCC::AL) {
3478     Parser.EatToEndOfStatement();
3479     return Error(NameLoc, "instruction '" + Mnemonic +
3480                  "' is not predicable, but condition code specified");
3481   }
3482
3483   // Add the carry setting operand, if necessary.
3484   if (CanAcceptCarrySet) {
3485     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size());
3486     Operands.push_back(ARMOperand::CreateCCOut(CarrySetting ? ARM::CPSR : 0,
3487                                                Loc));
3488   }
3489
3490   // Add the predication code operand, if necessary.
3491   if (CanAcceptPredicationCode) {
3492     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size() +
3493                                       CarrySetting);
3494     Operands.push_back(ARMOperand::CreateCondCode(
3495                          ARMCC::CondCodes(PredicationCode), Loc));
3496   }
3497
3498   // Add the processor imod operand, if necessary.
3499   if (ProcessorIMod) {
3500     Operands.push_back(ARMOperand::CreateImm(
3501           MCConstantExpr::Create(ProcessorIMod, getContext()),
3502                                  NameLoc, NameLoc));
3503   }
3504
3505   // Add the remaining tokens in the mnemonic.
3506   while (Next != StringRef::npos) {
3507     Start = Next;
3508     Next = Name.find('.', Start + 1);
3509     StringRef ExtraToken = Name.slice(Start, Next);
3510
3511     // For now, we're only parsing Thumb1 (for the most part), so
3512     // just ignore ".n" qualifiers. We'll use them to restrict
3513     // matching when we do Thumb2.
3514     if (ExtraToken != ".n") {
3515       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
3516       Operands.push_back(ARMOperand::CreateToken(ExtraToken, Loc));
3517     }
3518   }
3519
3520   // Read the remaining operands.
3521   if (getLexer().isNot(AsmToken::EndOfStatement)) {
3522     // Read the first operand.
3523     if (parseOperand(Operands, Mnemonic)) {
3524       Parser.EatToEndOfStatement();
3525       return true;
3526     }
3527
3528     while (getLexer().is(AsmToken::Comma)) {
3529       Parser.Lex();  // Eat the comma.
3530
3531       // Parse and remember the operand.
3532       if (parseOperand(Operands, Mnemonic)) {
3533         Parser.EatToEndOfStatement();
3534         return true;
3535       }
3536     }
3537   }
3538
3539   if (getLexer().isNot(AsmToken::EndOfStatement)) {
3540     Parser.EatToEndOfStatement();
3541     return TokError("unexpected token in argument list");
3542   }
3543
3544   Parser.Lex(); // Consume the EndOfStatement
3545
3546   // Some instructions, mostly Thumb, have forms for the same mnemonic that
3547   // do and don't have a cc_out optional-def operand. With some spot-checks
3548   // of the operand list, we can figure out which variant we're trying to
3549   // parse and adjust accordingly before actually matching. We shouldn't ever
3550   // try to remove a cc_out operand that was explicitly set on the the
3551   // mnemonic, of course (CarrySetting == true). Reason number #317 the
3552   // table driven matcher doesn't fit well with the ARM instruction set.
3553   if (!CarrySetting && shouldOmitCCOutOperand(Mnemonic, Operands)) {
3554     ARMOperand *Op = static_cast<ARMOperand*>(Operands[1]);
3555     Operands.erase(Operands.begin() + 1);
3556     delete Op;
3557   }
3558
3559   // ARM mode 'blx' need special handling, as the register operand version
3560   // is predicable, but the label operand version is not. So, we can't rely
3561   // on the Mnemonic based checking to correctly figure out when to put
3562   // a CondCode operand in the list. If we're trying to match the label
3563   // version, remove the CondCode operand here.
3564   if (!isThumb() && Mnemonic == "blx" && Operands.size() == 3 &&
3565       static_cast<ARMOperand*>(Operands[2])->isImm()) {
3566     ARMOperand *Op = static_cast<ARMOperand*>(Operands[1]);
3567     Operands.erase(Operands.begin() + 1);
3568     delete Op;
3569   }
3570
3571   // The vector-compare-to-zero instructions have a literal token "#0" at
3572   // the end that comes to here as an immediate operand. Convert it to a
3573   // token to play nicely with the matcher.
3574   if ((Mnemonic == "vceq" || Mnemonic == "vcge" || Mnemonic == "vcgt" ||
3575       Mnemonic == "vcle" || Mnemonic == "vclt") && Operands.size() == 6 &&
3576       static_cast<ARMOperand*>(Operands[5])->isImm()) {
3577     ARMOperand *Op = static_cast<ARMOperand*>(Operands[5]);
3578     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op->getImm());
3579     if (CE && CE->getValue() == 0) {
3580       Operands.erase(Operands.begin() + 5);
3581       Operands.push_back(ARMOperand::CreateToken("#0", Op->getStartLoc()));
3582       delete Op;
3583     }
3584   }
3585   // VCMP{E} does the same thing, but with a different operand count.
3586   if ((Mnemonic == "vcmp" || Mnemonic == "vcmpe") && Operands.size() == 5 &&
3587       static_cast<ARMOperand*>(Operands[4])->isImm()) {
3588     ARMOperand *Op = static_cast<ARMOperand*>(Operands[4]);
3589     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op->getImm());
3590     if (CE && CE->getValue() == 0) {
3591       Operands.erase(Operands.begin() + 4);
3592       Operands.push_back(ARMOperand::CreateToken("#0", Op->getStartLoc()));
3593       delete Op;
3594     }
3595   }
3596   // Similarly, the Thumb1 "RSB" instruction has a literal "#0" on the
3597   // end. Convert it to a token here.
3598   if (Mnemonic == "rsb" && isThumb() && Operands.size() == 6 &&
3599       static_cast<ARMOperand*>(Operands[5])->isImm()) {
3600     ARMOperand *Op = static_cast<ARMOperand*>(Operands[5]);
3601     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op->getImm());
3602     if (CE && CE->getValue() == 0) {
3603       Operands.erase(Operands.begin() + 5);
3604       Operands.push_back(ARMOperand::CreateToken("#0", Op->getStartLoc()));
3605       delete Op;
3606     }
3607   }
3608
3609   return false;
3610 }
3611
3612 // Validate context-sensitive operand constraints.
3613
3614 // return 'true' if register list contains non-low GPR registers,
3615 // 'false' otherwise. If Reg is in the register list or is HiReg, set
3616 // 'containsReg' to true.
3617 static bool checkLowRegisterList(MCInst Inst, unsigned OpNo, unsigned Reg,
3618                                  unsigned HiReg, bool &containsReg) {
3619   containsReg = false;
3620   for (unsigned i = OpNo; i < Inst.getNumOperands(); ++i) {
3621     unsigned OpReg = Inst.getOperand(i).getReg();
3622     if (OpReg == Reg)
3623       containsReg = true;
3624     // Anything other than a low register isn't legal here.
3625     if (!isARMLowRegister(OpReg) && (!HiReg || OpReg != HiReg))
3626       return true;
3627   }
3628   return false;
3629 }
3630
3631 // Check if the specified regisgter is in the register list of the inst,
3632 // starting at the indicated operand number.
3633 static bool listContainsReg(MCInst &Inst, unsigned OpNo, unsigned Reg) {
3634   for (unsigned i = OpNo; i < Inst.getNumOperands(); ++i) {
3635     unsigned OpReg = Inst.getOperand(i).getReg();
3636     if (OpReg == Reg)
3637       return true;
3638   }
3639   return false;
3640 }
3641
3642 // FIXME: We would really prefer to have MCInstrInfo (the wrapper around
3643 // the ARMInsts array) instead. Getting that here requires awkward
3644 // API changes, though. Better way?
3645 namespace llvm {
3646 extern MCInstrDesc ARMInsts[];
3647 }
3648 static MCInstrDesc &getInstDesc(unsigned Opcode) {
3649   return ARMInsts[Opcode];
3650 }
3651
3652 // FIXME: We would really like to be able to tablegen'erate this.
3653 bool ARMAsmParser::
3654 validateInstruction(MCInst &Inst,
3655                     const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
3656   MCInstrDesc &MCID = getInstDesc(Inst.getOpcode());
3657   SMLoc Loc = Operands[0]->getStartLoc();
3658   // Check the IT block state first.
3659   // NOTE: In Thumb mode, the BKPT instruction has the interesting property of
3660   // being allowed in IT blocks, but not being predicable.  It just always
3661   // executes.
3662   if (inITBlock() && Inst.getOpcode() != ARM::tBKPT) {
3663     unsigned bit = 1;
3664     if (ITState.FirstCond)
3665       ITState.FirstCond = false;
3666     else
3667       bit = (ITState.Mask >> (5 - ITState.CurPosition)) & 1;
3668     // The instruction must be predicable.
3669     if (!MCID.isPredicable())
3670       return Error(Loc, "instructions in IT block must be predicable");
3671     unsigned Cond = Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm();
3672     unsigned ITCond = bit ? ITState.Cond :
3673       ARMCC::getOppositeCondition(ITState.Cond);
3674     if (Cond != ITCond) {
3675       // Find the condition code Operand to get its SMLoc information.
3676       SMLoc CondLoc;
3677       for (unsigned i = 1; i < Operands.size(); ++i)
3678         if (static_cast<ARMOperand*>(Operands[i])->isCondCode())
3679           CondLoc = Operands[i]->getStartLoc();
3680       return Error(CondLoc, "incorrect condition in IT block; got '" +
3681                    StringRef(ARMCondCodeToString(ARMCC::CondCodes(Cond))) +
3682                    "', but expected '" +
3683                    ARMCondCodeToString(ARMCC::CondCodes(ITCond)) + "'");
3684     }
3685   // Check for non-'al' condition codes outside of the IT block.
3686   } else if (isThumbTwo() && MCID.isPredicable() &&
3687              Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm() !=
3688              ARMCC::AL && Inst.getOpcode() != ARM::tB &&
3689              Inst.getOpcode() != ARM::t2B)
3690     return Error(Loc, "predicated instructions must be in IT block");
3691
3692   switch (Inst.getOpcode()) {
3693   case ARM::LDRD:
3694   case ARM::LDRD_PRE:
3695   case ARM::LDRD_POST:
3696   case ARM::LDREXD: {
3697     // Rt2 must be Rt + 1.
3698     unsigned Rt = getARMRegisterNumbering(Inst.getOperand(0).getReg());
3699     unsigned Rt2 = getARMRegisterNumbering(Inst.getOperand(1).getReg());
3700     if (Rt2 != Rt + 1)
3701       return Error(Operands[3]->getStartLoc(),
3702                    "destination operands must be sequential");
3703     return false;
3704   }
3705   case ARM::STRD: {
3706     // Rt2 must be Rt + 1.
3707     unsigned Rt = getARMRegisterNumbering(Inst.getOperand(0).getReg());
3708     unsigned Rt2 = getARMRegisterNumbering(Inst.getOperand(1).getReg());
3709     if (Rt2 != Rt + 1)
3710       return Error(Operands[3]->getStartLoc(),
3711                    "source operands must be sequential");
3712     return false;
3713   }
3714   case ARM::STRD_PRE:
3715   case ARM::STRD_POST:
3716   case ARM::STREXD: {
3717     // Rt2 must be Rt + 1.
3718     unsigned Rt = getARMRegisterNumbering(Inst.getOperand(1).getReg());
3719     unsigned Rt2 = getARMRegisterNumbering(Inst.getOperand(2).getReg());
3720     if (Rt2 != Rt + 1)
3721       return Error(Operands[3]->getStartLoc(),
3722                    "source operands must be sequential");
3723     return false;
3724   }
3725   case ARM::SBFX:
3726   case ARM::UBFX: {
3727     // width must be in range [1, 32-lsb]
3728     unsigned lsb = Inst.getOperand(2).getImm();
3729     unsigned widthm1 = Inst.getOperand(3).getImm();
3730     if (widthm1 >= 32 - lsb)
3731       return Error(Operands[5]->getStartLoc(),
3732                    "bitfield width must be in range [1,32-lsb]");
3733     return false;
3734   }
3735   case ARM::tLDMIA: {
3736     // If we're parsing Thumb2, the .w variant is available and handles
3737     // most cases that are normally illegal for a Thumb1 LDM
3738     // instruction. We'll make the transformation in processInstruction()
3739     // if necessary.
3740     //
3741     // Thumb LDM instructions are writeback iff the base register is not
3742     // in the register list.
3743     unsigned Rn = Inst.getOperand(0).getReg();
3744     bool hasWritebackToken =
3745       (static_cast<ARMOperand*>(Operands[3])->isToken() &&
3746        static_cast<ARMOperand*>(Operands[3])->getToken() == "!");
3747     bool listContainsBase;
3748     if (checkLowRegisterList(Inst, 3, Rn, 0, listContainsBase) && !isThumbTwo())
3749       return Error(Operands[3 + hasWritebackToken]->getStartLoc(),
3750                    "registers must be in range r0-r7");
3751     // If we should have writeback, then there should be a '!' token.
3752     if (!listContainsBase && !hasWritebackToken && !isThumbTwo())
3753       return Error(Operands[2]->getStartLoc(),
3754                    "writeback operator '!' expected");
3755     // If we should not have writeback, there must not be a '!'. This is
3756     // true even for the 32-bit wide encodings.
3757     if (listContainsBase && hasWritebackToken)
3758       return Error(Operands[3]->getStartLoc(),
3759                    "writeback operator '!' not allowed when base register "
3760                    "in register list");
3761
3762     break;
3763   }
3764   case ARM::t2LDMIA_UPD: {
3765     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
3766       return Error(Operands[4]->getStartLoc(),
3767                    "writeback operator '!' not allowed when base register "
3768                    "in register list");
3769     break;
3770   }
3771   case ARM::tPOP: {
3772     bool listContainsBase;
3773     if (checkLowRegisterList(Inst, 3, 0, ARM::PC, listContainsBase))
3774       return Error(Operands[2]->getStartLoc(),
3775                    "registers must be in range r0-r7 or pc");
3776     break;
3777   }
3778   case ARM::tPUSH: {
3779     bool listContainsBase;
3780     if (checkLowRegisterList(Inst, 3, 0, ARM::LR, listContainsBase))
3781       return Error(Operands[2]->getStartLoc(),
3782                    "registers must be in range r0-r7 or lr");
3783     break;
3784   }
3785   case ARM::tSTMIA_UPD: {
3786     bool listContainsBase;
3787     if (checkLowRegisterList(Inst, 4, 0, 0, listContainsBase) && !isThumbTwo())
3788       return Error(Operands[4]->getStartLoc(),
3789                    "registers must be in range r0-r7");
3790     break;
3791   }
3792   }
3793
3794   return false;
3795 }
3796
3797 void ARMAsmParser::
3798 processInstruction(MCInst &Inst,
3799                    const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
3800   switch (Inst.getOpcode()) {
3801   case ARM::LDMIA_UPD:
3802     // If this is a load of a single register via a 'pop', then we should use
3803     // a post-indexed LDR instruction instead, per the ARM ARM.
3804     if (static_cast<ARMOperand*>(Operands[0])->getToken() == "pop" &&
3805         Inst.getNumOperands() == 5) {
3806       MCInst TmpInst;
3807       TmpInst.setOpcode(ARM::LDR_POST_IMM);
3808       TmpInst.addOperand(Inst.getOperand(4)); // Rt
3809       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
3810       TmpInst.addOperand(Inst.getOperand(1)); // Rn
3811       TmpInst.addOperand(MCOperand::CreateReg(0));  // am2offset
3812       TmpInst.addOperand(MCOperand::CreateImm(4));
3813       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
3814       TmpInst.addOperand(Inst.getOperand(3));
3815       Inst = TmpInst;
3816     }
3817     break;
3818   case ARM::STMDB_UPD:
3819     // If this is a store of a single register via a 'push', then we should use
3820     // a pre-indexed STR instruction instead, per the ARM ARM.
3821     if (static_cast<ARMOperand*>(Operands[0])->getToken() == "push" &&
3822         Inst.getNumOperands() == 5) {
3823       MCInst TmpInst;
3824       TmpInst.setOpcode(ARM::STR_PRE_IMM);
3825       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
3826       TmpInst.addOperand(Inst.getOperand(4)); // Rt
3827       TmpInst.addOperand(Inst.getOperand(1)); // addrmode_imm12
3828       TmpInst.addOperand(MCOperand::CreateImm(-4));
3829       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
3830       TmpInst.addOperand(Inst.getOperand(3));
3831       Inst = TmpInst;
3832     }
3833     break;
3834   case ARM::tADDi8:
3835     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
3836     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
3837     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
3838     // to encoding T1 if <Rd> is omitted."
3839     if (Inst.getOperand(3).getImm() < 8 && Operands.size() == 6)
3840       Inst.setOpcode(ARM::tADDi3);
3841     break;
3842   case ARM::tSUBi8:
3843     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
3844     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
3845     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
3846     // to encoding T1 if <Rd> is omitted."
3847     if (Inst.getOperand(3).getImm() < 8 && Operands.size() == 6)
3848       Inst.setOpcode(ARM::tSUBi3);
3849     break;
3850   case ARM::tB:
3851     // A Thumb conditional branch outside of an IT block is a tBcc.
3852     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock())
3853       Inst.setOpcode(ARM::tBcc);
3854     break;
3855   case ARM::t2B:
3856     // A Thumb2 conditional branch outside of an IT block is a t2Bcc.
3857     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock())
3858       Inst.setOpcode(ARM::t2Bcc);
3859     break;
3860   case ARM::t2Bcc:
3861     // If the conditional is AL or we're in an IT block, we really want t2B.
3862     if (Inst.getOperand(1).getImm() == ARMCC::AL || inITBlock())
3863       Inst.setOpcode(ARM::t2B);
3864     break;
3865   case ARM::tBcc:
3866     // If the conditional is AL, we really want tB.
3867     if (Inst.getOperand(1).getImm() == ARMCC::AL)
3868       Inst.setOpcode(ARM::tB);
3869     break;
3870   case ARM::tLDMIA: {
3871     // If the register list contains any high registers, or if the writeback
3872     // doesn't match what tLDMIA can do, we need to use the 32-bit encoding
3873     // instead if we're in Thumb2. Otherwise, this should have generated
3874     // an error in validateInstruction().
3875     unsigned Rn = Inst.getOperand(0).getReg();
3876     bool hasWritebackToken =
3877       (static_cast<ARMOperand*>(Operands[3])->isToken() &&
3878        static_cast<ARMOperand*>(Operands[3])->getToken() == "!");
3879     bool listContainsBase;
3880     if (checkLowRegisterList(Inst, 3, Rn, 0, listContainsBase) ||
3881         (!listContainsBase && !hasWritebackToken) ||
3882         (listContainsBase && hasWritebackToken)) {
3883       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
3884       assert (isThumbTwo());
3885       Inst.setOpcode(hasWritebackToken ? ARM::t2LDMIA_UPD : ARM::t2LDMIA);
3886       // If we're switching to the updating version, we need to insert
3887       // the writeback tied operand.
3888       if (hasWritebackToken)
3889         Inst.insert(Inst.begin(),
3890                     MCOperand::CreateReg(Inst.getOperand(0).getReg()));
3891     }
3892     break;
3893   }
3894   case ARM::tSTMIA_UPD: {
3895     // If the register list contains any high registers, we need to use
3896     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
3897     // should have generated an error in validateInstruction().
3898     unsigned Rn = Inst.getOperand(0).getReg();
3899     bool listContainsBase;
3900     if (checkLowRegisterList(Inst, 4, Rn, 0, listContainsBase)) {
3901       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
3902       assert (isThumbTwo());
3903       Inst.setOpcode(ARM::t2STMIA_UPD);
3904     }
3905     break;
3906   }
3907   case ARM::t2MOVi: {
3908     // If we can use the 16-bit encoding and the user didn't explicitly
3909     // request the 32-bit variant, transform it here.
3910     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
3911         Inst.getOperand(1).getImm() <= 255 &&
3912         ((!inITBlock() && Inst.getOperand(2).getImm() == ARMCC::AL &&
3913          Inst.getOperand(4).getReg() == ARM::CPSR) ||
3914         (inITBlock() && Inst.getOperand(4).getReg() == 0)) &&
3915         (!static_cast<ARMOperand*>(Operands[2])->isToken() ||
3916          static_cast<ARMOperand*>(Operands[2])->getToken() != ".w")) {
3917       // The operands aren't in the same order for tMOVi8...
3918       MCInst TmpInst;
3919       TmpInst.setOpcode(ARM::tMOVi8);
3920       TmpInst.addOperand(Inst.getOperand(0));
3921       TmpInst.addOperand(Inst.getOperand(4));
3922       TmpInst.addOperand(Inst.getOperand(1));
3923       TmpInst.addOperand(Inst.getOperand(2));
3924       TmpInst.addOperand(Inst.getOperand(3));
3925       Inst = TmpInst;
3926     }
3927     break;
3928   }
3929   case ARM::t2MOVr: {
3930     // If we can use the 16-bit encoding and the user didn't explicitly
3931     // request the 32-bit variant, transform it here.
3932     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
3933         isARMLowRegister(Inst.getOperand(1).getReg()) &&
3934         Inst.getOperand(2).getImm() == ARMCC::AL &&
3935         Inst.getOperand(4).getReg() == ARM::CPSR &&
3936         (!static_cast<ARMOperand*>(Operands[2])->isToken() ||
3937          static_cast<ARMOperand*>(Operands[2])->getToken() != ".w")) {
3938       // The operands aren't the same for tMOV[S]r... (no cc_out)
3939       MCInst TmpInst;
3940       TmpInst.setOpcode(Inst.getOperand(4).getReg() ? ARM::tMOVSr : ARM::tMOVr);
3941       TmpInst.addOperand(Inst.getOperand(0));
3942       TmpInst.addOperand(Inst.getOperand(1));
3943       TmpInst.addOperand(Inst.getOperand(2));
3944       TmpInst.addOperand(Inst.getOperand(3));
3945       Inst = TmpInst;
3946     }
3947     break;
3948   }
3949   case ARM::t2SXTH:
3950   case ARM::t2SXTB:
3951   case ARM::t2UXTH:
3952   case ARM::t2UXTB: {
3953     // If we can use the 16-bit encoding and the user didn't explicitly
3954     // request the 32-bit variant, transform it here.
3955     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
3956         isARMLowRegister(Inst.getOperand(1).getReg()) &&
3957         Inst.getOperand(2).getImm() == 0 &&
3958         (!static_cast<ARMOperand*>(Operands[2])->isToken() ||
3959          static_cast<ARMOperand*>(Operands[2])->getToken() != ".w")) {
3960       unsigned NewOpc;
3961       switch (Inst.getOpcode()) {
3962       default: llvm_unreachable("Illegal opcode!");
3963       case ARM::t2SXTH: NewOpc = ARM::tSXTH; break;
3964       case ARM::t2SXTB: NewOpc = ARM::tSXTB; break;
3965       case ARM::t2UXTH: NewOpc = ARM::tUXTH; break;
3966       case ARM::t2UXTB: NewOpc = ARM::tUXTB; break;
3967       }
3968       // The operands aren't the same for thumb1 (no rotate operand).
3969       MCInst TmpInst;
3970       TmpInst.setOpcode(NewOpc);
3971       TmpInst.addOperand(Inst.getOperand(0));
3972       TmpInst.addOperand(Inst.getOperand(1));
3973       TmpInst.addOperand(Inst.getOperand(3));
3974       TmpInst.addOperand(Inst.getOperand(4));
3975       Inst = TmpInst;
3976     }
3977     break;
3978   }
3979   case ARM::t2IT: {
3980     // The mask bits for all but the first condition are represented as
3981     // the low bit of the condition code value implies 't'. We currently
3982     // always have 1 implies 't', so XOR toggle the bits if the low bit
3983     // of the condition code is zero. The encoding also expects the low
3984     // bit of the condition to be encoded as bit 4 of the mask operand,
3985     // so mask that in if needed
3986     MCOperand &MO = Inst.getOperand(1);
3987     unsigned Mask = MO.getImm();
3988     unsigned OrigMask = Mask;
3989     unsigned TZ = CountTrailingZeros_32(Mask);
3990     if ((Inst.getOperand(0).getImm() & 1) == 0) {
3991       assert(Mask && TZ <= 3 && "illegal IT mask value!");
3992       for (unsigned i = 3; i != TZ; --i)
3993         Mask ^= 1 << i;
3994     } else
3995       Mask |= 0x10;
3996     MO.setImm(Mask);
3997
3998     // Set up the IT block state according to the IT instruction we just
3999     // matched.
4000     assert(!inITBlock() && "nested IT blocks?!");
4001     ITState.Cond = ARMCC::CondCodes(Inst.getOperand(0).getImm());
4002     ITState.Mask = OrigMask; // Use the original mask, not the updated one.
4003     ITState.CurPosition = 0;
4004     ITState.FirstCond = true;
4005     break;
4006   }
4007   }
4008 }
4009
4010 unsigned ARMAsmParser::checkTargetMatchPredicate(MCInst &Inst) {
4011   // 16-bit thumb arithmetic instructions either require or preclude the 'S'
4012   // suffix depending on whether they're in an IT block or not.
4013   unsigned Opc = Inst.getOpcode();
4014   MCInstrDesc &MCID = getInstDesc(Opc);
4015   if (MCID.TSFlags & ARMII::ThumbArithFlagSetting) {
4016     assert(MCID.hasOptionalDef() &&
4017            "optionally flag setting instruction missing optional def operand");
4018     assert(MCID.NumOperands == Inst.getNumOperands() &&
4019            "operand count mismatch!");
4020     // Find the optional-def operand (cc_out).
4021     unsigned OpNo;
4022     for (OpNo = 0;
4023          !MCID.OpInfo[OpNo].isOptionalDef() && OpNo < MCID.NumOperands;
4024          ++OpNo)
4025       ;
4026     // If we're parsing Thumb1, reject it completely.
4027     if (isThumbOne() && Inst.getOperand(OpNo).getReg() != ARM::CPSR)
4028       return Match_MnemonicFail;
4029     // If we're parsing Thumb2, which form is legal depends on whether we're
4030     // in an IT block.
4031     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() != ARM::CPSR &&
4032         !inITBlock())
4033       return Match_RequiresITBlock;
4034     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() == ARM::CPSR &&
4035         inITBlock())
4036       return Match_RequiresNotITBlock;
4037   }
4038   // Some high-register supporting Thumb1 encodings only allow both registers
4039   // to be from r0-r7 when in Thumb2.
4040   else if (Opc == ARM::tADDhirr && isThumbOne() &&
4041            isARMLowRegister(Inst.getOperand(1).getReg()) &&
4042            isARMLowRegister(Inst.getOperand(2).getReg()))
4043     return Match_RequiresThumb2;
4044   // Others only require ARMv6 or later.
4045   else if (Opc == ARM::tMOVr && isThumbOne() && !hasV6Ops() &&
4046            isARMLowRegister(Inst.getOperand(0).getReg()) &&
4047            isARMLowRegister(Inst.getOperand(1).getReg()))
4048     return Match_RequiresV6;
4049   return Match_Success;
4050 }
4051
4052 bool ARMAsmParser::
4053 MatchAndEmitInstruction(SMLoc IDLoc,
4054                         SmallVectorImpl<MCParsedAsmOperand*> &Operands,
4055                         MCStreamer &Out) {
4056   MCInst Inst;
4057   unsigned ErrorInfo;
4058   unsigned MatchResult;
4059   MatchResult = MatchInstructionImpl(Operands, Inst, ErrorInfo);
4060   switch (MatchResult) {
4061   default: break;
4062   case Match_Success:
4063     // Context sensitive operand constraints aren't handled by the matcher,
4064     // so check them here.
4065     if (validateInstruction(Inst, Operands)) {
4066       // Still progress the IT block, otherwise one wrong condition causes
4067       // nasty cascading errors.
4068       forwardITPosition();
4069       return true;
4070     }
4071
4072     // Some instructions need post-processing to, for example, tweak which
4073     // encoding is selected.
4074     processInstruction(Inst, Operands);
4075
4076     // Only move forward at the very end so that everything in validate
4077     // and process gets a consistent answer about whether we're in an IT
4078     // block.
4079     forwardITPosition();
4080
4081     Out.EmitInstruction(Inst);
4082     return false;
4083   case Match_MissingFeature:
4084     Error(IDLoc, "instruction requires a CPU feature not currently enabled");
4085     return true;
4086   case Match_InvalidOperand: {
4087     SMLoc ErrorLoc = IDLoc;
4088     if (ErrorInfo != ~0U) {
4089       if (ErrorInfo >= Operands.size())
4090         return Error(IDLoc, "too few operands for instruction");
4091
4092       ErrorLoc = ((ARMOperand*)Operands[ErrorInfo])->getStartLoc();
4093       if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
4094     }
4095
4096     return Error(ErrorLoc, "invalid operand for instruction");
4097   }
4098   case Match_MnemonicFail:
4099     return Error(IDLoc, "invalid instruction");
4100   case Match_ConversionFail:
4101     // The converter function will have already emited a diagnostic.
4102     return true;
4103   case Match_RequiresNotITBlock:
4104     return Error(IDLoc, "flag setting instruction only valid outside IT block");
4105   case Match_RequiresITBlock:
4106     return Error(IDLoc, "instruction only valid inside IT block");
4107   case Match_RequiresV6:
4108     return Error(IDLoc, "instruction variant requires ARMv6 or later");
4109   case Match_RequiresThumb2:
4110     return Error(IDLoc, "instruction variant requires Thumb2");
4111   }
4112
4113   llvm_unreachable("Implement any new match types added!");
4114   return true;
4115 }
4116
4117 /// parseDirective parses the arm specific directives
4118 bool ARMAsmParser::ParseDirective(AsmToken DirectiveID) {
4119   StringRef IDVal = DirectiveID.getIdentifier();
4120   if (IDVal == ".word")
4121     return parseDirectiveWord(4, DirectiveID.getLoc());
4122   else if (IDVal == ".thumb")
4123     return parseDirectiveThumb(DirectiveID.getLoc());
4124   else if (IDVal == ".thumb_func")
4125     return parseDirectiveThumbFunc(DirectiveID.getLoc());
4126   else if (IDVal == ".code")
4127     return parseDirectiveCode(DirectiveID.getLoc());
4128   else if (IDVal == ".syntax")
4129     return parseDirectiveSyntax(DirectiveID.getLoc());
4130   return true;
4131 }
4132
4133 /// parseDirectiveWord
4134 ///  ::= .word [ expression (, expression)* ]
4135 bool ARMAsmParser::parseDirectiveWord(unsigned Size, SMLoc L) {
4136   if (getLexer().isNot(AsmToken::EndOfStatement)) {
4137     for (;;) {
4138       const MCExpr *Value;
4139       if (getParser().ParseExpression(Value))
4140         return true;
4141
4142       getParser().getStreamer().EmitValue(Value, Size, 0/*addrspace*/);
4143
4144       if (getLexer().is(AsmToken::EndOfStatement))
4145         break;
4146
4147       // FIXME: Improve diagnostic.
4148       if (getLexer().isNot(AsmToken::Comma))
4149         return Error(L, "unexpected token in directive");
4150       Parser.Lex();
4151     }
4152   }
4153
4154   Parser.Lex();
4155   return false;
4156 }
4157
4158 /// parseDirectiveThumb
4159 ///  ::= .thumb
4160 bool ARMAsmParser::parseDirectiveThumb(SMLoc L) {
4161   if (getLexer().isNot(AsmToken::EndOfStatement))
4162     return Error(L, "unexpected token in directive");
4163   Parser.Lex();
4164
4165   // TODO: set thumb mode
4166   // TODO: tell the MC streamer the mode
4167   // getParser().getStreamer().Emit???();
4168   return false;
4169 }
4170
4171 /// parseDirectiveThumbFunc
4172 ///  ::= .thumbfunc symbol_name
4173 bool ARMAsmParser::parseDirectiveThumbFunc(SMLoc L) {
4174   const MCAsmInfo &MAI = getParser().getStreamer().getContext().getAsmInfo();
4175   bool isMachO = MAI.hasSubsectionsViaSymbols();
4176   StringRef Name;
4177
4178   // Darwin asm has function name after .thumb_func direction
4179   // ELF doesn't
4180   if (isMachO) {
4181     const AsmToken &Tok = Parser.getTok();
4182     if (Tok.isNot(AsmToken::Identifier) && Tok.isNot(AsmToken::String))
4183       return Error(L, "unexpected token in .thumb_func directive");
4184     Name = Tok.getString();
4185     Parser.Lex(); // Consume the identifier token.
4186   }
4187
4188   if (getLexer().isNot(AsmToken::EndOfStatement))
4189     return Error(L, "unexpected token in directive");
4190   Parser.Lex();
4191
4192   // FIXME: assuming function name will be the line following .thumb_func
4193   if (!isMachO) {
4194     Name = Parser.getTok().getString();
4195   }
4196
4197   // Mark symbol as a thumb symbol.
4198   MCSymbol *Func = getParser().getContext().GetOrCreateSymbol(Name);
4199   getParser().getStreamer().EmitThumbFunc(Func);
4200   return false;
4201 }
4202
4203 /// parseDirectiveSyntax
4204 ///  ::= .syntax unified | divided
4205 bool ARMAsmParser::parseDirectiveSyntax(SMLoc L) {
4206   const AsmToken &Tok = Parser.getTok();
4207   if (Tok.isNot(AsmToken::Identifier))
4208     return Error(L, "unexpected token in .syntax directive");
4209   StringRef Mode = Tok.getString();
4210   if (Mode == "unified" || Mode == "UNIFIED")
4211     Parser.Lex();
4212   else if (Mode == "divided" || Mode == "DIVIDED")
4213     return Error(L, "'.syntax divided' arm asssembly not supported");
4214   else
4215     return Error(L, "unrecognized syntax mode in .syntax directive");
4216
4217   if (getLexer().isNot(AsmToken::EndOfStatement))
4218     return Error(Parser.getTok().getLoc(), "unexpected token in directive");
4219   Parser.Lex();
4220
4221   // TODO tell the MC streamer the mode
4222   // getParser().getStreamer().Emit???();
4223   return false;
4224 }
4225
4226 /// parseDirectiveCode
4227 ///  ::= .code 16 | 32
4228 bool ARMAsmParser::parseDirectiveCode(SMLoc L) {
4229   const AsmToken &Tok = Parser.getTok();
4230   if (Tok.isNot(AsmToken::Integer))
4231     return Error(L, "unexpected token in .code directive");
4232   int64_t Val = Parser.getTok().getIntVal();
4233   if (Val == 16)
4234     Parser.Lex();
4235   else if (Val == 32)
4236     Parser.Lex();
4237   else
4238     return Error(L, "invalid operand to .code directive");
4239
4240   if (getLexer().isNot(AsmToken::EndOfStatement))
4241     return Error(Parser.getTok().getLoc(), "unexpected token in directive");
4242   Parser.Lex();
4243
4244   if (Val == 16) {
4245     if (!isThumb())
4246       SwitchMode();
4247     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
4248   } else {
4249     if (isThumb())
4250       SwitchMode();
4251     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
4252   }
4253
4254   return false;
4255 }
4256
4257 extern "C" void LLVMInitializeARMAsmLexer();
4258
4259 /// Force static initialization.
4260 extern "C" void LLVMInitializeARMAsmParser() {
4261   RegisterMCAsmParser<ARMAsmParser> X(TheARMTarget);
4262   RegisterMCAsmParser<ARMAsmParser> Y(TheThumbTarget);
4263   LLVMInitializeARMAsmLexer();
4264 }
4265
4266 #define GET_REGISTER_MATCHER
4267 #define GET_MATCHER_IMPLEMENTATION
4268 #include "ARMGenAsmMatcher.inc"