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