McARM: Add a variety of asserts on the sanity of memory operands.
[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 "ARM.h"
11 #include "ARMAddressingModes.h"
12 #include "ARMMCExpr.h"
13 #include "ARMBaseRegisterInfo.h"
14 #include "ARMSubtarget.h"
15 #include "llvm/MC/MCParser/MCAsmLexer.h"
16 #include "llvm/MC/MCParser/MCAsmParser.h"
17 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
18 #include "llvm/MC/MCContext.h"
19 #include "llvm/MC/MCStreamer.h"
20 #include "llvm/MC/MCExpr.h"
21 #include "llvm/MC/MCInst.h"
22 #include "llvm/Target/TargetRegistry.h"
23 #include "llvm/Target/TargetAsmParser.h"
24 #include "llvm/Support/SourceMgr.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/ADT/StringSwitch.h"
29 #include "llvm/ADT/Twine.h"
30 using namespace llvm;
31
32 /// Shift types used for register controlled shifts in ARM memory addressing.
33 enum ShiftType {
34   Lsl,
35   Lsr,
36   Asr,
37   Ror,
38   Rrx
39 };
40
41 namespace {
42
43 class ARMOperand;
44
45 class ARMAsmParser : public TargetAsmParser {
46   MCAsmParser &Parser;
47   TargetMachine &TM;
48
49   MCAsmParser &getParser() const { return Parser; }
50   MCAsmLexer &getLexer() const { return Parser.getLexer(); }
51
52   void Warning(SMLoc L, const Twine &Msg) { Parser.Warning(L, Msg); }
53   bool Error(SMLoc L, const Twine &Msg) { return Parser.Error(L, Msg); }
54
55   int TryParseRegister();
56   bool TryParseMCRName(SmallVectorImpl<MCParsedAsmOperand*>&);
57   bool TryParseRegisterWithWriteBack(SmallVectorImpl<MCParsedAsmOperand*> &);
58   bool ParseRegisterList(SmallVectorImpl<MCParsedAsmOperand*> &);
59   bool ParseMemory(SmallVectorImpl<MCParsedAsmOperand*> &);
60   bool ParseOperand(SmallVectorImpl<MCParsedAsmOperand*> &, bool isMCR);
61   bool ParsePrefix(ARMMCExpr::VariantKind &RefKind);
62   const MCExpr *ApplyPrefixToExpr(const MCExpr *E,
63                                   MCSymbolRefExpr::VariantKind Variant);
64
65
66   bool ParseMemoryOffsetReg(bool &Negative,
67                             bool &OffsetRegShifted,
68                             enum ShiftType &ShiftType,
69                             const MCExpr *&ShiftAmount,
70                             const MCExpr *&Offset,
71                             bool &OffsetIsReg,
72                             int &OffsetRegNum,
73                             SMLoc &E);
74   bool ParseShift(enum ShiftType &St, const MCExpr *&ShiftAmount, SMLoc &E);
75   bool ParseDirectiveWord(unsigned Size, SMLoc L);
76   bool ParseDirectiveThumb(SMLoc L);
77   bool ParseDirectiveThumbFunc(SMLoc L);
78   bool ParseDirectiveCode(SMLoc L);
79   bool ParseDirectiveSyntax(SMLoc L);
80
81   bool MatchAndEmitInstruction(SMLoc IDLoc,
82                                SmallVectorImpl<MCParsedAsmOperand*> &Operands,
83                                MCStreamer &Out);
84
85   /// @name Auto-generated Match Functions
86   /// {
87
88 #define GET_ASSEMBLER_HEADER
89 #include "ARMGenAsmMatcher.inc"
90
91   /// }
92
93 public:
94   ARMAsmParser(const Target &T, MCAsmParser &_Parser, TargetMachine &_TM)
95     : TargetAsmParser(T), Parser(_Parser), TM(_TM) {
96       // Initialize the set of available features.
97       setAvailableFeatures(ComputeAvailableFeatures(
98           &TM.getSubtarget<ARMSubtarget>()));
99     }
100
101   virtual bool ParseInstruction(StringRef Name, SMLoc NameLoc,
102                                 SmallVectorImpl<MCParsedAsmOperand*> &Operands);
103   virtual bool ParseDirective(AsmToken DirectiveID);
104 };
105 } // end anonymous namespace
106
107 namespace {
108
109 /// ARMOperand - Instances of this class represent a parsed ARM machine
110 /// instruction.
111 class ARMOperand : public MCParsedAsmOperand {
112   enum KindTy {
113     CondCode,
114     CCOut,
115     Immediate,
116     Memory,
117     Register,
118     RegisterList,
119     DPRRegisterList,
120     SPRRegisterList,
121     Token
122   } Kind;
123
124   SMLoc StartLoc, EndLoc;
125   SmallVector<unsigned, 8> Registers;
126
127   union {
128     struct {
129       ARMCC::CondCodes Val;
130     } CC;
131
132     struct {
133       const char *Data;
134       unsigned Length;
135     } Tok;
136
137     struct {
138       unsigned RegNum;
139     } Reg;
140
141     struct {
142       const MCExpr *Val;
143     } Imm;
144
145     /// Combined record for all forms of ARM address expressions.
146     struct {
147       unsigned BaseRegNum;
148       unsigned OffsetRegNum;         // used when OffsetIsReg is true
149       const MCExpr *Offset;          // used when OffsetIsReg is false
150       const MCExpr *ShiftAmount;     // used when OffsetRegShifted is true
151       enum ShiftType ShiftType;      // used when OffsetRegShifted is true
152       unsigned OffsetRegShifted : 1; // only used when OffsetIsReg is true
153       unsigned Preindexed       : 1;
154       unsigned Postindexed      : 1;
155       unsigned OffsetIsReg      : 1;
156       unsigned Negative         : 1; // only used when OffsetIsReg is true
157       unsigned Writeback        : 1;
158     } Mem;
159   };
160
161   ARMOperand(KindTy K) : MCParsedAsmOperand(), Kind(K) {}
162 public:
163   ARMOperand(const ARMOperand &o) : MCParsedAsmOperand() {
164     Kind = o.Kind;
165     StartLoc = o.StartLoc;
166     EndLoc = o.EndLoc;
167     switch (Kind) {
168     case CondCode:
169       CC = o.CC;
170       break;
171     case Token:
172       Tok = o.Tok;
173       break;
174     case CCOut:
175     case Register:
176       Reg = o.Reg;
177       break;
178     case RegisterList:
179     case DPRRegisterList:
180     case SPRRegisterList:
181       Registers = o.Registers;
182       break;
183     case Immediate:
184       Imm = o.Imm;
185       break;
186     case Memory:
187       Mem = o.Mem;
188       break;
189     }
190   }
191
192   /// getStartLoc - Get the location of the first token of this operand.
193   SMLoc getStartLoc() const { return StartLoc; }
194   /// getEndLoc - Get the location of the last token of this operand.
195   SMLoc getEndLoc() const { return EndLoc; }
196
197   ARMCC::CondCodes getCondCode() const {
198     assert(Kind == CondCode && "Invalid access!");
199     return CC.Val;
200   }
201
202   StringRef getToken() const {
203     assert(Kind == Token && "Invalid access!");
204     return StringRef(Tok.Data, Tok.Length);
205   }
206
207   unsigned getReg() const {
208     assert((Kind == Register || Kind == CCOut) && "Invalid access!");
209     return Reg.RegNum;
210   }
211
212   const SmallVectorImpl<unsigned> &getRegList() const {
213     assert((Kind == RegisterList || Kind == DPRRegisterList ||
214             Kind == SPRRegisterList) && "Invalid access!");
215     return Registers;
216   }
217
218   const MCExpr *getImm() const {
219     assert(Kind == Immediate && "Invalid access!");
220     return Imm.Val;
221   }
222
223   bool isCondCode() const { return Kind == CondCode; }
224   bool isCCOut() const { return Kind == CCOut; }
225   bool isImm() const { return Kind == Immediate; }
226   bool isReg() const { return Kind == Register; }
227   bool isRegList() const { return Kind == RegisterList; }
228   bool isDPRRegList() const { return Kind == DPRRegisterList; }
229   bool isSPRRegList() const { return Kind == SPRRegisterList; }
230   bool isToken() const { return Kind == Token; }
231   bool isMemory() const { return Kind == Memory; }
232   bool isMemMode5() const {
233     if (!isMemory() || Mem.OffsetIsReg || Mem.OffsetRegShifted ||
234         Mem.Writeback || Mem.Negative)
235       return false;
236
237     // If there is an offset expression, make sure it's valid.
238     if (!Mem.Offset) return true;
239
240     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Mem.Offset);
241     if (!CE) return false;
242
243     // The offset must be a multiple of 4 in the range 0-1020.
244     int64_t Value = CE->getValue();
245     return ((Value & 0x3) == 0 && Value <= 1020 && Value >= -1020);
246   }
247   bool isMemModeRegThumb() const {
248     if (!isMemory() || (!Mem.OffsetIsReg && !Mem.Offset) || Mem.Writeback)
249       return false;
250     return !Mem.Offset || !isa<MCConstantExpr>(Mem.Offset);
251   }
252   bool isMemModeImmThumb() const {
253     if (!isMemory() || (!Mem.OffsetIsReg && !Mem.Offset) || Mem.Writeback)
254       return false;
255
256     if (!Mem.Offset) return false;
257
258     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Mem.Offset);
259     if (!CE) return false;
260
261     // The offset must be a multiple of 4 in the range 0-124.
262     uint64_t Value = CE->getValue();
263     return ((Value & 0x3) == 0 && Value <= 124);
264   }
265
266   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
267     // Add as immediates when possible.  Null MCExpr = 0.
268     if (Expr == 0)
269       Inst.addOperand(MCOperand::CreateImm(0));
270     else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
271       Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
272     else
273       Inst.addOperand(MCOperand::CreateExpr(Expr));
274   }
275
276   void addCondCodeOperands(MCInst &Inst, unsigned N) const {
277     assert(N == 2 && "Invalid number of operands!");
278     Inst.addOperand(MCOperand::CreateImm(unsigned(getCondCode())));
279     unsigned RegNum = getCondCode() == ARMCC::AL ? 0: ARM::CPSR;
280     Inst.addOperand(MCOperand::CreateReg(RegNum));
281   }
282
283   void addCCOutOperands(MCInst &Inst, unsigned N) const {
284     assert(N == 1 && "Invalid number of operands!");
285     Inst.addOperand(MCOperand::CreateReg(getReg()));
286   }
287
288   void addRegOperands(MCInst &Inst, unsigned N) const {
289     assert(N == 1 && "Invalid number of operands!");
290     Inst.addOperand(MCOperand::CreateReg(getReg()));
291   }
292
293   void addRegListOperands(MCInst &Inst, unsigned N) const {
294     assert(N == 1 && "Invalid number of operands!");
295     const SmallVectorImpl<unsigned> &RegList = getRegList();
296     for (SmallVectorImpl<unsigned>::const_iterator
297            I = RegList.begin(), E = RegList.end(); I != E; ++I)
298       Inst.addOperand(MCOperand::CreateReg(*I));
299   }
300
301   void addDPRRegListOperands(MCInst &Inst, unsigned N) const {
302     addRegListOperands(Inst, N);
303   }
304
305   void addSPRRegListOperands(MCInst &Inst, unsigned N) const {
306     addRegListOperands(Inst, N);
307   }
308
309   void addImmOperands(MCInst &Inst, unsigned N) const {
310     assert(N == 1 && "Invalid number of operands!");
311     addExpr(Inst, getImm());
312   }
313
314   void addMemMode5Operands(MCInst &Inst, unsigned N) const {
315     assert(N == 2 && isMemMode5() && "Invalid number of operands!");
316
317     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
318     assert(!Mem.OffsetIsReg && "Invalid mode 5 operand");
319
320     // FIXME: #-0 is encoded differently than #0. Does the parser preserve
321     // the difference?
322     if (Mem.Offset) {
323       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Mem.Offset);
324       assert(CE && "Non-constant mode 5 offset operand!");
325
326       // The MCInst offset operand doesn't include the low two bits (like
327       // the instruction encoding).
328       int64_t Offset = CE->getValue() / 4;
329       if (Offset >= 0)
330         Inst.addOperand(MCOperand::CreateImm(ARM_AM::getAM5Opc(ARM_AM::add,
331                                                                Offset)));
332       else
333         Inst.addOperand(MCOperand::CreateImm(ARM_AM::getAM5Opc(ARM_AM::sub,
334                                                                -Offset)));
335     } else {
336       Inst.addOperand(MCOperand::CreateImm(0));
337     }
338   }
339
340   void addMemModeRegThumbOperands(MCInst &Inst, unsigned N) const {
341     assert(N == 2 && isMemModeRegThumb() && "Invalid number of operands!");
342     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
343     Inst.addOperand(MCOperand::CreateReg(Mem.OffsetRegNum));
344   }
345
346   void addMemModeImmThumbOperands(MCInst &Inst, unsigned N) const {
347     assert(N == 2 && isMemModeImmThumb() && "Invalid number of operands!");
348     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
349     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Mem.Offset);
350     assert(CE && "Non-constant mode offset operand!");
351     Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
352   }
353
354   virtual void dump(raw_ostream &OS) const;
355
356   static ARMOperand *CreateCondCode(ARMCC::CondCodes CC, SMLoc S) {
357     ARMOperand *Op = new ARMOperand(CondCode);
358     Op->CC.Val = CC;
359     Op->StartLoc = S;
360     Op->EndLoc = S;
361     return Op;
362   }
363
364   static ARMOperand *CreateCCOut(unsigned RegNum, SMLoc S) {
365     ARMOperand *Op = new ARMOperand(CCOut);
366     Op->Reg.RegNum = RegNum;
367     Op->StartLoc = S;
368     Op->EndLoc = S;
369     return Op;
370   }
371
372   static ARMOperand *CreateToken(StringRef Str, SMLoc S) {
373     ARMOperand *Op = new ARMOperand(Token);
374     Op->Tok.Data = Str.data();
375     Op->Tok.Length = Str.size();
376     Op->StartLoc = S;
377     Op->EndLoc = S;
378     return Op;
379   }
380
381   static ARMOperand *CreateReg(unsigned RegNum, SMLoc S, SMLoc E) {
382     ARMOperand *Op = new ARMOperand(Register);
383     Op->Reg.RegNum = RegNum;
384     Op->StartLoc = S;
385     Op->EndLoc = E;
386     return Op;
387   }
388
389   static ARMOperand *
390   CreateRegList(const SmallVectorImpl<std::pair<unsigned, SMLoc> > &Regs,
391                 SMLoc StartLoc, SMLoc EndLoc) {
392     KindTy Kind = RegisterList;
393
394     if (ARM::DPRRegClass.contains(Regs.front().first))
395       Kind = DPRRegisterList;
396     else if (ARM::SPRRegClass.contains(Regs.front().first))
397       Kind = SPRRegisterList;
398
399     ARMOperand *Op = new ARMOperand(Kind);
400     for (SmallVectorImpl<std::pair<unsigned, SMLoc> >::const_iterator
401            I = Regs.begin(), E = Regs.end(); I != E; ++I)
402       Op->Registers.push_back(I->first);
403     array_pod_sort(Op->Registers.begin(), Op->Registers.end());
404     Op->StartLoc = StartLoc;
405     Op->EndLoc = EndLoc;
406     return Op;
407   }
408
409   static ARMOperand *CreateImm(const MCExpr *Val, SMLoc S, SMLoc E) {
410     ARMOperand *Op = new ARMOperand(Immediate);
411     Op->Imm.Val = Val;
412     Op->StartLoc = S;
413     Op->EndLoc = E;
414     return Op;
415   }
416
417   static ARMOperand *CreateMem(unsigned BaseRegNum, bool OffsetIsReg,
418                                const MCExpr *Offset, int OffsetRegNum,
419                                bool OffsetRegShifted, enum ShiftType ShiftType,
420                                const MCExpr *ShiftAmount, bool Preindexed,
421                                bool Postindexed, bool Negative, bool Writeback,
422                                SMLoc S, SMLoc E) {
423     assert((OffsetRegNum == -1 || OffsetIsReg) &&
424            "OffsetRegNum must imply OffsetIsReg!");
425     assert((!OffsetRegShifted || OffsetIsReg) &&
426            "OffsetRegShifted must imply OffsetIsReg!");
427     assert((!ShiftAmount || (OffsetIsReg && OffsetRegShifted)) &&
428            "Cannot have shift amount without shifted register offset!");
429     assert((!Offset || !OffsetIsReg) &&
430            "Cannot have expression offset and register offset!");
431
432     ARMOperand *Op = new ARMOperand(Memory);
433     Op->Mem.BaseRegNum = BaseRegNum;
434     Op->Mem.OffsetIsReg = OffsetIsReg;
435     Op->Mem.Offset = Offset;
436     Op->Mem.OffsetRegNum = OffsetRegNum;
437     Op->Mem.OffsetRegShifted = OffsetRegShifted;
438     Op->Mem.ShiftType = ShiftType;
439     Op->Mem.ShiftAmount = ShiftAmount;
440     Op->Mem.Preindexed = Preindexed;
441     Op->Mem.Postindexed = Postindexed;
442     Op->Mem.Negative = Negative;
443     Op->Mem.Writeback = Writeback;
444
445     Op->StartLoc = S;
446     Op->EndLoc = E;
447     return Op;
448   }
449 };
450
451 } // end anonymous namespace.
452
453 void ARMOperand::dump(raw_ostream &OS) const {
454   switch (Kind) {
455   case CondCode:
456     OS << "<ARMCC::" << ARMCondCodeToString(getCondCode()) << ">";
457     break;
458   case CCOut:
459     OS << "<ccout " << getReg() << ">";
460     break;
461   case Immediate:
462     getImm()->print(OS);
463     break;
464   case Memory:
465     OS << "<memory>";
466     break;
467   case Register:
468     OS << "<register " << getReg() << ">";
469     break;
470   case RegisterList:
471   case DPRRegisterList:
472   case SPRRegisterList: {
473     OS << "<register_list ";
474
475     const SmallVectorImpl<unsigned> &RegList = getRegList();
476     for (SmallVectorImpl<unsigned>::const_iterator
477            I = RegList.begin(), E = RegList.end(); I != E; ) {
478       OS << *I;
479       if (++I < E) OS << ", ";
480     }
481
482     OS << ">";
483     break;
484   }
485   case Token:
486     OS << "'" << getToken() << "'";
487     break;
488   }
489 }
490
491 /// @name Auto-generated Match Functions
492 /// {
493
494 static unsigned MatchRegisterName(StringRef Name);
495
496 /// }
497
498 /// Try to parse a register name.  The token must be an Identifier when called,
499 /// and if it is a register name the token is eaten and the register number is
500 /// returned.  Otherwise return -1.
501 ///
502 int ARMAsmParser::TryParseRegister() {
503   const AsmToken &Tok = Parser.getTok();
504   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
505
506   // FIXME: Validate register for the current architecture; we have to do
507   // validation later, so maybe there is no need for this here.
508   std::string upperCase = Tok.getString().str();
509   std::string lowerCase = LowercaseString(upperCase);
510   unsigned RegNum = MatchRegisterName(lowerCase);
511   if (!RegNum) {
512     RegNum = StringSwitch<unsigned>(lowerCase)
513       .Case("r13", ARM::SP)
514       .Case("r14", ARM::LR)
515       .Case("r15", ARM::PC)
516       .Case("ip", ARM::R12)
517       .Default(0);
518   }
519   if (!RegNum) return -1;
520   
521   Parser.Lex(); // Eat identifier token.
522   return RegNum;
523 }
524
525
526 /// Try to parse a register name.  The token must be an Identifier when called.
527 /// If it's a register, an AsmOperand is created. Another AsmOperand is created
528 /// if there is a "writeback". 'true' if it's not a register.
529 ///
530 /// TODO this is likely to change to allow different register types and or to
531 /// parse for a specific register type.
532 bool ARMAsmParser::
533 TryParseRegisterWithWriteBack(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
534   SMLoc S = Parser.getTok().getLoc();
535   int RegNo = TryParseRegister();
536   if (RegNo == -1)
537     return true;
538
539   Operands.push_back(ARMOperand::CreateReg(RegNo, S, Parser.getTok().getLoc()));
540
541   const AsmToken &ExclaimTok = Parser.getTok();
542   if (ExclaimTok.is(AsmToken::Exclaim)) {
543     Operands.push_back(ARMOperand::CreateToken(ExclaimTok.getString(),
544                                                ExclaimTok.getLoc()));
545     Parser.Lex(); // Eat exclaim token
546   }
547
548   return false;
549 }
550
551 static int MatchMCRName(StringRef Name) {
552   // Use the same layout as the tablegen'erated register name matcher. Ugly,
553   // but efficient.
554   switch (Name.size()) {
555   default: break;
556   case 2:
557     if (Name[0] != 'p' && Name[0] != 'c')
558       return -1;
559     switch (Name[1]) {
560     default:  return -1;
561     case '0': return 0;
562     case '1': return 1;
563     case '2': return 2;
564     case '3': return 3;
565     case '4': return 4;
566     case '5': return 5;
567     case '6': return 6;
568     case '7': return 7;
569     case '8': return 8;
570     case '9': return 9;
571     }
572     break;
573   case 3:
574     if ((Name[0] != 'p' && Name[0] != 'c') || Name[1] != '1')
575       return -1;
576     switch (Name[2]) {
577     default:  return -1;
578     case '0': return 10;
579     case '1': return 11;
580     case '2': return 12;
581     case '3': return 13;
582     case '4': return 14;
583     case '5': return 15;
584     }
585     break;
586   }
587
588   llvm_unreachable("Unhandled coprocessor operand string!");
589   return -1;
590 }
591
592 /// TryParseMCRName - Try to parse an MCR/MRC symbolic operand
593 /// name.  The token must be an Identifier when called, and if it is a MCR 
594 /// operand name, the token is eaten and the operand is added to the
595 /// operand list.
596 bool ARMAsmParser::
597 TryParseMCRName(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
598   SMLoc S = Parser.getTok().getLoc();
599   const AsmToken &Tok = Parser.getTok();
600   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
601
602   int Num = MatchMCRName(Tok.getString());
603   if (Num == -1)
604     return true;
605
606   Parser.Lex(); // Eat identifier token.
607   Operands.push_back(ARMOperand::CreateImm(
608        MCConstantExpr::Create(Num, getContext()), S, Parser.getTok().getLoc()));
609   return false;
610 }
611
612 /// Parse a register list, return it if successful else return null.  The first
613 /// token must be a '{' when called.
614 bool ARMAsmParser::
615 ParseRegisterList(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
616   assert(Parser.getTok().is(AsmToken::LCurly) &&
617          "Token is not a Left Curly Brace");
618   SMLoc S = Parser.getTok().getLoc();
619
620   // Read the rest of the registers in the list.
621   unsigned PrevRegNum = 0;
622   SmallVector<std::pair<unsigned, SMLoc>, 32> Registers;
623
624   do {
625     bool IsRange = Parser.getTok().is(AsmToken::Minus);
626     Parser.Lex(); // Eat non-identifier token.
627
628     const AsmToken &RegTok = Parser.getTok();
629     SMLoc RegLoc = RegTok.getLoc();
630     if (RegTok.isNot(AsmToken::Identifier)) {
631       Error(RegLoc, "register expected");
632       return true;
633     }
634
635     int RegNum = TryParseRegister();
636     if (RegNum == -1) {
637       Error(RegLoc, "register expected");
638       return true;
639     }
640
641     if (IsRange) {
642       int Reg = PrevRegNum;
643       do {
644         ++Reg;
645         Registers.push_back(std::make_pair(Reg, RegLoc));
646       } while (Reg != RegNum);
647     } else {
648       Registers.push_back(std::make_pair(RegNum, RegLoc));
649     }
650
651     PrevRegNum = RegNum;
652   } while (Parser.getTok().is(AsmToken::Comma) ||
653            Parser.getTok().is(AsmToken::Minus));
654
655   // Process the right curly brace of the list.
656   const AsmToken &RCurlyTok = Parser.getTok();
657   if (RCurlyTok.isNot(AsmToken::RCurly)) {
658     Error(RCurlyTok.getLoc(), "'}' expected");
659     return true;
660   }
661
662   SMLoc E = RCurlyTok.getLoc();
663   Parser.Lex(); // Eat right curly brace token.
664
665   // Verify the register list.
666   SmallVectorImpl<std::pair<unsigned, SMLoc> >::const_iterator
667     RI = Registers.begin(), RE = Registers.end();
668
669   unsigned HighRegNum = getARMRegisterNumbering(RI->first);
670   bool EmittedWarning = false;
671
672   DenseMap<unsigned, bool> RegMap;
673   RegMap[HighRegNum] = true;
674
675   for (++RI; RI != RE; ++RI) {
676     const std::pair<unsigned, SMLoc> &RegInfo = *RI;
677     unsigned Reg = getARMRegisterNumbering(RegInfo.first);
678
679     if (RegMap[Reg]) {
680       Error(RegInfo.second, "register duplicated in register list");
681       return true;
682     }
683
684     if (!EmittedWarning && Reg < HighRegNum)
685       Warning(RegInfo.second,
686               "register not in ascending order in register list");
687
688     RegMap[Reg] = true;
689     HighRegNum = std::max(Reg, HighRegNum);
690   }
691
692   Operands.push_back(ARMOperand::CreateRegList(Registers, S, E));
693   return false;
694 }
695
696 /// Parse an ARM memory expression, return false if successful else return true
697 /// or an error.  The first token must be a '[' when called.
698 ///
699 /// TODO Only preindexing and postindexing addressing are started, unindexed
700 /// with option, etc are still to do.
701 bool ARMAsmParser::
702 ParseMemory(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
703   SMLoc S, E;
704   assert(Parser.getTok().is(AsmToken::LBrac) &&
705          "Token is not a Left Bracket");
706   S = Parser.getTok().getLoc();
707   Parser.Lex(); // Eat left bracket token.
708
709   const AsmToken &BaseRegTok = Parser.getTok();
710   if (BaseRegTok.isNot(AsmToken::Identifier)) {
711     Error(BaseRegTok.getLoc(), "register expected");
712     return true;
713   }
714   int BaseRegNum = TryParseRegister();
715   if (BaseRegNum == -1) {
716     Error(BaseRegTok.getLoc(), "register expected");
717     return true;
718   }
719
720   bool Preindexed = false;
721   bool Postindexed = false;
722   bool OffsetIsReg = false;
723   bool Negative = false;
724   bool Writeback = false;
725
726   // First look for preindexed address forms, that is after the "[Rn" we now
727   // have to see if the next token is a comma.
728   const AsmToken &Tok = Parser.getTok();
729   if (Tok.is(AsmToken::Comma)) {
730     Preindexed = true;
731     Parser.Lex(); // Eat comma token.
732     int OffsetRegNum;
733     bool OffsetRegShifted;
734     enum ShiftType ShiftType;
735     const MCExpr *ShiftAmount = 0;
736     const MCExpr *Offset = 0;
737     if (ParseMemoryOffsetReg(Negative, OffsetRegShifted, ShiftType, ShiftAmount,
738                              Offset, OffsetIsReg, OffsetRegNum, E))
739       return true;
740     const AsmToken &RBracTok = Parser.getTok();
741     if (RBracTok.isNot(AsmToken::RBrac)) {
742       Error(RBracTok.getLoc(), "']' expected");
743       return true;
744     }
745     E = RBracTok.getLoc();
746     Parser.Lex(); // Eat right bracket token.
747
748
749     const AsmToken &ExclaimTok = Parser.getTok();
750     ARMOperand *WBOp = 0;
751     if (ExclaimTok.is(AsmToken::Exclaim)) {
752       WBOp = ARMOperand::CreateToken(ExclaimTok.getString(),
753                                      ExclaimTok.getLoc());
754       Writeback = true;
755       Parser.Lex(); // Eat exclaim token
756     }
757
758     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, OffsetIsReg, Offset,
759                                              OffsetRegNum, OffsetRegShifted,
760                                              ShiftType, ShiftAmount, Preindexed,
761                                              Postindexed, Negative, Writeback,
762                                              S, E));
763     if (WBOp)
764       Operands.push_back(WBOp);
765
766     return false;
767   }
768   // The "[Rn" we have so far was not followed by a comma.
769   else if (Tok.is(AsmToken::RBrac)) {
770     // If there's anything other than the right brace, this is a post indexing
771     // addressing form.
772     E = Tok.getLoc();
773     Parser.Lex(); // Eat right bracket token.
774
775     int OffsetRegNum = -1;
776     bool OffsetRegShifted = false;
777     enum ShiftType ShiftType = Lsl;
778     const MCExpr *ShiftAmount = 0;
779     const MCExpr *Offset = 0;
780
781     const AsmToken &NextTok = Parser.getTok();
782
783     if (NextTok.isNot(AsmToken::EndOfStatement)) {
784       Postindexed = true;
785       Writeback = true;
786
787       if (NextTok.isNot(AsmToken::Comma)) {
788         Error(NextTok.getLoc(), "',' expected");
789         return true;
790       }
791
792       Parser.Lex(); // Eat comma token.
793
794       if (ParseMemoryOffsetReg(Negative, OffsetRegShifted, ShiftType,
795                                ShiftAmount, Offset, OffsetIsReg, OffsetRegNum,
796                                E))
797         return true;
798     }
799
800     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, OffsetIsReg, Offset,
801                                              OffsetRegNum, OffsetRegShifted,
802                                              ShiftType, ShiftAmount, Preindexed,
803                                              Postindexed, Negative, Writeback,
804                                              S, E));
805     return false;
806   }
807
808   return true;
809 }
810
811 /// Parse the offset of a memory operand after we have seen "[Rn," or "[Rn],"
812 /// we will parse the following (were +/- means that a plus or minus is
813 /// optional):
814 ///   +/-Rm
815 ///   +/-Rm, shift
816 ///   #offset
817 /// we return false on success or an error otherwise.
818 bool ARMAsmParser::ParseMemoryOffsetReg(bool &Negative,
819                                         bool &OffsetRegShifted,
820                                         enum ShiftType &ShiftType,
821                                         const MCExpr *&ShiftAmount,
822                                         const MCExpr *&Offset,
823                                         bool &OffsetIsReg,
824                                         int &OffsetRegNum,
825                                         SMLoc &E) {
826   Negative = false;
827   OffsetRegShifted = false;
828   OffsetIsReg = false;
829   OffsetRegNum = -1;
830   const AsmToken &NextTok = Parser.getTok();
831   E = NextTok.getLoc();
832   if (NextTok.is(AsmToken::Plus))
833     Parser.Lex(); // Eat plus token.
834   else if (NextTok.is(AsmToken::Minus)) {
835     Negative = true;
836     Parser.Lex(); // Eat minus token
837   }
838   // See if there is a register following the "[Rn," or "[Rn]," we have so far.
839   const AsmToken &OffsetRegTok = Parser.getTok();
840   if (OffsetRegTok.is(AsmToken::Identifier)) {
841     SMLoc CurLoc = OffsetRegTok.getLoc();
842     OffsetRegNum = TryParseRegister();
843     if (OffsetRegNum != -1) {
844       OffsetIsReg = true;
845       E = CurLoc;
846     }
847   }
848
849   // If we parsed a register as the offset then there can be a shift after that.
850   if (OffsetRegNum != -1) {
851     // Look for a comma then a shift
852     const AsmToken &Tok = Parser.getTok();
853     if (Tok.is(AsmToken::Comma)) {
854       Parser.Lex(); // Eat comma token.
855
856       const AsmToken &Tok = Parser.getTok();
857       if (ParseShift(ShiftType, ShiftAmount, E))
858         return Error(Tok.getLoc(), "shift expected");
859       OffsetRegShifted = true;
860     }
861   }
862   else { // the "[Rn," or "[Rn,]" we have so far was not followed by "Rm"
863     // Look for #offset following the "[Rn," or "[Rn],"
864     const AsmToken &HashTok = Parser.getTok();
865     if (HashTok.isNot(AsmToken::Hash))
866       return Error(HashTok.getLoc(), "'#' expected");
867
868     Parser.Lex(); // Eat hash token.
869
870     if (getParser().ParseExpression(Offset))
871      return true;
872     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
873   }
874   return false;
875 }
876
877 /// ParseShift as one of these two:
878 ///   ( lsl | lsr | asr | ror ) , # shift_amount
879 ///   rrx
880 /// and returns true if it parses a shift otherwise it returns false.
881 bool ARMAsmParser::ParseShift(ShiftType &St, const MCExpr *&ShiftAmount,
882                               SMLoc &E) {
883   const AsmToken &Tok = Parser.getTok();
884   if (Tok.isNot(AsmToken::Identifier))
885     return true;
886   StringRef ShiftName = Tok.getString();
887   if (ShiftName == "lsl" || ShiftName == "LSL")
888     St = Lsl;
889   else if (ShiftName == "lsr" || ShiftName == "LSR")
890     St = Lsr;
891   else if (ShiftName == "asr" || ShiftName == "ASR")
892     St = Asr;
893   else if (ShiftName == "ror" || ShiftName == "ROR")
894     St = Ror;
895   else if (ShiftName == "rrx" || ShiftName == "RRX")
896     St = Rrx;
897   else
898     return true;
899   Parser.Lex(); // Eat shift type token.
900
901   // Rrx stands alone.
902   if (St == Rrx)
903     return false;
904
905   // Otherwise, there must be a '#' and a shift amount.
906   const AsmToken &HashTok = Parser.getTok();
907   if (HashTok.isNot(AsmToken::Hash))
908     return Error(HashTok.getLoc(), "'#' expected");
909   Parser.Lex(); // Eat hash token.
910
911   if (getParser().ParseExpression(ShiftAmount))
912     return true;
913
914   return false;
915 }
916
917 /// Parse a arm instruction operand.  For now this parses the operand regardless
918 /// of the mnemonic.
919 bool ARMAsmParser::ParseOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands,
920                                 bool isMCR){
921   SMLoc S, E;
922   switch (getLexer().getKind()) {
923   default:
924     Error(Parser.getTok().getLoc(), "unexpected token in operand");
925     return true;
926   case AsmToken::Identifier:
927     if (!TryParseRegisterWithWriteBack(Operands))
928       return false;
929     if (isMCR && !TryParseMCRName(Operands))
930       return false;
931
932     // Fall though for the Identifier case that is not a register or a
933     // special name.
934   case AsmToken::Integer: // things like 1f and 2b as a branch targets
935   case AsmToken::Dot: {   // . as a branch target
936     // This was not a register so parse other operands that start with an
937     // identifier (like labels) as expressions and create them as immediates.
938     const MCExpr *IdVal;
939     S = Parser.getTok().getLoc();
940     if (getParser().ParseExpression(IdVal))
941       return true;
942     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
943     Operands.push_back(ARMOperand::CreateImm(IdVal, S, E));
944     return false;
945   }
946   case AsmToken::LBrac:
947     return ParseMemory(Operands);
948   case AsmToken::LCurly:
949     return ParseRegisterList(Operands);
950   case AsmToken::Hash:
951     // #42 -> immediate.
952     // TODO: ":lower16:" and ":upper16:" modifiers after # before immediate
953     S = Parser.getTok().getLoc();
954     Parser.Lex();
955     const MCExpr *ImmVal;
956     if (getParser().ParseExpression(ImmVal))
957       return true;
958     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
959     Operands.push_back(ARMOperand::CreateImm(ImmVal, S, E));
960     return false;
961   case AsmToken::Colon: {
962     // ":lower16:" and ":upper16:" expression prefixes
963     // FIXME: Check it's an expression prefix,
964     // e.g. (FOO - :lower16:BAR) isn't legal.
965     ARMMCExpr::VariantKind RefKind;
966     if (ParsePrefix(RefKind))
967       return true;
968
969     const MCExpr *SubExprVal;
970     if (getParser().ParseExpression(SubExprVal))
971       return true;
972
973     const MCExpr *ExprVal = ARMMCExpr::Create(RefKind, SubExprVal,
974                                                    getContext());
975     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
976     Operands.push_back(ARMOperand::CreateImm(ExprVal, S, E));
977     return false;
978   }
979   }
980 }
981
982 // ParsePrefix - Parse ARM 16-bit relocations expression prefix, i.e.
983 //  :lower16: and :upper16:.
984 bool ARMAsmParser::ParsePrefix(ARMMCExpr::VariantKind &RefKind) {
985   RefKind = ARMMCExpr::VK_ARM_None;
986
987   // :lower16: and :upper16: modifiers
988   assert(getLexer().is(AsmToken::Colon) && "expected a :");
989   Parser.Lex(); // Eat ':'
990
991   if (getLexer().isNot(AsmToken::Identifier)) {
992     Error(Parser.getTok().getLoc(), "expected prefix identifier in operand");
993     return true;
994   }
995
996   StringRef IDVal = Parser.getTok().getIdentifier();
997   if (IDVal == "lower16") {
998     RefKind = ARMMCExpr::VK_ARM_LO16;
999   } else if (IDVal == "upper16") {
1000     RefKind = ARMMCExpr::VK_ARM_HI16;
1001   } else {
1002     Error(Parser.getTok().getLoc(), "unexpected prefix in operand");
1003     return true;
1004   }
1005   Parser.Lex();
1006
1007   if (getLexer().isNot(AsmToken::Colon)) {
1008     Error(Parser.getTok().getLoc(), "unexpected token after prefix");
1009     return true;
1010   }
1011   Parser.Lex(); // Eat the last ':'
1012   return false;
1013 }
1014
1015 const MCExpr *
1016 ARMAsmParser::ApplyPrefixToExpr(const MCExpr *E,
1017                                 MCSymbolRefExpr::VariantKind Variant) {
1018   // Recurse over the given expression, rebuilding it to apply the given variant
1019   // to the leftmost symbol.
1020   if (Variant == MCSymbolRefExpr::VK_None)
1021     return E;
1022
1023   switch (E->getKind()) {
1024   case MCExpr::Target:
1025     llvm_unreachable("Can't handle target expr yet");
1026   case MCExpr::Constant:
1027     llvm_unreachable("Can't handle lower16/upper16 of constant yet");
1028
1029   case MCExpr::SymbolRef: {
1030     const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
1031
1032     if (SRE->getKind() != MCSymbolRefExpr::VK_None)
1033       return 0;
1034
1035     return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
1036   }
1037
1038   case MCExpr::Unary:
1039     llvm_unreachable("Can't handle unary expressions yet");
1040
1041   case MCExpr::Binary: {
1042     const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
1043     const MCExpr *LHS = ApplyPrefixToExpr(BE->getLHS(), Variant);
1044     const MCExpr *RHS = BE->getRHS();
1045     if (!LHS)
1046       return 0;
1047
1048     return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
1049   }
1050   }
1051
1052   assert(0 && "Invalid expression kind!");
1053   return 0;
1054 }
1055
1056 /// \brief Given a mnemonic, split out possible predication code and carry
1057 /// setting letters to form a canonical mnemonic and flags.
1058 //
1059 // FIXME: Would be nice to autogen this.
1060 static StringRef SplitMnemonicAndCC(StringRef Mnemonic,
1061                                     unsigned &PredicationCode,
1062                                     bool &CarrySetting) {
1063   PredicationCode = ARMCC::AL;
1064   CarrySetting = false;
1065
1066   // Ignore some mnemonics we know aren't predicated forms.
1067   //
1068   // FIXME: Would be nice to autogen this.
1069   if (Mnemonic == "teq" || Mnemonic == "vceq" ||
1070       Mnemonic == "movs" ||
1071       Mnemonic == "svc" ||
1072       (Mnemonic == "mls" || Mnemonic == "smmls" || Mnemonic == "vcls" ||
1073        Mnemonic == "vmls" || Mnemonic == "vnmls") ||
1074       Mnemonic == "vacge" || Mnemonic == "vcge" ||
1075       Mnemonic == "vclt" ||
1076       Mnemonic == "vacgt" || Mnemonic == "vcgt" ||
1077       Mnemonic == "vcle" ||
1078       (Mnemonic == "smlal" || Mnemonic == "umaal" || Mnemonic == "umlal" ||
1079        Mnemonic == "vabal" || Mnemonic == "vmlal" || Mnemonic == "vpadal" ||
1080        Mnemonic == "vqdmlal"))
1081     return Mnemonic;
1082
1083   // First, split out any predication code.
1084   unsigned CC = StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2))
1085     .Case("eq", ARMCC::EQ)
1086     .Case("ne", ARMCC::NE)
1087     .Case("hs", ARMCC::HS)
1088     .Case("lo", ARMCC::LO)
1089     .Case("mi", ARMCC::MI)
1090     .Case("pl", ARMCC::PL)
1091     .Case("vs", ARMCC::VS)
1092     .Case("vc", ARMCC::VC)
1093     .Case("hi", ARMCC::HI)
1094     .Case("ls", ARMCC::LS)
1095     .Case("ge", ARMCC::GE)
1096     .Case("lt", ARMCC::LT)
1097     .Case("gt", ARMCC::GT)
1098     .Case("le", ARMCC::LE)
1099     .Case("al", ARMCC::AL)
1100     .Default(~0U);
1101   if (CC != ~0U) {
1102     Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 2);
1103     PredicationCode = CC;
1104   }
1105
1106   // Next, determine if we have a carry setting bit. We explicitly ignore all
1107   // the instructions we know end in 's'.
1108   if (Mnemonic.endswith("s") &&
1109       !(Mnemonic == "asrs" || Mnemonic == "cps" || Mnemonic == "mls" ||
1110         Mnemonic == "movs" || Mnemonic == "mrs" || Mnemonic == "smmls" ||
1111         Mnemonic == "vabs" || Mnemonic == "vcls" || Mnemonic == "vmls" ||
1112         Mnemonic == "vmrs" || Mnemonic == "vnmls" || Mnemonic == "vqabs" ||
1113         Mnemonic == "vrecps" || Mnemonic == "vrsqrts")) {
1114     Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 1);
1115     CarrySetting = true;
1116   }
1117
1118   return Mnemonic;
1119 }
1120
1121 /// \brief Given a canonical mnemonic, determine if the instruction ever allows
1122 /// inclusion of carry set or predication code operands.
1123 //
1124 // FIXME: It would be nice to autogen this.
1125 static void GetMnemonicAcceptInfo(StringRef Mnemonic, bool &CanAcceptCarrySet,
1126                                   bool &CanAcceptPredicationCode) {
1127   if (Mnemonic == "and" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
1128       Mnemonic == "rrx" || Mnemonic == "ror" || Mnemonic == "sub" ||
1129       Mnemonic == "smull" || Mnemonic == "add" || Mnemonic == "adc" ||
1130       Mnemonic == "mul" || Mnemonic == "bic" || Mnemonic == "asr" ||
1131       Mnemonic == "umlal" || Mnemonic == "orr" || Mnemonic == "mov" ||
1132       Mnemonic == "rsb" || Mnemonic == "rsc" || Mnemonic == "orn" ||
1133       Mnemonic == "sbc" || Mnemonic == "mla" || Mnemonic == "umull" ||
1134       Mnemonic == "eor" || Mnemonic == "smlal" || Mnemonic == "mvn") {
1135     CanAcceptCarrySet = true;
1136   } else {
1137     CanAcceptCarrySet = false;
1138   }
1139
1140   if (Mnemonic == "cbnz" || Mnemonic == "setend" || Mnemonic == "dmb" ||
1141       Mnemonic == "cps" || Mnemonic == "mcr2" || Mnemonic == "it" ||
1142       Mnemonic == "mcrr2" || Mnemonic == "cbz" || Mnemonic == "cdp2" ||
1143       Mnemonic == "trap" || Mnemonic == "mrc2" || Mnemonic == "mrrc2" ||
1144       Mnemonic == "dsb" || Mnemonic == "movs") {
1145     CanAcceptPredicationCode = false;
1146   } else {
1147     CanAcceptPredicationCode = true;
1148   }
1149 }
1150
1151 /// Parse an arm instruction mnemonic followed by its operands.
1152 bool ARMAsmParser::ParseInstruction(StringRef Name, SMLoc NameLoc,
1153                                SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1154   // Create the leading tokens for the mnemonic, split by '.' characters.
1155   size_t Start = 0, Next = Name.find('.');
1156   StringRef Head = Name.slice(Start, Next);
1157
1158   // Split out the predication code and carry setting flag from the mnemonic.
1159   unsigned PredicationCode;
1160   bool CarrySetting;
1161   Head = SplitMnemonicAndCC(Head, PredicationCode, CarrySetting);
1162
1163   Operands.push_back(ARMOperand::CreateToken(Head, NameLoc));
1164
1165   // Next, add the CCOut and ConditionCode operands, if needed.
1166   //
1167   // For mnemonics which can ever incorporate a carry setting bit or predication
1168   // code, our matching model involves us always generating CCOut and
1169   // ConditionCode operands to match the mnemonic "as written" and then we let
1170   // the matcher deal with finding the right instruction or generating an
1171   // appropriate error.
1172   bool CanAcceptCarrySet, CanAcceptPredicationCode;
1173   GetMnemonicAcceptInfo(Head, CanAcceptCarrySet, CanAcceptPredicationCode);
1174
1175   // Add the carry setting operand, if necessary.
1176   //
1177   // FIXME: It would be awesome if we could somehow invent a location such that
1178   // match errors on this operand would print a nice diagnostic about how the
1179   // 's' character in the mnemonic resulted in a CCOut operand.
1180   if (CanAcceptCarrySet) {
1181     Operands.push_back(ARMOperand::CreateCCOut(CarrySetting ? ARM::CPSR : 0,
1182                                                NameLoc));
1183   } else {
1184     // This mnemonic can't ever accept a carry set, but the user wrote one (or
1185     // misspelled another mnemonic).
1186
1187     // FIXME: Issue a nice error.
1188   }
1189
1190   // Add the predication code operand, if necessary.
1191   if (CanAcceptPredicationCode) {
1192     Operands.push_back(ARMOperand::CreateCondCode(
1193                          ARMCC::CondCodes(PredicationCode), NameLoc));
1194   } else {
1195     // This mnemonic can't ever accept a predication code, but the user wrote
1196     // one (or misspelled another mnemonic).
1197
1198     // FIXME: Issue a nice error.
1199   }
1200
1201   // Add the remaining tokens in the mnemonic.
1202   while (Next != StringRef::npos) {
1203     Start = Next;
1204     Next = Name.find('.', Start + 1);
1205     Head = Name.slice(Start, Next);
1206
1207     Operands.push_back(ARMOperand::CreateToken(Head, NameLoc));
1208   }
1209
1210   bool isMCR = (Head == "mcr"  || Head == "mcr2" ||
1211                 Head == "mcrr" || Head == "mcrr2" ||
1212                 Head == "mrc"  || Head == "mrc2" ||
1213                 Head == "mrrc" || Head == "mrrc2");
1214
1215   // Read the remaining operands.
1216   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1217     // Read the first operand.
1218     if (ParseOperand(Operands, isMCR)) {
1219       Parser.EatToEndOfStatement();
1220       return true;
1221     }
1222
1223     while (getLexer().is(AsmToken::Comma)) {
1224       Parser.Lex();  // Eat the comma.
1225
1226       // Parse and remember the operand.
1227       if (ParseOperand(Operands, isMCR)) {
1228         Parser.EatToEndOfStatement();
1229         return true;
1230       }
1231     }
1232   }
1233
1234   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1235     Parser.EatToEndOfStatement();
1236     return TokError("unexpected token in argument list");
1237   }
1238
1239   Parser.Lex(); // Consume the EndOfStatement
1240   return false;
1241 }
1242
1243 bool ARMAsmParser::
1244 MatchAndEmitInstruction(SMLoc IDLoc,
1245                         SmallVectorImpl<MCParsedAsmOperand*> &Operands,
1246                         MCStreamer &Out) {
1247   MCInst Inst;
1248   unsigned ErrorInfo;
1249   MatchResultTy MatchResult, MatchResult2;
1250   MatchResult = MatchInstructionImpl(Operands, Inst, ErrorInfo);
1251   if (MatchResult != Match_Success) {
1252     // If we get a Match_InvalidOperand it might be some arithmetic instruction
1253     // that does not update the condition codes.  So try adding a CCOut operand
1254     // with a value of reg0.
1255     if (MatchResult == Match_InvalidOperand) {
1256       Operands.insert(Operands.begin() + 1,
1257                       ARMOperand::CreateCCOut(0,
1258                                   ((ARMOperand*)Operands[0])->getStartLoc()));
1259       MatchResult2 = MatchInstructionImpl(Operands, Inst, ErrorInfo);
1260       if (MatchResult2 == Match_Success)
1261         MatchResult = Match_Success;
1262       else {
1263         ARMOperand *CCOut = ((ARMOperand*)Operands[1]);
1264         Operands.erase(Operands.begin() + 1);
1265         delete CCOut;
1266       }
1267     }
1268     // If we get a Match_MnemonicFail it might be some arithmetic instruction
1269     // that updates the condition codes if it ends in 's'.  So see if the
1270     // mnemonic ends in 's' and if so try removing the 's' and adding a CCOut
1271     // operand with a value of CPSR.
1272     else if(MatchResult == Match_MnemonicFail) {
1273       // Get the instruction mnemonic, which is the first token.
1274       StringRef Mnemonic = ((ARMOperand*)Operands[0])->getToken();
1275       if (Mnemonic.substr(Mnemonic.size()-1) == "s") {
1276         // removed the 's' from the mnemonic for matching.
1277         StringRef MnemonicNoS = Mnemonic.slice(0, Mnemonic.size() - 1);
1278         SMLoc NameLoc = ((ARMOperand*)Operands[0])->getStartLoc();
1279         ARMOperand *OldMnemonic = ((ARMOperand*)Operands[0]);
1280         Operands.erase(Operands.begin());
1281         delete OldMnemonic;
1282         Operands.insert(Operands.begin(),
1283                         ARMOperand::CreateToken(MnemonicNoS, NameLoc));
1284         Operands.insert(Operands.begin() + 1,
1285                         ARMOperand::CreateCCOut(ARM::CPSR, NameLoc));
1286         MatchResult2 = MatchInstructionImpl(Operands, Inst, ErrorInfo);
1287         if (MatchResult2 == Match_Success)
1288           MatchResult = Match_Success;
1289         else {
1290           ARMOperand *OldMnemonic = ((ARMOperand*)Operands[0]);
1291           Operands.erase(Operands.begin());
1292           delete OldMnemonic;
1293           Operands.insert(Operands.begin(),
1294                           ARMOperand::CreateToken(Mnemonic, NameLoc));
1295           ARMOperand *CCOut = ((ARMOperand*)Operands[1]);
1296           Operands.erase(Operands.begin() + 1);
1297           delete CCOut;
1298         }
1299       }
1300     }
1301   }
1302   switch (MatchResult) {
1303   case Match_Success:
1304     Out.EmitInstruction(Inst);
1305     return false;
1306   case Match_MissingFeature:
1307     Error(IDLoc, "instruction requires a CPU feature not currently enabled");
1308     return true;
1309   case Match_InvalidOperand: {
1310     SMLoc ErrorLoc = IDLoc;
1311     if (ErrorInfo != ~0U) {
1312       if (ErrorInfo >= Operands.size())
1313         return Error(IDLoc, "too few operands for instruction");
1314
1315       ErrorLoc = ((ARMOperand*)Operands[ErrorInfo])->getStartLoc();
1316       if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
1317     }
1318
1319     return Error(ErrorLoc, "invalid operand for instruction");
1320   }
1321   case Match_MnemonicFail:
1322     return Error(IDLoc, "unrecognized instruction mnemonic");
1323   }
1324
1325   llvm_unreachable("Implement any new match types added!");
1326   return true;
1327 }
1328
1329 /// ParseDirective parses the arm specific directives
1330 bool ARMAsmParser::ParseDirective(AsmToken DirectiveID) {
1331   StringRef IDVal = DirectiveID.getIdentifier();
1332   if (IDVal == ".word")
1333     return ParseDirectiveWord(4, DirectiveID.getLoc());
1334   else if (IDVal == ".thumb")
1335     return ParseDirectiveThumb(DirectiveID.getLoc());
1336   else if (IDVal == ".thumb_func")
1337     return ParseDirectiveThumbFunc(DirectiveID.getLoc());
1338   else if (IDVal == ".code")
1339     return ParseDirectiveCode(DirectiveID.getLoc());
1340   else if (IDVal == ".syntax")
1341     return ParseDirectiveSyntax(DirectiveID.getLoc());
1342   return true;
1343 }
1344
1345 /// ParseDirectiveWord
1346 ///  ::= .word [ expression (, expression)* ]
1347 bool ARMAsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
1348   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1349     for (;;) {
1350       const MCExpr *Value;
1351       if (getParser().ParseExpression(Value))
1352         return true;
1353
1354       getParser().getStreamer().EmitValue(Value, Size, 0/*addrspace*/);
1355
1356       if (getLexer().is(AsmToken::EndOfStatement))
1357         break;
1358
1359       // FIXME: Improve diagnostic.
1360       if (getLexer().isNot(AsmToken::Comma))
1361         return Error(L, "unexpected token in directive");
1362       Parser.Lex();
1363     }
1364   }
1365
1366   Parser.Lex();
1367   return false;
1368 }
1369
1370 /// ParseDirectiveThumb
1371 ///  ::= .thumb
1372 bool ARMAsmParser::ParseDirectiveThumb(SMLoc L) {
1373   if (getLexer().isNot(AsmToken::EndOfStatement))
1374     return Error(L, "unexpected token in directive");
1375   Parser.Lex();
1376
1377   // TODO: set thumb mode
1378   // TODO: tell the MC streamer the mode
1379   // getParser().getStreamer().Emit???();
1380   return false;
1381 }
1382
1383 /// ParseDirectiveThumbFunc
1384 ///  ::= .thumbfunc symbol_name
1385 bool ARMAsmParser::ParseDirectiveThumbFunc(SMLoc L) {
1386   const AsmToken &Tok = Parser.getTok();
1387   if (Tok.isNot(AsmToken::Identifier) && Tok.isNot(AsmToken::String))
1388     return Error(L, "unexpected token in .thumb_func directive");
1389   StringRef Name = Tok.getString();
1390   Parser.Lex(); // Consume the identifier token.
1391   if (getLexer().isNot(AsmToken::EndOfStatement))
1392     return Error(L, "unexpected token in directive");
1393   Parser.Lex();
1394
1395   // Mark symbol as a thumb symbol.
1396   MCSymbol *Func = getParser().getContext().GetOrCreateSymbol(Name);
1397   getParser().getStreamer().EmitThumbFunc(Func);
1398   return false;
1399 }
1400
1401 /// ParseDirectiveSyntax
1402 ///  ::= .syntax unified | divided
1403 bool ARMAsmParser::ParseDirectiveSyntax(SMLoc L) {
1404   const AsmToken &Tok = Parser.getTok();
1405   if (Tok.isNot(AsmToken::Identifier))
1406     return Error(L, "unexpected token in .syntax directive");
1407   StringRef Mode = Tok.getString();
1408   if (Mode == "unified" || Mode == "UNIFIED")
1409     Parser.Lex();
1410   else if (Mode == "divided" || Mode == "DIVIDED")
1411     Parser.Lex();
1412   else
1413     return Error(L, "unrecognized syntax mode in .syntax directive");
1414
1415   if (getLexer().isNot(AsmToken::EndOfStatement))
1416     return Error(Parser.getTok().getLoc(), "unexpected token in directive");
1417   Parser.Lex();
1418
1419   // TODO tell the MC streamer the mode
1420   // getParser().getStreamer().Emit???();
1421   return false;
1422 }
1423
1424 /// ParseDirectiveCode
1425 ///  ::= .code 16 | 32
1426 bool ARMAsmParser::ParseDirectiveCode(SMLoc L) {
1427   const AsmToken &Tok = Parser.getTok();
1428   if (Tok.isNot(AsmToken::Integer))
1429     return Error(L, "unexpected token in .code directive");
1430   int64_t Val = Parser.getTok().getIntVal();
1431   if (Val == 16)
1432     Parser.Lex();
1433   else if (Val == 32)
1434     Parser.Lex();
1435   else
1436     return Error(L, "invalid operand to .code directive");
1437
1438   if (getLexer().isNot(AsmToken::EndOfStatement))
1439     return Error(Parser.getTok().getLoc(), "unexpected token in directive");
1440   Parser.Lex();
1441
1442   // FIXME: We need to be able switch subtargets at this point so that
1443   // MatchInstructionImpl() will work when it gets the AvailableFeatures which
1444   // includes Feature_IsThumb or not to match the right instructions.  This is
1445   // blocked on the FIXME in llvm-mc.cpp when creating the TargetMachine.
1446   if (Val == 16){
1447     assert(TM.getSubtarget<ARMSubtarget>().isThumb() &&
1448            "switching between arm/thumb not yet suppported via .code 16)");
1449     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
1450   }
1451   else{
1452     assert(!TM.getSubtarget<ARMSubtarget>().isThumb() &&
1453            "switching between thumb/arm not yet suppported via .code 32)");
1454     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
1455    }
1456
1457   return false;
1458 }
1459
1460 extern "C" void LLVMInitializeARMAsmLexer();
1461
1462 /// Force static initialization.
1463 extern "C" void LLVMInitializeARMAsmParser() {
1464   RegisterAsmParser<ARMAsmParser> X(TheARMTarget);
1465   RegisterAsmParser<ARMAsmParser> Y(TheThumbTarget);
1466   LLVMInitializeARMAsmLexer();
1467 }
1468
1469 #define GET_REGISTER_MATCHER
1470 #define GET_MATCHER_IMPLEMENTATION
1471 #include "ARMGenAsmMatcher.inc"