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