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