1 //===- WasmAsmParser.cpp - Wasm Assembly Parser -----------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 // --
8 //
9 // Note, this is for wasm, the binary format (analogous to ELF), not wasm,
10 // the instruction set (analogous to x86), for which parsing code lives in
11 // WebAssemblyAsmParser.
12 //
13 // This file contains processing for generic directives implemented using
14 // MCTargetStreamer, the ones that depend on WebAssemblyTargetStreamer are in
15 // WebAssemblyAsmParser.
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "llvm/BinaryFormat/Wasm.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCParser/MCAsmLexer.h"
22 #include "llvm/MC/MCParser/MCAsmParser.h"
23 #include "llvm/MC/MCParser/MCAsmParserExtension.h"
24 #include "llvm/MC/MCSectionWasm.h"
25 #include "llvm/MC/MCStreamer.h"
26 #include "llvm/MC/MCSymbol.h"
27 #include "llvm/MC/MCSymbolWasm.h"
28 #include "llvm/Support/MachineValueType.h"
29 
30 using namespace llvm;
31 
32 namespace {
33 
34 class WasmAsmParser : public MCAsmParserExtension {
35   MCAsmParser *Parser = nullptr;
36   MCAsmLexer *Lexer = nullptr;
37 
38   template<bool (WasmAsmParser::*HandlerMethod)(StringRef, SMLoc)>
39   void addDirectiveHandler(StringRef Directive) {
40     MCAsmParser::ExtensionDirectiveHandler Handler = std::make_pair(
41         this, HandleDirective<WasmAsmParser, HandlerMethod>);
42 
43     getParser().addDirectiveHandler(Directive, Handler);
44   }
45 
46 public:
47   WasmAsmParser() { BracketExpressionsSupported = true; }
48 
49   void Initialize(MCAsmParser &P) override {
50     Parser = &P;
51     Lexer = &Parser->getLexer();
52     // Call the base implementation.
53     this->MCAsmParserExtension::Initialize(*Parser);
54 
55     addDirectiveHandler<&WasmAsmParser::parseSectionDirectiveText>(".text");
56     addDirectiveHandler<&WasmAsmParser::parseSectionDirective>(".section");
57     addDirectiveHandler<&WasmAsmParser::parseDirectiveSize>(".size");
58     addDirectiveHandler<&WasmAsmParser::parseDirectiveType>(".type");
59     addDirectiveHandler<&WasmAsmParser::ParseDirectiveIdent>(".ident");
60     addDirectiveHandler<
61       &WasmAsmParser::ParseDirectiveSymbolAttribute>(".weak");
62     addDirectiveHandler<
63       &WasmAsmParser::ParseDirectiveSymbolAttribute>(".local");
64     addDirectiveHandler<
65       &WasmAsmParser::ParseDirectiveSymbolAttribute>(".internal");
66     addDirectiveHandler<
67       &WasmAsmParser::ParseDirectiveSymbolAttribute>(".hidden");
68   }
69 
70   bool error(const StringRef &Msg, const AsmToken &Tok) {
71     return Parser->Error(Tok.getLoc(), Msg + Tok.getString());
72   }
73 
74   bool isNext(AsmToken::TokenKind Kind) {
75     auto Ok = Lexer->is(Kind);
76     if (Ok)
77       Lex();
78     return Ok;
79   }
80 
81   bool expect(AsmToken::TokenKind Kind, const char *KindName) {
82     if (!isNext(Kind))
83       return error(std::string("Expected ") + KindName + ", instead got: ",
84                    Lexer->getTok());
85     return false;
86   }
87 
88   bool parseSectionDirectiveText(StringRef, SMLoc) {
89     // FIXME: .text currently no-op.
90     return false;
91   }
92 
93   bool parseSectionFlags(StringRef FlagStr, bool &Passive, bool &Group) {
94     for (char C : FlagStr) {
95       switch (C) {
96       case 'p':
97         Passive = true;
98         break;
99       case 'G':
100         Group = true;
101         break;
102       default:
103         return Parser->Error(getTok().getLoc(),
104                              StringRef("Unexepcted section flag: ") + FlagStr);
105       }
106     }
107     return false;
108   }
109 
110   bool parseGroup(StringRef &GroupName) {
111     if (Lexer->isNot(AsmToken::Comma))
112       return TokError("expected group name");
113     Lex();
114     if (Lexer->is(AsmToken::Integer)) {
115       GroupName = getTok().getString();
116       Lex();
117     } else if (Parser->parseIdentifier(GroupName)) {
118       return TokError("invalid group name");
119     }
120     if (Lexer->is(AsmToken::Comma)) {
121       Lex();
122       StringRef Linkage;
123       if (Parser->parseIdentifier(Linkage))
124         return TokError("invalid linkage");
125       if (Linkage != "comdat")
126         return TokError("Linkage must be 'comdat'");
127     }
128     return false;
129   }
130 
131   bool parseSectionDirective(StringRef, SMLoc) {
132     StringRef Name;
133     if (Parser->parseIdentifier(Name))
134       return TokError("expected identifier in directive");
135 
136     if (expect(AsmToken::Comma, ","))
137       return true;
138 
139     if (Lexer->isNot(AsmToken::String))
140       return error("expected string in directive, instead got: ", Lexer->getTok());
141 
142     auto Kind = StringSwitch<Optional<SectionKind>>(Name)
143                     .StartsWith(".data", SectionKind::getData())
144                     .StartsWith(".tdata", SectionKind::getThreadData())
145                     .StartsWith(".tbss", SectionKind::getThreadBSS())
146                     .StartsWith(".rodata", SectionKind::getReadOnly())
147                     .StartsWith(".text", SectionKind::getText())
148                     .StartsWith(".custom_section", SectionKind::getMetadata())
149                     .StartsWith(".bss", SectionKind::getBSS())
150                     // See use of .init_array in WasmObjectWriter and
151                     // TargetLoweringObjectFileWasm
152                     .StartsWith(".init_array", SectionKind::getData())
153                     .StartsWith(".debug_", SectionKind::getMetadata())
154                     .Default(SectionKind::getData());
155 
156     // Update section flags if present in this .section directive
157     bool Passive = false;
158     bool Group = false;
159     if (parseSectionFlags(getTok().getStringContents(), Passive, Group))
160       return true;
161 
162     Lex();
163 
164     if (expect(AsmToken::Comma, ",") || expect(AsmToken::At, "@"))
165       return true;
166 
167     StringRef GroupName;
168     if (Group && parseGroup(GroupName))
169       return true;
170 
171     if (expect(AsmToken::EndOfStatement, "eol"))
172       return true;
173 
174     // TODO: Parse UniqueID
175     MCSectionWasm *WS = getContext().getWasmSection(
176         Name, Kind.getValue(), GroupName, MCContext::GenericSectionID);
177     if (Passive) {
178       if (!WS->isWasmData())
179         return Parser->Error(getTok().getLoc(),
180                              "Only data sections can be passive");
181       WS->setPassive();
182     }
183     getStreamer().SwitchSection(WS);
184     return false;
185   }
186 
187   // TODO: This function is almost the same as ELFAsmParser::ParseDirectiveSize
188   // so maybe could be shared somehow.
189   bool parseDirectiveSize(StringRef, SMLoc) {
190     StringRef Name;
191     if (Parser->parseIdentifier(Name))
192       return TokError("expected identifier in directive");
193     auto Sym = getContext().getOrCreateSymbol(Name);
194     if (expect(AsmToken::Comma, ","))
195       return true;
196     const MCExpr *Expr;
197     if (Parser->parseExpression(Expr))
198       return true;
199     if (expect(AsmToken::EndOfStatement, "eol"))
200       return true;
201     // This is done automatically by the assembler for functions currently,
202     // so this is only currently needed for data sections:
203     getStreamer().emitELFSize(Sym, Expr);
204     return false;
205   }
206 
207   bool parseDirectiveType(StringRef, SMLoc) {
208     // This could be the start of a function, check if followed by
209     // "label,@function"
210     if (!Lexer->is(AsmToken::Identifier))
211       return error("Expected label after .type directive, got: ",
212                    Lexer->getTok());
213     auto WasmSym = cast<MCSymbolWasm>(
214                      getStreamer().getContext().getOrCreateSymbol(
215                        Lexer->getTok().getString()));
216     Lex();
217     if (!(isNext(AsmToken::Comma) && isNext(AsmToken::At) &&
218           Lexer->is(AsmToken::Identifier)))
219       return error("Expected label,@type declaration, got: ", Lexer->getTok());
220     auto TypeName = Lexer->getTok().getString();
221     if (TypeName == "function") {
222       WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
223       auto *Current =
224           cast<MCSectionWasm>(getStreamer().getCurrentSection().first);
225       if (Current->getGroup())
226         WasmSym->setComdat(true);
227     } else if (TypeName == "global")
228       WasmSym->setType(wasm::WASM_SYMBOL_TYPE_GLOBAL);
229     else if (TypeName == "object")
230       WasmSym->setType(wasm::WASM_SYMBOL_TYPE_DATA);
231     else
232       return error("Unknown WASM symbol type: ", Lexer->getTok());
233     Lex();
234     return expect(AsmToken::EndOfStatement, "EOL");
235   }
236 
237   // FIXME: Shared with ELF.
238   /// ParseDirectiveIdent
239   ///  ::= .ident string
240   bool ParseDirectiveIdent(StringRef, SMLoc) {
241     if (getLexer().isNot(AsmToken::String))
242       return TokError("unexpected token in '.ident' directive");
243     StringRef Data = getTok().getIdentifier();
244     Lex();
245     if (getLexer().isNot(AsmToken::EndOfStatement))
246       return TokError("unexpected token in '.ident' directive");
247     Lex();
248     getStreamer().emitIdent(Data);
249     return false;
250   }
251 
252   // FIXME: Shared with ELF.
253   /// ParseDirectiveSymbolAttribute
254   ///  ::= { ".local", ".weak", ... } [ identifier ( , identifier )* ]
255   bool ParseDirectiveSymbolAttribute(StringRef Directive, SMLoc) {
256     MCSymbolAttr Attr = StringSwitch<MCSymbolAttr>(Directive)
257       .Case(".weak", MCSA_Weak)
258       .Case(".local", MCSA_Local)
259       .Case(".hidden", MCSA_Hidden)
260       .Case(".internal", MCSA_Internal)
261       .Case(".protected", MCSA_Protected)
262       .Default(MCSA_Invalid);
263     assert(Attr != MCSA_Invalid && "unexpected symbol attribute directive!");
264     if (getLexer().isNot(AsmToken::EndOfStatement)) {
265       while (true) {
266         StringRef Name;
267         if (getParser().parseIdentifier(Name))
268           return TokError("expected identifier in directive");
269         MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
270         getStreamer().emitSymbolAttribute(Sym, Attr);
271         if (getLexer().is(AsmToken::EndOfStatement))
272           break;
273         if (getLexer().isNot(AsmToken::Comma))
274           return TokError("unexpected token in directive");
275         Lex();
276       }
277     }
278     Lex();
279     return false;
280   }
281 };
282 
283 } // end anonymous namespace
284 
285 namespace llvm {
286 
287 MCAsmParserExtension *createWasmAsmParser() {
288   return new WasmAsmParser;
289 }
290 
291 } // end namespace llvm
292