Add support for @note. Patch by Jörg Sonnenberger.
[oota-llvm.git] / lib / MC / MCParser / ELFAsmParser.cpp
1 //===- ELFAsmParser.cpp - ELF Assembly Parser -----------------------------===//
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 "llvm/MC/MCParser/MCAsmParserExtension.h"
11 #include "llvm/ADT/StringSwitch.h"
12 #include "llvm/ADT/Twine.h"
13 #include "llvm/MC/MCAsmInfo.h"
14 #include "llvm/MC/MCContext.h"
15 #include "llvm/MC/MCExpr.h"
16 #include "llvm/MC/MCParser/MCAsmLexer.h"
17 #include "llvm/MC/MCSectionELF.h"
18 #include "llvm/MC/MCStreamer.h"
19 using namespace llvm;
20
21 namespace {
22
23 class ELFAsmParser : public MCAsmParserExtension {
24   template<bool (ELFAsmParser::*Handler)(StringRef, SMLoc)>
25   void AddDirectiveHandler(StringRef Directive) {
26     getParser().AddDirectiveHandler(this, Directive,
27                                     HandleDirective<ELFAsmParser, Handler>);
28   }
29
30   bool ParseSectionSwitch(StringRef Section, unsigned Type,
31                           unsigned Flags, SectionKind Kind);
32
33 public:
34   ELFAsmParser() {}
35
36   virtual void Initialize(MCAsmParser &Parser) {
37     // Call the base implementation.
38     this->MCAsmParserExtension::Initialize(Parser);
39
40     AddDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveData>(".data");
41     AddDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveText>(".text");
42     AddDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveBSS>(".bss");
43     AddDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveRoData>(".rodata");
44     AddDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveTData>(".tdata");
45     AddDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveTBSS>(".tbss");
46     AddDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveDataRel>(".data.rel");
47     AddDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveDataRelRo>(".data.rel.ro");
48     AddDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveDataRelRoLocal>(".data.rel.ro.local");
49     AddDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveEhFrame>(".eh_frame");
50     AddDirectiveHandler<&ELFAsmParser::ParseDirectiveSection>(".section");
51     AddDirectiveHandler<&ELFAsmParser::ParseDirectiveSize>(".size");
52     AddDirectiveHandler<&ELFAsmParser::ParseDirectivePrevious>(".previous");
53     AddDirectiveHandler<&ELFAsmParser::ParseDirectiveType>(".type");
54     AddDirectiveHandler<&ELFAsmParser::ParseDirectiveIdent>(".ident");
55     AddDirectiveHandler<&ELFAsmParser::ParseDirectiveSymver>(".symver");
56     AddDirectiveHandler<&ELFAsmParser::ParseDirectiveWeakref>(".weakref");
57   }
58
59   // FIXME: Part of this logic is duplicated in the MCELFStreamer. What is
60   // the best way for us to get access to it?
61   bool ParseSectionDirectiveData(StringRef, SMLoc) {
62     return ParseSectionSwitch(".data", MCSectionELF::SHT_PROGBITS,
63                               MCSectionELF::SHF_WRITE |MCSectionELF::SHF_ALLOC,
64                               SectionKind::getDataRel());
65   }
66   bool ParseSectionDirectiveText(StringRef, SMLoc) {
67     return ParseSectionSwitch(".text", MCSectionELF::SHT_PROGBITS,
68                               MCSectionELF::SHF_EXECINSTR |
69                               MCSectionELF::SHF_ALLOC, SectionKind::getText());
70   }
71   bool ParseSectionDirectiveBSS(StringRef, SMLoc) {
72     return ParseSectionSwitch(".bss", MCSectionELF::SHT_NOBITS,
73                               MCSectionELF::SHF_WRITE |
74                               MCSectionELF::SHF_ALLOC, SectionKind::getBSS());
75   }
76   bool ParseSectionDirectiveRoData(StringRef, SMLoc) {
77     return ParseSectionSwitch(".rodata", MCSectionELF::SHT_PROGBITS,
78                               MCSectionELF::SHF_ALLOC,
79                               SectionKind::getReadOnly());
80   }
81   bool ParseSectionDirectiveTData(StringRef, SMLoc) {
82     return ParseSectionSwitch(".tdata", MCSectionELF::SHT_PROGBITS,
83                               MCSectionELF::SHF_ALLOC |
84                               MCSectionELF::SHF_TLS | MCSectionELF::SHF_WRITE,
85                               SectionKind::getThreadData());
86   }
87   bool ParseSectionDirectiveTBSS(StringRef, SMLoc) {
88     return ParseSectionSwitch(".tbss", MCSectionELF::SHT_NOBITS,
89                               MCSectionELF::SHF_ALLOC |
90                               MCSectionELF::SHF_TLS | MCSectionELF::SHF_WRITE,
91                               SectionKind::getThreadBSS());
92   }
93   bool ParseSectionDirectiveDataRel(StringRef, SMLoc) {
94     return ParseSectionSwitch(".data.rel", MCSectionELF::SHT_PROGBITS,
95                               MCSectionELF::SHF_ALLOC |
96                               MCSectionELF::SHF_WRITE,
97                               SectionKind::getDataRel());
98   }
99   bool ParseSectionDirectiveDataRelRo(StringRef, SMLoc) {
100     return ParseSectionSwitch(".data.rel.ro", MCSectionELF::SHT_PROGBITS,
101                               MCSectionELF::SHF_ALLOC |
102                               MCSectionELF::SHF_WRITE,
103                               SectionKind::getReadOnlyWithRel());
104   }
105   bool ParseSectionDirectiveDataRelRoLocal(StringRef, SMLoc) {
106     return ParseSectionSwitch(".data.rel.ro.local", MCSectionELF::SHT_PROGBITS,
107                               MCSectionELF::SHF_ALLOC |
108                               MCSectionELF::SHF_WRITE,
109                               SectionKind::getReadOnlyWithRelLocal());
110   }
111   bool ParseSectionDirectiveEhFrame(StringRef, SMLoc) {
112     return ParseSectionSwitch(".eh_frame", MCSectionELF::SHT_PROGBITS,
113                               MCSectionELF::SHF_ALLOC |
114                               MCSectionELF::SHF_WRITE,
115                               SectionKind::getDataRel());
116   }
117   bool ParseDirectiveSection(StringRef, SMLoc);
118   bool ParseDirectiveSize(StringRef, SMLoc);
119   bool ParseDirectivePrevious(StringRef, SMLoc);
120   bool ParseDirectiveType(StringRef, SMLoc);
121   bool ParseDirectiveIdent(StringRef, SMLoc);
122   bool ParseDirectiveSymver(StringRef, SMLoc);
123   bool ParseDirectiveWeakref(StringRef, SMLoc);
124
125 private:
126   bool ParseSectionName(StringRef &SectionName);
127 };
128
129 }
130
131 bool ELFAsmParser::ParseSectionSwitch(StringRef Section, unsigned Type,
132                                       unsigned Flags, SectionKind Kind) {
133   if (getLexer().isNot(AsmToken::EndOfStatement))
134     return TokError("unexpected token in section switching directive");
135   Lex();
136
137   getStreamer().SwitchSection(getContext().getELFSection(
138                                 Section, Type, Flags, Kind));
139
140   return false;
141 }
142
143 bool ELFAsmParser::ParseDirectiveSize(StringRef, SMLoc) {
144   StringRef Name;
145   if (getParser().ParseIdentifier(Name))
146     return TokError("expected identifier in directive");
147   MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);;
148
149   if (getLexer().isNot(AsmToken::Comma))
150     return TokError("unexpected token in directive");
151   Lex();
152
153   const MCExpr *Expr;
154   if (getParser().ParseExpression(Expr))
155     return true;
156
157   if (getLexer().isNot(AsmToken::EndOfStatement))
158     return TokError("unexpected token in directive");
159
160   getStreamer().EmitELFSize(Sym, Expr);
161   return false;
162 }
163
164 bool ELFAsmParser::ParseSectionName(StringRef &SectionName) {
165   // A section name can contain -, so we cannot just use
166   // ParseIdentifier.
167   SMLoc FirstLoc = getLexer().getLoc();
168   unsigned Size = 0;
169
170   for (;;) {
171     StringRef Tmp;
172     unsigned CurSize;
173
174     SMLoc PrevLoc = getLexer().getLoc();
175     if (getLexer().is(AsmToken::Minus)) {
176       CurSize = 1;
177       Lex(); // Consume the "-".
178     } else if (!getParser().ParseIdentifier(Tmp))
179       CurSize = Tmp.size();
180     else
181       break;
182
183     Size += CurSize;
184     SectionName = StringRef(FirstLoc.getPointer(), Size);
185
186     // Make sure the following token is adjacent.
187     if (PrevLoc.getPointer() + CurSize != getTok().getLoc().getPointer())
188       break;
189   }
190   if (Size == 0)
191     return true;
192
193   return false;
194 }
195
196 static SectionKind computeSectionKind(unsigned Flags) {
197   if (Flags & MCSectionELF::SHF_EXECINSTR)
198     return SectionKind::getText();
199   if (Flags & MCSectionELF::SHF_TLS)
200     return SectionKind::getThreadData();
201   return SectionKind::getDataRel();
202 }
203
204 static int parseSectionFlags(StringRef flagsStr) {
205   int flags = 0;
206
207   for (unsigned i = 0; i < flagsStr.size(); i++) {
208     switch (flagsStr[i]) {
209     case 'a':
210       flags |= MCSectionELF::SHF_ALLOC;
211       break;
212     case 'x':
213       flags |= MCSectionELF::SHF_EXECINSTR;
214       break;
215     case 'w':
216       flags |= MCSectionELF::SHF_WRITE;
217       break;
218     case 'M':
219       flags |= MCSectionELF::SHF_MERGE;
220       break;
221     case 'S':
222       flags |= MCSectionELF::SHF_STRINGS;
223       break;
224     case 'T':
225       flags |= MCSectionELF::SHF_TLS;
226       break;
227     case 'c':
228       flags |= MCSectionELF::XCORE_SHF_CP_SECTION;
229       break;
230     case 'd':
231       flags |= MCSectionELF::XCORE_SHF_DP_SECTION;
232       break;
233     case 'G':
234       flags |= MCSectionELF::SHF_GROUP;
235       break;
236     default:
237       return -1;
238     }
239   }
240
241   return flags;
242 }
243
244 // FIXME: This is a work in progress.
245 bool ELFAsmParser::ParseDirectiveSection(StringRef, SMLoc) {
246   StringRef SectionName;
247
248   if (ParseSectionName(SectionName))
249     return TokError("expected identifier in directive");
250
251   StringRef TypeName;
252   int64_t Size = 0;
253   StringRef GroupName;
254   unsigned Flags = 0;
255
256   // Set the defaults first.
257   if (SectionName == ".fini" || SectionName == ".init" ||
258       SectionName == ".rodata")
259     Flags |= MCSectionELF::SHF_ALLOC;
260   if (SectionName == ".fini" || SectionName == ".init")
261     Flags |= MCSectionELF::SHF_EXECINSTR;
262
263   if (getLexer().is(AsmToken::Comma)) {
264     Lex();
265
266     if (getLexer().isNot(AsmToken::String))
267       return TokError("expected string in directive");
268
269     StringRef FlagsStr = getTok().getStringContents();
270     Lex();
271
272     int extraFlags = parseSectionFlags(FlagsStr);
273     if (extraFlags < 0)
274       return TokError("unknown flag");
275     Flags |= extraFlags;
276
277     bool Mergeable = Flags & MCSectionELF::SHF_MERGE;
278     bool Group = Flags & MCSectionELF::SHF_GROUP;
279
280     if (getLexer().isNot(AsmToken::Comma)) {
281       if (Mergeable)
282         return TokError("Mergeable section must specify the type");
283       if (Group)
284         return TokError("Group section must specify the type");
285     } else {
286       Lex();
287       if (getLexer().isNot(AsmToken::Percent) && getLexer().isNot(AsmToken::At))
288         return TokError("expected '@' or '%' before type");
289
290       Lex();
291       if (getParser().ParseIdentifier(TypeName))
292         return TokError("expected identifier in directive");
293
294       if (Mergeable) {
295         if (getLexer().isNot(AsmToken::Comma))
296           return TokError("expected the entry size");
297         Lex();
298         if (getParser().ParseAbsoluteExpression(Size))
299           return true;
300         if (Size <= 0)
301           return TokError("entry size must be positive");
302       }
303
304       if (Group) {
305         if (getLexer().isNot(AsmToken::Comma))
306           return TokError("expected group name");
307         Lex();
308         if (getParser().ParseIdentifier(GroupName))
309           return true;
310         if (getLexer().is(AsmToken::Comma)) {
311           Lex();
312           StringRef Linkage;
313           if (getParser().ParseIdentifier(Linkage))
314             return true;
315           if (Linkage != "comdat")
316             return TokError("Linkage must be 'comdat'");
317         }
318       }
319     }
320   }
321
322   if (getLexer().isNot(AsmToken::EndOfStatement))
323     return TokError("unexpected token in directive");
324
325   unsigned Type = MCSectionELF::SHT_PROGBITS;
326
327   if (!TypeName.empty()) {
328     if (TypeName == "init_array")
329       Type = MCSectionELF::SHT_INIT_ARRAY;
330     else if (TypeName == "fini_array")
331       Type = MCSectionELF::SHT_FINI_ARRAY;
332     else if (TypeName == "preinit_array")
333       Type = MCSectionELF::SHT_PREINIT_ARRAY;
334     else if (TypeName == "nobits")
335       Type = MCSectionELF::SHT_NOBITS;
336     else if (TypeName == "progbits")
337       Type = MCSectionELF::SHT_PROGBITS;
338     else if (TypeName == "note")
339       Type = MCSectionELF::SHT_NOTE;
340     else
341       return TokError("unknown section type");
342   }
343
344   SectionKind Kind = computeSectionKind(Flags);
345   getStreamer().SwitchSection(getContext().getELFSection(SectionName, Type,
346                                                          Flags, Kind, Size,
347                                                          GroupName));
348   return false;
349 }
350
351 bool ELFAsmParser::ParseDirectivePrevious(StringRef DirName, SMLoc) {
352   const MCSection *PreviousSection = getStreamer().getPreviousSection();
353   if (PreviousSection != NULL)
354     getStreamer().SwitchSection(PreviousSection);
355
356   return false;
357 }
358
359 /// ParseDirectiveELFType
360 ///  ::= .type identifier , @attribute
361 bool ELFAsmParser::ParseDirectiveType(StringRef, SMLoc) {
362   StringRef Name;
363   if (getParser().ParseIdentifier(Name))
364     return TokError("expected identifier in directive");
365
366   // Handle the identifier as the key symbol.
367   MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
368
369   if (getLexer().isNot(AsmToken::Comma))
370     return TokError("unexpected token in '.type' directive");
371   Lex();
372
373   if (getLexer().isNot(AsmToken::Percent) && getLexer().isNot(AsmToken::At))
374     return TokError("expected '@' or '%' before type");
375   Lex();
376
377   StringRef Type;
378   SMLoc TypeLoc;
379
380   TypeLoc = getLexer().getLoc();
381   if (getParser().ParseIdentifier(Type))
382     return TokError("expected symbol type in directive");
383
384   MCSymbolAttr Attr = StringSwitch<MCSymbolAttr>(Type)
385     .Case("function", MCSA_ELF_TypeFunction)
386     .Case("object", MCSA_ELF_TypeObject)
387     .Case("tls_object", MCSA_ELF_TypeTLS)
388     .Case("common", MCSA_ELF_TypeCommon)
389     .Case("notype", MCSA_ELF_TypeNoType)
390     .Case("gnu_unique_object", MCSA_ELF_TypeGnuUniqueObject)
391     .Default(MCSA_Invalid);
392
393   if (Attr == MCSA_Invalid)
394     return Error(TypeLoc, "unsupported attribute in '.type' directive");
395
396   if (getLexer().isNot(AsmToken::EndOfStatement))
397     return TokError("unexpected token in '.type' directive");
398
399   Lex();
400
401   getStreamer().EmitSymbolAttribute(Sym, Attr);
402
403   return false;
404 }
405
406 /// ParseDirectiveIdent
407 ///  ::= .ident string
408 bool ELFAsmParser::ParseDirectiveIdent(StringRef, SMLoc) {
409   if (getLexer().isNot(AsmToken::String))
410     return TokError("unexpected token in '.ident' directive");
411
412   StringRef Data = getTok().getIdentifier();
413
414   Lex();
415
416   const MCSection *OldSection = getStreamer().getCurrentSection();
417   const MCSection *Comment =
418     getContext().getELFSection(".comment", MCSectionELF::SHT_PROGBITS,
419                                MCSectionELF::SHF_MERGE |
420                                MCSectionELF::SHF_STRINGS,
421                                SectionKind::getReadOnly(),
422                                1, "");
423
424   static bool First = true;
425
426   getStreamer().SwitchSection(Comment);
427   if (First)
428     getStreamer().EmitIntValue(0, 1);
429   First = false;
430   getStreamer().EmitBytes(Data, 0);
431   getStreamer().EmitIntValue(0, 1);
432   getStreamer().SwitchSection(OldSection);
433   return false;
434 }
435
436 /// ParseDirectiveSymver
437 ///  ::= .symver foo, bar2@zed
438 bool ELFAsmParser::ParseDirectiveSymver(StringRef, SMLoc) {
439   StringRef Name;
440   if (getParser().ParseIdentifier(Name))
441     return TokError("expected identifier in directive");
442
443   if (getLexer().isNot(AsmToken::Comma))
444     return TokError("expected a comma");
445
446   Lex();
447
448   StringRef AliasName;
449   if (getParser().ParseIdentifier(AliasName))
450     return TokError("expected identifier in directive");
451
452   if (AliasName.find('@') == StringRef::npos)
453     return TokError("expected a '@' in the name");
454
455   MCSymbol *Alias = getContext().GetOrCreateSymbol(AliasName);
456   MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
457   const MCExpr *Value = MCSymbolRefExpr::Create(Sym, getContext());
458
459   getStreamer().EmitAssignment(Alias, Value);
460   return false;
461 }
462
463 /// ParseDirectiveWeakref
464 ///  ::= .weakref foo, bar
465 bool ELFAsmParser::ParseDirectiveWeakref(StringRef, SMLoc) {
466   // FIXME: Share code with the other alias building directives.
467
468   StringRef AliasName;
469   if (getParser().ParseIdentifier(AliasName))
470     return TokError("expected identifier in directive");
471
472   if (getLexer().isNot(AsmToken::Comma))
473     return TokError("expected a comma");
474
475   Lex();
476
477   StringRef Name;
478   if (getParser().ParseIdentifier(Name))
479     return TokError("expected identifier in directive");
480
481   MCSymbol *Alias = getContext().GetOrCreateSymbol(AliasName);
482
483   MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
484
485   getStreamer().EmitWeakReference(Alias, Sym);
486   return false;
487 }
488
489 namespace llvm {
490
491 MCAsmParserExtension *createELFAsmParser() {
492   return new ELFAsmParser;
493 }
494
495 }