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/ADT/StringExtras.h"
20#include "llvm/BinaryFormat/Wasm.h"
21#include "llvm/MC/MCContext.h"
22#include "llvm/MC/MCObjectFileInfo.h"
23#include "llvm/MC/MCParser/AsmLexer.h"
24#include "llvm/MC/MCParser/MCAsmParser.h"
25#include "llvm/MC/MCParser/MCAsmParserExtension.h"
26#include "llvm/MC/MCSectionWasm.h"
27#include "llvm/MC/MCStreamer.h"
28#include "llvm/MC/MCSymbolWasm.h"
29#include <optional>
30
31using namespace llvm;
32
33namespace {
34
35class WasmAsmParser : public MCAsmParserExtension {
36 MCAsmParser *Parser = nullptr;
37 AsmLexer *Lexer = nullptr;
38
39 template<bool (WasmAsmParser::*HandlerMethod)(StringRef, SMLoc)>
40 void addDirectiveHandler(StringRef Directive) {
41 MCAsmParser::ExtensionDirectiveHandler Handler = std::make_pair(
42 this, HandleDirective<WasmAsmParser, HandlerMethod>);
43
44 getParser().addDirectiveHandler(Directive, Handler);
45 }
46
47public:
48 WasmAsmParser() { BracketExpressionsSupported = true; }
49
50 void Initialize(MCAsmParser &P) override {
51 Parser = &P;
52 Lexer = &Parser->getLexer();
53 // Call the base implementation.
54 this->MCAsmParserExtension::Initialize(Parser&: *Parser);
55
56 addDirectiveHandler<&WasmAsmParser::parseSectionDirectiveText>(Directive: ".text");
57 addDirectiveHandler<&WasmAsmParser::parseSectionDirectiveData>(Directive: ".data");
58 addDirectiveHandler<&WasmAsmParser::parseSectionDirective>(Directive: ".section");
59 addDirectiveHandler<&WasmAsmParser::parseDirectiveSize>(Directive: ".size");
60 addDirectiveHandler<&WasmAsmParser::parseDirectiveType>(Directive: ".type");
61 addDirectiveHandler<&WasmAsmParser::ParseDirectiveIdent>(Directive: ".ident");
62 addDirectiveHandler<
63 &WasmAsmParser::ParseDirectiveSymbolAttribute>(Directive: ".weak");
64 addDirectiveHandler<
65 &WasmAsmParser::ParseDirectiveSymbolAttribute>(Directive: ".local");
66 addDirectiveHandler<
67 &WasmAsmParser::ParseDirectiveSymbolAttribute>(Directive: ".internal");
68 addDirectiveHandler<
69 &WasmAsmParser::ParseDirectiveSymbolAttribute>(Directive: ".hidden");
70 }
71
72 bool error(const StringRef &Msg, const AsmToken &Tok) {
73 return Parser->Error(L: Tok.getLoc(), Msg: Msg + Tok.getString());
74 }
75
76 bool isNext(AsmToken::TokenKind Kind) {
77 auto Ok = Lexer->is(K: Kind);
78 if (Ok)
79 Lex();
80 return Ok;
81 }
82
83 bool expect(AsmToken::TokenKind Kind, const char *KindName) {
84 if (!isNext(Kind))
85 return error(Msg: std::string("Expected ") + KindName + ", instead got: ",
86 Tok: Lexer->getTok());
87 return false;
88 }
89
90 bool parseSectionDirectiveText(StringRef, SMLoc) {
91 // FIXME: .text currently no-op.
92 return false;
93 }
94
95 bool parseSectionDirectiveData(StringRef, SMLoc) {
96 auto *S = getContext().getObjectFileInfo()->getDataSection();
97 getStreamer().switchSection(Section: S);
98 return false;
99 }
100
101 uint32_t parseSectionFlags(StringRef FlagStr, bool &Passive, bool &Group) {
102 uint32_t flags = 0;
103 for (char C : FlagStr) {
104 switch (C) {
105 case 'p':
106 Passive = true;
107 break;
108 case 'G':
109 Group = true;
110 break;
111 case 'T':
112 flags |= wasm::WASM_SEG_FLAG_TLS;
113 break;
114 case 'S':
115 flags |= wasm::WASM_SEG_FLAG_STRINGS;
116 break;
117 case 'R':
118 flags |= wasm::WASM_SEG_FLAG_RETAIN;
119 break;
120 default:
121 return -1U;
122 }
123 }
124 return flags;
125 }
126
127 bool parseGroup(StringRef &GroupName) {
128 if (Lexer->isNot(K: AsmToken::Comma))
129 return TokError(Msg: "expected group name");
130 Lex();
131 if (Lexer->is(K: AsmToken::Integer)) {
132 GroupName = getTok().getString();
133 Lex();
134 } else if (Parser->parseIdentifier(Res&: GroupName)) {
135 return TokError(Msg: "invalid group name");
136 }
137 if (Lexer->is(K: AsmToken::Comma)) {
138 Lex();
139 StringRef Linkage;
140 if (Parser->parseIdentifier(Res&: Linkage))
141 return TokError(Msg: "invalid linkage");
142 if (Linkage != "comdat")
143 return TokError(Msg: "Linkage must be 'comdat'");
144 }
145 return false;
146 }
147
148 bool parseSectionDirective(StringRef, SMLoc loc) {
149 StringRef Name;
150 if (Parser->parseIdentifier(Res&: Name))
151 return TokError(Msg: "expected identifier in directive");
152
153 if (expect(Kind: AsmToken::Comma, KindName: ","))
154 return true;
155
156 if (Lexer->isNot(K: AsmToken::String))
157 return error(Msg: "expected string in directive, instead got: ", Tok: Lexer->getTok());
158
159 auto Kind = StringSwitch<std::optional<SectionKind>>(Name)
160 .StartsWith(S: ".data", Value: SectionKind::getData())
161 .StartsWith(S: ".tdata", Value: SectionKind::getThreadData())
162 .StartsWith(S: ".tbss", Value: SectionKind::getThreadBSS())
163 .StartsWith(S: ".rodata", Value: SectionKind::getReadOnly())
164 .StartsWith(S: ".text", Value: SectionKind::getText())
165 .StartsWith(S: ".custom_section", Value: SectionKind::getMetadata())
166 .StartsWith(S: ".bss", Value: SectionKind::getBSS())
167 // See use of .init_array in WasmObjectWriter and
168 // TargetLoweringObjectFileWasm
169 .StartsWith(S: ".init_array", Value: SectionKind::getData())
170 .StartsWith(S: ".debug_", Value: SectionKind::getMetadata())
171 .Default(Value: SectionKind::getData());
172
173 // Update section flags if present in this .section directive
174 bool Passive = false;
175 bool Group = false;
176 uint32_t Flags =
177 parseSectionFlags(FlagStr: getTok().getStringContents(), Passive, Group);
178 if (Flags == -1U)
179 return TokError(Msg: "unknown flag");
180
181 Lex();
182
183 if (expect(Kind: AsmToken::Comma, KindName: ",") || expect(Kind: AsmToken::At, KindName: "@"))
184 return true;
185
186 StringRef GroupName;
187 if (Group && parseGroup(GroupName))
188 return true;
189
190 if (expect(Kind: AsmToken::EndOfStatement, KindName: "eol"))
191 return true;
192
193 // TODO: Parse UniqueID
194 MCSectionWasm *WS = getContext().getWasmSection(
195 Section: Name, K: *Kind, Flags, Group: GroupName, UniqueID: MCSection::NonUniqueID);
196
197 if (WS->getSegmentFlags() != Flags)
198 Parser->Error(L: loc, Msg: "changed section flags for " + Name +
199 ", expected: 0x" +
200 utohexstr(X: WS->getSegmentFlags()));
201
202 if (Passive) {
203 if (!WS->isWasmData())
204 return Parser->Error(L: loc, Msg: "Only data sections can be passive");
205 WS->setPassive();
206 }
207
208 getStreamer().switchSection(Section: WS);
209 return false;
210 }
211
212 // TODO: This function is almost the same as ELFAsmParser::ParseDirectiveSize
213 // so maybe could be shared somehow.
214 bool parseDirectiveSize(StringRef, SMLoc Loc) {
215 MCSymbol *Sym;
216 if (Parser->parseSymbol(Res&: Sym))
217 return TokError(Msg: "expected identifier in directive");
218 if (expect(Kind: AsmToken::Comma, KindName: ","))
219 return true;
220 const MCExpr *Expr;
221 if (Parser->parseExpression(Res&: Expr))
222 return true;
223 if (expect(Kind: AsmToken::EndOfStatement, KindName: "eol"))
224 return true;
225 auto WasmSym = static_cast<const MCSymbolWasm *>(Sym);
226 if (WasmSym->isFunction()) {
227 // Ignore .size directives for function symbols. They get their size
228 // set automatically based on their content.
229 Warning(L: Loc, Msg: ".size directive ignored for function symbols");
230 } else {
231 getStreamer().emitELFSize(Symbol: Sym, Value: Expr);
232 }
233 return false;
234 }
235
236 bool parseDirectiveType(StringRef, SMLoc) {
237 // This could be the start of a function, check if followed by
238 // "label,@function"
239 if (!Lexer->is(K: AsmToken::Identifier))
240 return error(Msg: "Expected label after .type directive, got: ",
241 Tok: Lexer->getTok());
242 auto *WasmSym = static_cast<MCSymbolWasm *>(
243 getStreamer().getContext().parseSymbol(Name: Lexer->getTok().getString()));
244 Lex();
245 if (!(isNext(Kind: AsmToken::Comma) && isNext(Kind: AsmToken::At) &&
246 Lexer->is(K: AsmToken::Identifier)))
247 return error(Msg: "Expected label,@type declaration, got: ", Tok: Lexer->getTok());
248 auto TypeName = Lexer->getTok().getString();
249 if (TypeName == "function") {
250 WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
251 auto *Current =
252 static_cast<MCSectionWasm *>(getStreamer().getCurrentSectionOnly());
253 if (Current->getGroup())
254 WasmSym->setComdat(true);
255 } else if (TypeName == "global")
256 WasmSym->setType(wasm::WASM_SYMBOL_TYPE_GLOBAL);
257 else if (TypeName == "object")
258 WasmSym->setType(wasm::WASM_SYMBOL_TYPE_DATA);
259 else
260 return error(Msg: "Unknown WASM symbol type: ", Tok: Lexer->getTok());
261 Lex();
262 return expect(Kind: AsmToken::EndOfStatement, KindName: "EOL");
263 }
264
265 // FIXME: Shared with ELF.
266 /// ParseDirectiveIdent
267 /// ::= .ident string
268 bool ParseDirectiveIdent(StringRef, SMLoc) {
269 if (getLexer().isNot(K: AsmToken::String))
270 return TokError(Msg: "unexpected token in '.ident' directive");
271 StringRef Data = getTok().getIdentifier();
272 Lex();
273 if (getLexer().isNot(K: AsmToken::EndOfStatement))
274 return TokError(Msg: "unexpected token in '.ident' directive");
275 Lex();
276 getStreamer().emitIdent(IdentString: Data);
277 return false;
278 }
279
280 // FIXME: Shared with ELF.
281 /// ParseDirectiveSymbolAttribute
282 /// ::= { ".local", ".weak", ... } [ identifier ( , identifier )* ]
283 bool ParseDirectiveSymbolAttribute(StringRef Directive, SMLoc) {
284 MCSymbolAttr Attr = StringSwitch<MCSymbolAttr>(Directive)
285 .Case(S: ".weak", Value: MCSA_Weak)
286 .Case(S: ".local", Value: MCSA_Local)
287 .Case(S: ".hidden", Value: MCSA_Hidden)
288 .Case(S: ".internal", Value: MCSA_Internal)
289 .Case(S: ".protected", Value: MCSA_Protected)
290 .Default(Value: MCSA_Invalid);
291 assert(Attr != MCSA_Invalid && "unexpected symbol attribute directive!");
292 if (getLexer().isNot(K: AsmToken::EndOfStatement)) {
293 while (true) {
294 MCSymbol *Sym;
295 if (getParser().parseSymbol(Res&: Sym))
296 return TokError(Msg: "expected identifier in directive");
297 getStreamer().emitSymbolAttribute(Symbol: Sym, Attribute: Attr);
298 if (getLexer().is(K: AsmToken::EndOfStatement))
299 break;
300 if (getLexer().isNot(K: AsmToken::Comma))
301 return TokError(Msg: "unexpected token in directive");
302 Lex();
303 }
304 }
305 Lex();
306 return false;
307 }
308};
309
310} // end anonymous namespace
311
312MCAsmParserExtension *llvm::createWasmAsmParser() { return new WasmAsmParser; }
313