Rename a parameter to avoid confusion with a local variable
[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 "ARMSubtarget.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/MCContext.h"
17 #include "llvm/MC/MCStreamer.h"
18 #include "llvm/MC/MCExpr.h"
19 #include "llvm/MC/MCInst.h"
20 #include "llvm/Target/TargetRegistry.h"
21 #include "llvm/Target/TargetAsmParser.h"
22 #include "llvm/Support/SourceMgr.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/StringSwitch.h"
26 #include "llvm/ADT/Twine.h"
27 using namespace llvm;
28
29 // The shift types for register controlled shifts in arm memory addressing
30 enum ShiftType {
31   Lsl,
32   Lsr,
33   Asr,
34   Ror,
35   Rrx
36 };
37
38 namespace {
39
40 class ARMOperand;
41
42 class ARMAsmParser : public TargetAsmParser {
43   MCAsmParser &Parser;
44   TargetMachine &TM;
45
46   MCAsmParser &getParser() const { return Parser; }
47   MCAsmLexer &getLexer() const { return Parser.getLexer(); }
48
49   void Warning(SMLoc L, const Twine &Msg) { Parser.Warning(L, Msg); }
50   bool Error(SMLoc L, const Twine &Msg) { return Parser.Error(L, Msg); }
51
52   int TryParseRegister();
53   ARMOperand *TryParseRegisterWithWriteBack();
54   ARMOperand *ParseRegisterList();
55   ARMOperand *ParseMemory();
56   ARMOperand *ParseOperand();
57
58   bool ParseMemoryOffsetReg(bool &Negative,
59                             bool &OffsetRegShifted,
60                             enum ShiftType &ShiftType,
61                             const MCExpr *&ShiftAmount,
62                             const MCExpr *&Offset,
63                             bool &OffsetIsReg,
64                             int &OffsetRegNum,
65                             SMLoc &E);
66   bool ParseShift(enum ShiftType &St, const MCExpr *&ShiftAmount, SMLoc &E);
67   bool ParseDirectiveWord(unsigned Size, SMLoc L);
68   bool ParseDirectiveThumb(SMLoc L);
69   bool ParseDirectiveThumbFunc(SMLoc L);
70   bool ParseDirectiveCode(SMLoc L);
71   bool ParseDirectiveSyntax(SMLoc L);
72
73   bool MatchAndEmitInstruction(SMLoc IDLoc,
74                                SmallVectorImpl<MCParsedAsmOperand*> &Operands,
75                                MCStreamer &Out);
76
77   /// @name Auto-generated Match Functions
78   /// {
79
80 #define GET_ASSEMBLER_HEADER
81 #include "ARMGenAsmMatcher.inc"
82
83   /// }
84
85 public:
86   ARMAsmParser(const Target &T, MCAsmParser &_Parser, TargetMachine &_TM)
87     : TargetAsmParser(T), Parser(_Parser), TM(_TM) {
88       // Initialize the set of available features.
89       setAvailableFeatures(ComputeAvailableFeatures(
90           &TM.getSubtarget<ARMSubtarget>()));
91     }
92
93   virtual bool ParseInstruction(StringRef Name, SMLoc NameLoc,
94                                 SmallVectorImpl<MCParsedAsmOperand*> &Operands);
95   virtual bool ParseDirective(AsmToken DirectiveID);
96 };
97 } // end anonymous namespace
98
99 namespace {
100
101 /// ARMOperand - Instances of this class represent a parsed ARM machine
102 /// instruction.
103 class ARMOperand : public MCParsedAsmOperand {
104   enum KindTy {
105     CondCode,
106     Immediate,
107     Memory,
108     Register,
109     RegisterList,
110     Token
111   } Kind;
112
113   SMLoc StartLoc, EndLoc;
114
115   union {
116     struct {
117       ARMCC::CondCodes Val;
118     } CC;
119
120     struct {
121       const char *Data;
122       unsigned Length;
123     } Tok;
124
125     struct {
126       unsigned RegNum;
127       bool Writeback;
128     } Reg;
129
130     struct {
131       SmallVector<unsigned, 32> *Registers;
132     } RegList;
133
134     struct {
135       const MCExpr *Val;
136     } Imm;
137
138     // This is for all forms of ARM address expressions
139     struct {
140       unsigned BaseRegNum;
141       unsigned OffsetRegNum;         // used when OffsetIsReg is true
142       const MCExpr *Offset;          // used when OffsetIsReg is false
143       const MCExpr *ShiftAmount;     // used when OffsetRegShifted is true
144       enum ShiftType ShiftType;      // used when OffsetRegShifted is true
145       unsigned OffsetRegShifted : 1; // only used when OffsetIsReg is true
146       unsigned Preindexed : 1;
147       unsigned Postindexed : 1;
148       unsigned OffsetIsReg : 1;
149       unsigned Negative : 1;         // only used when OffsetIsReg is true
150       unsigned Writeback : 1;
151     } Mem;
152   };
153
154   ARMOperand(KindTy K) : MCParsedAsmOperand(), Kind(K) {}
155 public:
156   ARMOperand(const ARMOperand &o) : MCParsedAsmOperand() {
157     Kind = o.Kind;
158     StartLoc = o.StartLoc;
159     EndLoc = o.EndLoc;
160     switch (Kind) {
161     case CondCode:
162       CC = o.CC;
163       break;
164     case Token:
165       Tok = o.Tok;
166       break;
167     case Register:
168       Reg = o.Reg;
169       break;
170     case RegisterList:
171       RegList = o.RegList;
172       break;
173     case Immediate:
174       Imm = o.Imm;
175       break;
176     case Memory:
177       Mem = o.Mem;
178       break;
179     }
180   }
181   ~ARMOperand() {
182     if (isRegList())
183       delete RegList.Registers;
184   }
185
186   /// getStartLoc - Get the location of the first token of this operand.
187   SMLoc getStartLoc() const { return StartLoc; }
188   /// getEndLoc - Get the location of the last token of this operand.
189   SMLoc getEndLoc() const { return EndLoc; }
190
191   ARMCC::CondCodes getCondCode() const {
192     assert(Kind == CondCode && "Invalid access!");
193     return CC.Val;
194   }
195
196   StringRef getToken() const {
197     assert(Kind == Token && "Invalid access!");
198     return StringRef(Tok.Data, Tok.Length);
199   }
200
201   unsigned getReg() const {
202     assert(Kind == Register && "Invalid access!");
203     return Reg.RegNum;
204   }
205
206   const SmallVectorImpl<unsigned> &getRegList() const {
207     assert(Kind == RegisterList && "Invalid access!");
208     return *RegList.Registers;
209   }
210
211   const MCExpr *getImm() const {
212     assert(Kind == Immediate && "Invalid access!");
213     return Imm.Val;
214   }
215
216   bool isCondCode() const { return Kind == CondCode; }
217   bool isImm() const { return Kind == Immediate; }
218   bool isReg() const { return Kind == Register; }
219   bool isRegList() const { return Kind == RegisterList; }
220   bool isToken() const { return Kind == Token; }
221   bool isMemory() const { return Kind == Memory; }
222   bool isMemMode5() const {
223     if (!isMemory() || Mem.OffsetIsReg || Mem.OffsetRegShifted ||
224         Mem.Writeback || Mem.Negative)
225       return false;
226     // If there is an offset expression, make sure it's valid.
227     if (!Mem.Offset)
228       return true;
229     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Mem.Offset);
230     if (!CE)
231       return false;
232     // The offset must be a multiple of 4 in the range 0-1020.
233     int64_t Value = CE->getValue();
234     return ((Value & 0x3) == 0 && Value <= 1020 && Value >= -1020);
235   }
236
237   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
238     // Add as immediates when possible.  Null MCExpr = 0.
239     if (Expr == 0)
240       Inst.addOperand(MCOperand::CreateImm(0));
241     else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
242       Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
243     else
244       Inst.addOperand(MCOperand::CreateExpr(Expr));
245   }
246
247   void addCondCodeOperands(MCInst &Inst, unsigned N) const {
248     assert(N == 2 && "Invalid number of operands!");
249     Inst.addOperand(MCOperand::CreateImm(unsigned(getCondCode())));
250     // FIXME: What belongs here?
251     Inst.addOperand(MCOperand::CreateReg(0));
252   }
253
254   void addRegOperands(MCInst &Inst, unsigned N) const {
255     assert(N == 1 && "Invalid number of operands!");
256     Inst.addOperand(MCOperand::CreateReg(getReg()));
257   }
258
259   void addRegListOperands(MCInst &Inst, unsigned N) const {
260     assert(N == 1 && "Invalid number of operands!");
261     const SmallVectorImpl<unsigned> &RegList = getRegList();
262     for (SmallVectorImpl<unsigned>::const_iterator
263            I = RegList.begin(), E = RegList.end(); I != E; ++I)
264       Inst.addOperand(MCOperand::CreateReg(*I));
265   }
266
267   void addImmOperands(MCInst &Inst, unsigned N) const {
268     assert(N == 1 && "Invalid number of operands!");
269     addExpr(Inst, getImm());
270   }
271
272   void addMemMode5Operands(MCInst &Inst, unsigned N) const {
273     assert(N == 2 && isMemMode5() && "Invalid number of operands!");
274
275     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
276     assert(!Mem.OffsetIsReg && "Invalid mode 5 operand");
277
278     // FIXME: #-0 is encoded differently than #0. Does the parser preserve
279     // the difference?
280     if (Mem.Offset) {
281       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Mem.Offset);
282       assert(CE && "Non-constant mode 5 offset operand!");
283
284       // The MCInst offset operand doesn't include the low two bits (like
285       // the instruction encoding).
286       int64_t Offset = CE->getValue() / 4;
287       if (Offset >= 0)
288         Inst.addOperand(MCOperand::CreateImm(ARM_AM::getAM5Opc(ARM_AM::add,
289                                                                Offset)));
290       else
291         Inst.addOperand(MCOperand::CreateImm(ARM_AM::getAM5Opc(ARM_AM::sub,
292                                                                -Offset)));
293     } else {
294       Inst.addOperand(MCOperand::CreateImm(0));
295     }
296   }
297
298   virtual void dump(raw_ostream &OS) const;
299
300   static ARMOperand *CreateCondCode(ARMCC::CondCodes CC, SMLoc S) {
301     ARMOperand *Op = new ARMOperand(CondCode);
302     Op->CC.Val = CC;
303     Op->StartLoc = S;
304     Op->EndLoc = S;
305     return Op;
306   }
307
308   static ARMOperand *CreateToken(StringRef Str, SMLoc S) {
309     ARMOperand *Op = new ARMOperand(Token);
310     Op->Tok.Data = Str.data();
311     Op->Tok.Length = Str.size();
312     Op->StartLoc = S;
313     Op->EndLoc = S;
314     return Op;
315   }
316
317   static ARMOperand *CreateReg(unsigned RegNum, bool Writeback, SMLoc S,
318                                SMLoc E) {
319     ARMOperand *Op = new ARMOperand(Register);
320     Op->Reg.RegNum = RegNum;
321     Op->Reg.Writeback = Writeback;
322     Op->StartLoc = S;
323     Op->EndLoc = E;
324     return Op;
325   }
326
327   static ARMOperand *
328   CreateRegList(const SmallVectorImpl<std::pair<unsigned, SMLoc> > &Regs,
329                 SMLoc StartLoc, SMLoc EndLoc) {
330     ARMOperand *Op = new ARMOperand(RegisterList);
331     Op->RegList.Registers = new SmallVector<unsigned, 32>();
332     for (SmallVectorImpl<std::pair<unsigned, SMLoc> >::const_iterator
333            I = Regs.begin(), E = Regs.end(); I != E; ++I)
334       Op->RegList.Registers->push_back(I->first);
335     std::sort(Op->RegList.Registers->begin(), Op->RegList.Registers->end());
336     Op->StartLoc = StartLoc;
337     Op->EndLoc = EndLoc;
338     return Op;
339   }
340
341   static ARMOperand *CreateImm(const MCExpr *Val, SMLoc S, SMLoc E) {
342     ARMOperand *Op = new ARMOperand(Immediate);
343     Op->Imm.Val = Val;
344     Op->StartLoc = S;
345     Op->EndLoc = E;
346     return Op;
347   }
348
349   static ARMOperand *CreateMem(unsigned BaseRegNum, bool OffsetIsReg,
350                                const MCExpr *Offset, unsigned OffsetRegNum,
351                                bool OffsetRegShifted, enum ShiftType ShiftType,
352                                const MCExpr *ShiftAmount, bool Preindexed,
353                                bool Postindexed, bool Negative, bool Writeback,
354                                SMLoc S, SMLoc E) {
355     ARMOperand *Op = new ARMOperand(Memory);
356     Op->Mem.BaseRegNum = BaseRegNum;
357     Op->Mem.OffsetIsReg = OffsetIsReg;
358     Op->Mem.Offset = Offset;
359     Op->Mem.OffsetRegNum = OffsetRegNum;
360     Op->Mem.OffsetRegShifted = OffsetRegShifted;
361     Op->Mem.ShiftType = ShiftType;
362     Op->Mem.ShiftAmount = ShiftAmount;
363     Op->Mem.Preindexed = Preindexed;
364     Op->Mem.Postindexed = Postindexed;
365     Op->Mem.Negative = Negative;
366     Op->Mem.Writeback = Writeback;
367
368     Op->StartLoc = S;
369     Op->EndLoc = E;
370     return Op;
371   }
372 };
373
374 } // end anonymous namespace.
375
376 void ARMOperand::dump(raw_ostream &OS) const {
377   switch (Kind) {
378   case CondCode:
379     OS << ARMCondCodeToString(getCondCode());
380     break;
381   case Immediate:
382     getImm()->print(OS);
383     break;
384   case Memory:
385     OS << "<memory>";
386     break;
387   case Register:
388     OS << "<register " << getReg() << ">";
389     break;
390   case RegisterList: {
391     OS << "<register_list ";
392
393     const SmallVectorImpl<unsigned> &RegList = getRegList();
394     for (SmallVectorImpl<unsigned>::const_iterator
395            I = RegList.begin(), E = RegList.end(); I != E; ) {
396       OS << *I;
397       if (++I < E) OS << ", ";
398     }
399
400     OS << ">";
401     break;
402   }
403   case Token:
404     OS << "'" << getToken() << "'";
405     break;
406   }
407 }
408
409 /// @name Auto-generated Match Functions
410 /// {
411
412 static unsigned MatchRegisterName(StringRef Name);
413
414 /// }
415
416 /// Try to parse a register name.  The token must be an Identifier when called,
417 /// and if it is a register name the token is eaten and the register number is
418 /// returned.  Otherwise return -1.
419 ///
420 int ARMAsmParser::TryParseRegister() {
421   const AsmToken &Tok = Parser.getTok();
422   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
423
424   // FIXME: Validate register for the current architecture; we have to do
425   // validation later, so maybe there is no need for this here.
426   unsigned RegNum = MatchRegisterName(Tok.getString());
427   if (RegNum == 0)
428     return -1;
429   Parser.Lex(); // Eat identifier token.
430   return RegNum;
431 }
432
433
434 /// Try to parse a register name.  The token must be an Identifier when called,
435 /// and if it is a register name the token is eaten and the register number is
436 /// returned.  Otherwise return -1.
437 ///
438 /// TODO this is likely to change to allow different register types and or to
439 /// parse for a specific register type.
440 ARMOperand *ARMAsmParser::TryParseRegisterWithWriteBack() {
441   SMLoc S = Parser.getTok().getLoc();
442   int RegNo = TryParseRegister();
443   if (RegNo == -1)
444     return 0;
445
446   SMLoc E = Parser.getTok().getLoc();
447
448   bool Writeback = false;
449   const AsmToken &ExclaimTok = Parser.getTok();
450   if (ExclaimTok.is(AsmToken::Exclaim)) {
451     E = ExclaimTok.getLoc();
452     Writeback = true;
453     Parser.Lex(); // Eat exclaim token
454   }
455
456   return ARMOperand::CreateReg(RegNo, Writeback, S, E);
457 }
458
459 /// Parse a register list, return it if successful else return null.  The first
460 /// token must be a '{' when called.
461 ARMOperand *ARMAsmParser::ParseRegisterList() {
462   assert(Parser.getTok().is(AsmToken::LCurly) &&
463          "Token is not a Left Curly Brace");
464   SMLoc S = Parser.getTok().getLoc();
465
466   // Read the rest of the registers in the list.
467   unsigned PrevRegNum = 0;
468   SmallVector<std::pair<unsigned, SMLoc>, 32> Registers;
469
470   do {
471     bool IsRange = Parser.getTok().is(AsmToken::Minus);
472     Parser.Lex(); // Eat non-identifier token.
473
474     const AsmToken &RegTok = Parser.getTok();
475     SMLoc RegLoc = RegTok.getLoc();
476     if (RegTok.isNot(AsmToken::Identifier)) {
477       Error(RegLoc, "register expected");
478       return 0;
479     }
480
481     int RegNum = TryParseRegister();
482     if (RegNum == -1) {
483       Error(RegLoc, "register expected");
484       return 0;
485     }
486
487     if (IsRange) {
488       int Reg = PrevRegNum;
489       do {
490         ++Reg;
491         Registers.push_back(std::make_pair(Reg, RegLoc));
492       } while (Reg != RegNum);
493     } else {
494       Registers.push_back(std::make_pair(RegNum, RegLoc));
495     }
496
497     PrevRegNum = RegNum;
498   } while (Parser.getTok().is(AsmToken::Comma) ||
499            Parser.getTok().is(AsmToken::Minus));
500
501   // Process the right curly brace of the list.
502   const AsmToken &RCurlyTok = Parser.getTok();
503   if (RCurlyTok.isNot(AsmToken::RCurly)) {
504     Error(RCurlyTok.getLoc(), "'}' expected");
505     return 0;
506   }
507
508   SMLoc E = RCurlyTok.getLoc();
509   Parser.Lex(); // Eat right curly brace token.
510  
511   // Verify the register list.
512   SmallVectorImpl<std::pair<unsigned, SMLoc> >::const_iterator
513     RI = Registers.begin(), RE = Registers.end();
514
515   DenseMap<unsigned, bool> RegMap;
516   RegMap[RI->first] = true;
517
518   unsigned HighRegNum = RI->first;
519   bool EmittedWarning = false;
520
521   for (++RI; RI != RE; ++RI) {
522     const std::pair<unsigned, SMLoc> &RegInfo = *RI;
523     unsigned Reg = RegInfo.first;
524
525     if (RegMap[Reg]) {
526       Error(RegInfo.second, "register duplicated in register list");
527       return 0;
528     }
529
530     if (!EmittedWarning && Reg < HighRegNum)
531       Warning(RegInfo.second,
532               "register not in ascending order in register list");
533
534     RegMap[Reg] = true;
535     HighRegNum = std::max(Reg, HighRegNum);
536   }
537
538   return ARMOperand::CreateRegList(Registers, S, E);
539 }
540
541 /// Parse an ARM memory expression, return false if successful else return true
542 /// or an error.  The first token must be a '[' when called.
543 /// TODO Only preindexing and postindexing addressing are started, unindexed
544 /// with option, etc are still to do.
545 ARMOperand *ARMAsmParser::ParseMemory() {
546   SMLoc S, E;
547   assert(Parser.getTok().is(AsmToken::LBrac) &&
548          "Token is not a Left Bracket");
549   S = Parser.getTok().getLoc();
550   Parser.Lex(); // Eat left bracket token.
551
552   const AsmToken &BaseRegTok = Parser.getTok();
553   if (BaseRegTok.isNot(AsmToken::Identifier)) {
554     Error(BaseRegTok.getLoc(), "register expected");
555     return 0;
556   }
557   int BaseRegNum = TryParseRegister();
558   if (BaseRegNum == -1) {
559     Error(BaseRegTok.getLoc(), "register expected");
560     return 0;
561   }
562
563   bool Preindexed = false;
564   bool Postindexed = false;
565   bool OffsetIsReg = false;
566   bool Negative = false;
567   bool Writeback = false;
568
569   // First look for preindexed address forms, that is after the "[Rn" we now
570   // have to see if the next token is a comma.
571   const AsmToken &Tok = Parser.getTok();
572   if (Tok.is(AsmToken::Comma)) {
573     Preindexed = true;
574     Parser.Lex(); // Eat comma token.
575     int OffsetRegNum;
576     bool OffsetRegShifted;
577     enum ShiftType ShiftType;
578     const MCExpr *ShiftAmount;
579     const MCExpr *Offset;
580     if (ParseMemoryOffsetReg(Negative, OffsetRegShifted, ShiftType, ShiftAmount,
581                              Offset, OffsetIsReg, OffsetRegNum, E))
582       return 0;
583     const AsmToken &RBracTok = Parser.getTok();
584     if (RBracTok.isNot(AsmToken::RBrac)) {
585       Error(RBracTok.getLoc(), "']' expected");
586       return 0;
587     }
588     E = RBracTok.getLoc();
589     Parser.Lex(); // Eat right bracket token.
590
591     const AsmToken &ExclaimTok = Parser.getTok();
592     if (ExclaimTok.is(AsmToken::Exclaim)) {
593       E = ExclaimTok.getLoc();
594       Writeback = true;
595       Parser.Lex(); // Eat exclaim token
596     }
597     return ARMOperand::CreateMem(BaseRegNum, OffsetIsReg, Offset, OffsetRegNum,
598                                  OffsetRegShifted, ShiftType, ShiftAmount,
599                                  Preindexed, Postindexed, Negative, Writeback,
600                                  S, E);
601   }
602   // The "[Rn" we have so far was not followed by a comma.
603   else if (Tok.is(AsmToken::RBrac)) {
604     // If there's anything other than the right brace, this is a post indexing
605     // addressing form.
606     E = Tok.getLoc();
607     Parser.Lex(); // Eat right bracket token.
608
609     int OffsetRegNum = 0;
610     bool OffsetRegShifted = false;
611     enum ShiftType ShiftType;
612     const MCExpr *ShiftAmount;
613     const MCExpr *Offset = 0;
614
615     const AsmToken &NextTok = Parser.getTok();
616     if (NextTok.isNot(AsmToken::EndOfStatement)) {
617       Postindexed = true;
618       Writeback = true;
619       if (NextTok.isNot(AsmToken::Comma)) {
620         Error(NextTok.getLoc(), "',' expected");
621         return 0;
622       }
623       Parser.Lex(); // Eat comma token.
624       if (ParseMemoryOffsetReg(Negative, OffsetRegShifted, ShiftType,
625                                ShiftAmount, Offset, OffsetIsReg, OffsetRegNum,
626                                E))
627         return 0;
628     }
629
630     return ARMOperand::CreateMem(BaseRegNum, OffsetIsReg, Offset, OffsetRegNum,
631                                  OffsetRegShifted, ShiftType, ShiftAmount,
632                                  Preindexed, Postindexed, Negative, Writeback,
633                                  S, E);
634   }
635
636   return 0;
637 }
638
639 /// Parse the offset of a memory operand after we have seen "[Rn," or "[Rn],"
640 /// we will parse the following (were +/- means that a plus or minus is
641 /// optional):
642 ///   +/-Rm
643 ///   +/-Rm, shift
644 ///   #offset
645 /// we return false on success or an error otherwise.
646 bool ARMAsmParser::ParseMemoryOffsetReg(bool &Negative,
647                                         bool &OffsetRegShifted,
648                                         enum ShiftType &ShiftType,
649                                         const MCExpr *&ShiftAmount,
650                                         const MCExpr *&Offset,
651                                         bool &OffsetIsReg,
652                                         int &OffsetRegNum,
653                                         SMLoc &E) {
654   Negative = false;
655   OffsetRegShifted = false;
656   OffsetIsReg = false;
657   OffsetRegNum = -1;
658   const AsmToken &NextTok = Parser.getTok();
659   E = NextTok.getLoc();
660   if (NextTok.is(AsmToken::Plus))
661     Parser.Lex(); // Eat plus token.
662   else if (NextTok.is(AsmToken::Minus)) {
663     Negative = true;
664     Parser.Lex(); // Eat minus token
665   }
666   // See if there is a register following the "[Rn," or "[Rn]," we have so far.
667   const AsmToken &OffsetRegTok = Parser.getTok();
668   if (OffsetRegTok.is(AsmToken::Identifier)) {
669     SMLoc CurLoc = OffsetRegTok.getLoc();
670     OffsetRegNum = TryParseRegister();
671     if (OffsetRegNum != -1) {
672       OffsetIsReg = true;
673       E = CurLoc;
674     }
675   }
676
677   // If we parsed a register as the offset then there can be a shift after that.
678   if (OffsetRegNum != -1) {
679     // Look for a comma then a shift
680     const AsmToken &Tok = Parser.getTok();
681     if (Tok.is(AsmToken::Comma)) {
682       Parser.Lex(); // Eat comma token.
683
684       const AsmToken &Tok = Parser.getTok();
685       if (ParseShift(ShiftType, ShiftAmount, E))
686         return Error(Tok.getLoc(), "shift expected");
687       OffsetRegShifted = true;
688     }
689   }
690   else { // the "[Rn," or "[Rn,]" we have so far was not followed by "Rm"
691     // Look for #offset following the "[Rn," or "[Rn],"
692     const AsmToken &HashTok = Parser.getTok();
693     if (HashTok.isNot(AsmToken::Hash))
694       return Error(HashTok.getLoc(), "'#' expected");
695
696     Parser.Lex(); // Eat hash token.
697
698     if (getParser().ParseExpression(Offset))
699      return true;
700     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
701   }
702   return false;
703 }
704
705 /// ParseShift as one of these two:
706 ///   ( lsl | lsr | asr | ror ) , # shift_amount
707 ///   rrx
708 /// and returns true if it parses a shift otherwise it returns false.
709 bool ARMAsmParser::ParseShift(ShiftType &St, const MCExpr *&ShiftAmount,
710                               SMLoc &E) {
711   const AsmToken &Tok = Parser.getTok();
712   if (Tok.isNot(AsmToken::Identifier))
713     return true;
714   StringRef ShiftName = Tok.getString();
715   if (ShiftName == "lsl" || ShiftName == "LSL")
716     St = Lsl;
717   else if (ShiftName == "lsr" || ShiftName == "LSR")
718     St = Lsr;
719   else if (ShiftName == "asr" || ShiftName == "ASR")
720     St = Asr;
721   else if (ShiftName == "ror" || ShiftName == "ROR")
722     St = Ror;
723   else if (ShiftName == "rrx" || ShiftName == "RRX")
724     St = Rrx;
725   else
726     return true;
727   Parser.Lex(); // Eat shift type token.
728
729   // Rrx stands alone.
730   if (St == Rrx)
731     return false;
732
733   // Otherwise, there must be a '#' and a shift amount.
734   const AsmToken &HashTok = Parser.getTok();
735   if (HashTok.isNot(AsmToken::Hash))
736     return Error(HashTok.getLoc(), "'#' expected");
737   Parser.Lex(); // Eat hash token.
738
739   if (getParser().ParseExpression(ShiftAmount))
740     return true;
741
742   return false;
743 }
744
745 /// Parse a arm instruction operand.  For now this parses the operand regardless
746 /// of the mnemonic.
747 ARMOperand *ARMAsmParser::ParseOperand() {
748   SMLoc S, E;
749   switch (getLexer().getKind()) {
750   default:
751     Error(Parser.getTok().getLoc(), "unexpected token in operand");
752     return 0;
753   case AsmToken::Identifier:
754     if (ARMOperand *Op = TryParseRegisterWithWriteBack())
755       return Op;
756
757     // This was not a register so parse other operands that start with an
758     // identifier (like labels) as expressions and create them as immediates.
759     const MCExpr *IdVal;
760     S = Parser.getTok().getLoc();
761     if (getParser().ParseExpression(IdVal))
762       return 0;
763     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
764     return ARMOperand::CreateImm(IdVal, S, E);
765   case AsmToken::LBrac:
766     return ParseMemory();
767   case AsmToken::LCurly:
768     return ParseRegisterList();
769   case AsmToken::Hash:
770     // #42 -> immediate.
771     // TODO: ":lower16:" and ":upper16:" modifiers after # before immediate
772     S = Parser.getTok().getLoc();
773     Parser.Lex();
774     const MCExpr *ImmVal;
775     if (getParser().ParseExpression(ImmVal))
776       return 0;
777     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
778     return ARMOperand::CreateImm(ImmVal, S, E);
779   }
780 }
781
782 /// Parse an arm instruction mnemonic followed by its operands.
783 bool ARMAsmParser::ParseInstruction(StringRef Name, SMLoc NameLoc,
784                                SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
785   // Create the leading tokens for the mnemonic, split by '.' characters.
786   size_t Start = 0, Next = Name.find('.');
787   StringRef Head = Name.slice(Start, Next);
788
789   // Determine the predicate, if any.
790   //
791   // FIXME: We need a way to check whether a prefix supports predication,
792   // otherwise we will end up with an ambiguity for instructions that happen to
793   // end with a predicate name.
794   // FIXME: Likewise, some arithmetic instructions have an 's' prefix which
795   // indicates to update the condition codes. Those instructions have an
796   // additional immediate operand which encodes the prefix as reg0 or CPSR.
797   // Just checking for a suffix of 's' definitely creates ambiguities; e.g,
798   // the SMMLS instruction.
799   unsigned CC = StringSwitch<unsigned>(Head.substr(Head.size()-2))
800     .Case("eq", ARMCC::EQ)
801     .Case("ne", ARMCC::NE)
802     .Case("hs", ARMCC::HS)
803     .Case("lo", ARMCC::LO)
804     .Case("mi", ARMCC::MI)
805     .Case("pl", ARMCC::PL)
806     .Case("vs", ARMCC::VS)
807     .Case("vc", ARMCC::VC)
808     .Case("hi", ARMCC::HI)
809     .Case("ls", ARMCC::LS)
810     .Case("ge", ARMCC::GE)
811     .Case("lt", ARMCC::LT)
812     .Case("gt", ARMCC::GT)
813     .Case("le", ARMCC::LE)
814     .Case("al", ARMCC::AL)
815     .Default(~0U);
816
817   if (CC == ~0U ||
818       (CC == ARMCC::LS && (Head == "vmls" || Head == "vnmls"))) {
819     CC = ARMCC::AL;
820   } else {
821     Head = Head.slice(0, Head.size() - 2);
822   }
823
824   Operands.push_back(ARMOperand::CreateToken(Head, NameLoc));
825   // FIXME: Should only add this operand for predicated instructions
826   Operands.push_back(ARMOperand::CreateCondCode(ARMCC::CondCodes(CC), NameLoc));
827
828   // Add the remaining tokens in the mnemonic.
829   while (Next != StringRef::npos) {
830     Start = Next;
831     Next = Name.find('.', Start + 1);
832     Head = Name.slice(Start, Next);
833
834     Operands.push_back(ARMOperand::CreateToken(Head, NameLoc));
835   }
836
837   // Read the remaining operands.
838   if (getLexer().isNot(AsmToken::EndOfStatement)) {
839     // Read the first operand.
840     if (ARMOperand *Op = ParseOperand())
841       Operands.push_back(Op);
842     else {
843       Parser.EatToEndOfStatement();
844       return true;
845     }
846
847     while (getLexer().is(AsmToken::Comma)) {
848       Parser.Lex();  // Eat the comma.
849
850       // Parse and remember the operand.
851       if (ARMOperand *Op = ParseOperand())
852         Operands.push_back(Op);
853       else {
854         Parser.EatToEndOfStatement();
855         return true;
856       }
857     }
858   }
859
860   if (getLexer().isNot(AsmToken::EndOfStatement)) {
861     Parser.EatToEndOfStatement();
862     return TokError("unexpected token in argument list");
863   }
864
865   Parser.Lex(); // Consume the EndOfStatement
866   return false;
867 }
868
869 bool ARMAsmParser::
870 MatchAndEmitInstruction(SMLoc IDLoc,
871                         SmallVectorImpl<MCParsedAsmOperand*> &Operands,
872                         MCStreamer &Out) {
873   MCInst Inst;
874   unsigned ErrorInfo;
875   switch (MatchInstructionImpl(Operands, Inst, ErrorInfo)) {
876   case Match_Success:
877     Out.EmitInstruction(Inst);
878     return false;
879   case Match_MissingFeature:
880     Error(IDLoc, "instruction requires a CPU feature not currently enabled");
881     return true;
882   case Match_InvalidOperand: {
883     SMLoc ErrorLoc = IDLoc;
884     if (ErrorInfo != ~0U) {
885       if (ErrorInfo >= Operands.size())
886         return Error(IDLoc, "too few operands for instruction");
887
888       ErrorLoc = ((ARMOperand*)Operands[ErrorInfo])->getStartLoc();
889       if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
890     }
891
892     return Error(ErrorLoc, "invalid operand for instruction");
893   }
894   case Match_MnemonicFail:
895     return Error(IDLoc, "unrecognized instruction mnemonic");
896   }
897
898   llvm_unreachable("Implement any new match types added!");
899   return true;
900 }
901
902 /// ParseDirective parses the arm specific directives
903 bool ARMAsmParser::ParseDirective(AsmToken DirectiveID) {
904   StringRef IDVal = DirectiveID.getIdentifier();
905   if (IDVal == ".word")
906     return ParseDirectiveWord(4, DirectiveID.getLoc());
907   else if (IDVal == ".thumb")
908     return ParseDirectiveThumb(DirectiveID.getLoc());
909   else if (IDVal == ".thumb_func")
910     return ParseDirectiveThumbFunc(DirectiveID.getLoc());
911   else if (IDVal == ".code")
912     return ParseDirectiveCode(DirectiveID.getLoc());
913   else if (IDVal == ".syntax")
914     return ParseDirectiveSyntax(DirectiveID.getLoc());
915   return true;
916 }
917
918 /// ParseDirectiveWord
919 ///  ::= .word [ expression (, expression)* ]
920 bool ARMAsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
921   if (getLexer().isNot(AsmToken::EndOfStatement)) {
922     for (;;) {
923       const MCExpr *Value;
924       if (getParser().ParseExpression(Value))
925         return true;
926
927       getParser().getStreamer().EmitValue(Value, Size, 0/*addrspace*/);
928
929       if (getLexer().is(AsmToken::EndOfStatement))
930         break;
931
932       // FIXME: Improve diagnostic.
933       if (getLexer().isNot(AsmToken::Comma))
934         return Error(L, "unexpected token in directive");
935       Parser.Lex();
936     }
937   }
938
939   Parser.Lex();
940   return false;
941 }
942
943 /// ParseDirectiveThumb
944 ///  ::= .thumb
945 bool ARMAsmParser::ParseDirectiveThumb(SMLoc L) {
946   if (getLexer().isNot(AsmToken::EndOfStatement))
947     return Error(L, "unexpected token in directive");
948   Parser.Lex();
949
950   // TODO: set thumb mode
951   // TODO: tell the MC streamer the mode
952   // getParser().getStreamer().Emit???();
953   return false;
954 }
955
956 /// ParseDirectiveThumbFunc
957 ///  ::= .thumbfunc symbol_name
958 bool ARMAsmParser::ParseDirectiveThumbFunc(SMLoc L) {
959   const AsmToken &Tok = Parser.getTok();
960   if (Tok.isNot(AsmToken::Identifier) && Tok.isNot(AsmToken::String))
961     return Error(L, "unexpected token in .thumb_func directive");
962   StringRef Name = Tok.getString();
963   Parser.Lex(); // Consume the identifier token.
964   if (getLexer().isNot(AsmToken::EndOfStatement))
965     return Error(L, "unexpected token in directive");
966   Parser.Lex();
967
968   // Mark symbol as a thumb symbol.
969   MCSymbol *Func = getParser().getContext().GetOrCreateSymbol(Name);
970   getParser().getStreamer().EmitThumbFunc(Func);
971   return false;
972 }
973
974 /// ParseDirectiveSyntax
975 ///  ::= .syntax unified | divided
976 bool ARMAsmParser::ParseDirectiveSyntax(SMLoc L) {
977   const AsmToken &Tok = Parser.getTok();
978   if (Tok.isNot(AsmToken::Identifier))
979     return Error(L, "unexpected token in .syntax directive");
980   StringRef Mode = Tok.getString();
981   if (Mode == "unified" || Mode == "UNIFIED")
982     Parser.Lex();
983   else if (Mode == "divided" || Mode == "DIVIDED")
984     Parser.Lex();
985   else
986     return Error(L, "unrecognized syntax mode in .syntax directive");
987
988   if (getLexer().isNot(AsmToken::EndOfStatement))
989     return Error(Parser.getTok().getLoc(), "unexpected token in directive");
990   Parser.Lex();
991
992   // TODO tell the MC streamer the mode
993   // getParser().getStreamer().Emit???();
994   return false;
995 }
996
997 /// ParseDirectiveCode
998 ///  ::= .code 16 | 32
999 bool ARMAsmParser::ParseDirectiveCode(SMLoc L) {
1000   const AsmToken &Tok = Parser.getTok();
1001   if (Tok.isNot(AsmToken::Integer))
1002     return Error(L, "unexpected token in .code directive");
1003   int64_t Val = Parser.getTok().getIntVal();
1004   if (Val == 16)
1005     Parser.Lex();
1006   else if (Val == 32)
1007     Parser.Lex();
1008   else
1009     return Error(L, "invalid operand to .code directive");
1010
1011   if (getLexer().isNot(AsmToken::EndOfStatement))
1012     return Error(Parser.getTok().getLoc(), "unexpected token in directive");
1013   Parser.Lex();
1014
1015   if (Val == 16)
1016     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
1017   else
1018     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
1019
1020   return false;
1021 }
1022
1023 extern "C" void LLVMInitializeARMAsmLexer();
1024
1025 /// Force static initialization.
1026 extern "C" void LLVMInitializeARMAsmParser() {
1027   RegisterAsmParser<ARMAsmParser> X(TheARMTarget);
1028   RegisterAsmParser<ARMAsmParser> Y(TheThumbTarget);
1029   LLVMInitializeARMAsmLexer();
1030 }
1031
1032 #define GET_REGISTER_MATCHER
1033 #define GET_MATCHER_IMPLEMENTATION
1034 #include "ARMGenAsmMatcher.inc"