Fix PR4948 (and a leak): by not destroying the DwarfException
[llvm/avr.git] / tools / llvm-mc / AsmParser.cpp
blobb1e8e9ae404fa64de604157d105141057771f6ba
1 //===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
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 // This class implements the parser for assembly files.
12 //===----------------------------------------------------------------------===//
14 #include "AsmParser.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/MC/MCContext.h"
19 #include "llvm/MC/MCExpr.h"
20 #include "llvm/MC/MCInst.h"
21 #include "llvm/MC/MCSectionMachO.h"
22 #include "llvm/MC/MCStreamer.h"
23 #include "llvm/MC/MCSymbol.h"
24 #include "llvm/Support/SourceMgr.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/Target/TargetAsmParser.h"
27 using namespace llvm;
29 // Mach-O section uniquing.
31 // FIXME: Figure out where this should live, it should be shared by
32 // TargetLoweringObjectFile.
33 typedef StringMap<const MCSectionMachO*> MachOUniqueMapTy;
35 AsmParser::~AsmParser() {
36 // If we have the MachO uniquing map, free it.
37 delete (MachOUniqueMapTy*)SectionUniquingMap;
40 const MCSection *AsmParser::getMachOSection(const StringRef &Segment,
41 const StringRef &Section,
42 unsigned TypeAndAttributes,
43 unsigned Reserved2,
44 SectionKind Kind) const {
45 // We unique sections by their segment/section pair. The returned section
46 // may not have the same flags as the requested section, if so this should be
47 // diagnosed by the client as an error.
49 // Create the map if it doesn't already exist.
50 if (SectionUniquingMap == 0)
51 SectionUniquingMap = new MachOUniqueMapTy();
52 MachOUniqueMapTy &Map = *(MachOUniqueMapTy*)SectionUniquingMap;
54 // Form the name to look up.
55 SmallString<64> Name;
56 Name += Segment;
57 Name.push_back(',');
58 Name += Section;
60 // Do the lookup, if we have a hit, return it.
61 const MCSectionMachO *&Entry = Map[Name.str()];
63 // FIXME: This should validate the type and attributes.
64 if (Entry) return Entry;
66 // Otherwise, return a new section.
67 return Entry = MCSectionMachO::Create(Segment, Section, TypeAndAttributes,
68 Reserved2, Kind, Ctx);
71 void AsmParser::Warning(SMLoc L, const Twine &Msg) {
72 Lexer.PrintMessage(L, Msg.str(), "warning");
75 bool AsmParser::Error(SMLoc L, const Twine &Msg) {
76 Lexer.PrintMessage(L, Msg.str(), "error");
77 return true;
80 bool AsmParser::TokError(const char *Msg) {
81 Lexer.PrintMessage(Lexer.getLoc(), Msg, "error");
82 return true;
85 bool AsmParser::Run() {
86 // Create the initial section.
88 // FIXME: Support -n.
89 // FIXME: Target hook & command line option for initial section.
90 Out.SwitchSection(getMachOSection("__TEXT", "__text",
91 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
92 0, SectionKind()));
95 // Prime the lexer.
96 Lexer.Lex();
98 bool HadError = false;
100 AsmCond StartingCondState = TheCondState;
102 // While we have input, parse each statement.
103 while (Lexer.isNot(AsmToken::Eof)) {
104 // Handle conditional assembly here before calling ParseStatement()
105 if (Lexer.getKind() == AsmToken::Identifier) {
106 // If we have an identifier, handle it as the key symbol.
107 AsmToken ID = Lexer.getTok();
108 SMLoc IDLoc = ID.getLoc();
109 StringRef IDVal = ID.getString();
111 if (IDVal == ".if" ||
112 IDVal == ".elseif" ||
113 IDVal == ".else" ||
114 IDVal == ".endif") {
115 if (!ParseConditionalAssemblyDirectives(IDVal, IDLoc))
116 continue;
117 HadError = true;
118 EatToEndOfStatement();
119 continue;
122 if (TheCondState.Ignore) {
123 EatToEndOfStatement();
124 continue;
127 if (!ParseStatement()) continue;
129 // We had an error, remember it and recover by skipping to the next line.
130 HadError = true;
131 EatToEndOfStatement();
134 if (TheCondState.TheCond != StartingCondState.TheCond ||
135 TheCondState.Ignore != StartingCondState.Ignore)
136 return TokError("unmatched .ifs or .elses");
138 if (!HadError)
139 Out.Finish();
141 return HadError;
144 /// ParseConditionalAssemblyDirectives - parse the conditional assembly
145 /// directives
146 bool AsmParser::ParseConditionalAssemblyDirectives(StringRef Directive,
147 SMLoc DirectiveLoc) {
148 if (Directive == ".if")
149 return ParseDirectiveIf(DirectiveLoc);
150 if (Directive == ".elseif")
151 return ParseDirectiveElseIf(DirectiveLoc);
152 if (Directive == ".else")
153 return ParseDirectiveElse(DirectiveLoc);
154 if (Directive == ".endif")
155 return ParseDirectiveEndIf(DirectiveLoc);
156 return true;
159 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
160 void AsmParser::EatToEndOfStatement() {
161 while (Lexer.isNot(AsmToken::EndOfStatement) &&
162 Lexer.isNot(AsmToken::Eof))
163 Lexer.Lex();
165 // Eat EOL.
166 if (Lexer.is(AsmToken::EndOfStatement))
167 Lexer.Lex();
171 /// ParseParenExpr - Parse a paren expression and return it.
172 /// NOTE: This assumes the leading '(' has already been consumed.
174 /// parenexpr ::= expr)
176 bool AsmParser::ParseParenExpr(const MCExpr *&Res) {
177 if (ParseExpression(Res)) return true;
178 if (Lexer.isNot(AsmToken::RParen))
179 return TokError("expected ')' in parentheses expression");
180 Lexer.Lex();
181 return false;
184 MCSymbol *AsmParser::CreateSymbol(StringRef Name) {
185 if (MCSymbol *S = Ctx.LookupSymbol(Name))
186 return S;
188 // If the label starts with L it is an assembler temporary label.
189 if (Name.startswith("L"))
190 return Ctx.CreateTemporarySymbol(Name);
192 return Ctx.CreateSymbol(Name);
195 /// ParsePrimaryExpr - Parse a primary expression and return it.
196 /// primaryexpr ::= (parenexpr
197 /// primaryexpr ::= symbol
198 /// primaryexpr ::= number
199 /// primaryexpr ::= ~,+,- primaryexpr
200 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res) {
201 switch (Lexer.getKind()) {
202 default:
203 return TokError("unknown token in expression");
204 case AsmToken::Exclaim:
205 Lexer.Lex(); // Eat the operator.
206 if (ParsePrimaryExpr(Res))
207 return true;
208 Res = MCUnaryExpr::CreateLNot(Res, getContext());
209 return false;
210 case AsmToken::String:
211 case AsmToken::Identifier: {
212 // This is a label, this should be parsed as part of an expression, to
213 // handle things like LFOO+4.
214 MCSymbol *Sym = CreateSymbol(Lexer.getTok().getIdentifier());
216 Res = MCSymbolRefExpr::Create(Sym, getContext());
217 Lexer.Lex(); // Eat identifier.
218 return false;
220 case AsmToken::Integer:
221 Res = MCConstantExpr::Create(Lexer.getTok().getIntVal(), getContext());
222 Lexer.Lex(); // Eat token.
223 return false;
224 case AsmToken::LParen:
225 Lexer.Lex(); // Eat the '('.
226 return ParseParenExpr(Res);
227 case AsmToken::Minus:
228 Lexer.Lex(); // Eat the operator.
229 if (ParsePrimaryExpr(Res))
230 return true;
231 Res = MCUnaryExpr::CreateMinus(Res, getContext());
232 return false;
233 case AsmToken::Plus:
234 Lexer.Lex(); // Eat the operator.
235 if (ParsePrimaryExpr(Res))
236 return true;
237 Res = MCUnaryExpr::CreatePlus(Res, getContext());
238 return false;
239 case AsmToken::Tilde:
240 Lexer.Lex(); // Eat the operator.
241 if (ParsePrimaryExpr(Res))
242 return true;
243 Res = MCUnaryExpr::CreateNot(Res, getContext());
244 return false;
248 /// ParseExpression - Parse an expression and return it.
249 ///
250 /// expr ::= expr +,- expr -> lowest.
251 /// expr ::= expr |,^,&,! expr -> middle.
252 /// expr ::= expr *,/,%,<<,>> expr -> highest.
253 /// expr ::= primaryexpr
255 bool AsmParser::ParseExpression(const MCExpr *&Res) {
256 Res = 0;
257 return ParsePrimaryExpr(Res) ||
258 ParseBinOpRHS(1, Res);
261 bool AsmParser::ParseParenExpression(const MCExpr *&Res) {
262 if (ParseParenExpr(Res))
263 return true;
265 return false;
268 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
269 const MCExpr *Expr;
271 SMLoc StartLoc = Lexer.getLoc();
272 if (ParseExpression(Expr))
273 return true;
275 if (!Expr->EvaluateAsAbsolute(Ctx, Res))
276 return Error(StartLoc, "expected absolute expression");
278 return false;
281 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
282 MCBinaryExpr::Opcode &Kind) {
283 switch (K) {
284 default:
285 return 0; // not a binop.
287 // Lowest Precedence: &&, ||
288 case AsmToken::AmpAmp:
289 Kind = MCBinaryExpr::LAnd;
290 return 1;
291 case AsmToken::PipePipe:
292 Kind = MCBinaryExpr::LOr;
293 return 1;
295 // Low Precedence: +, -, ==, !=, <>, <, <=, >, >=
296 case AsmToken::Plus:
297 Kind = MCBinaryExpr::Add;
298 return 2;
299 case AsmToken::Minus:
300 Kind = MCBinaryExpr::Sub;
301 return 2;
302 case AsmToken::EqualEqual:
303 Kind = MCBinaryExpr::EQ;
304 return 2;
305 case AsmToken::ExclaimEqual:
306 case AsmToken::LessGreater:
307 Kind = MCBinaryExpr::NE;
308 return 2;
309 case AsmToken::Less:
310 Kind = MCBinaryExpr::LT;
311 return 2;
312 case AsmToken::LessEqual:
313 Kind = MCBinaryExpr::LTE;
314 return 2;
315 case AsmToken::Greater:
316 Kind = MCBinaryExpr::GT;
317 return 2;
318 case AsmToken::GreaterEqual:
319 Kind = MCBinaryExpr::GTE;
320 return 2;
322 // Intermediate Precedence: |, &, ^
324 // FIXME: gas seems to support '!' as an infix operator?
325 case AsmToken::Pipe:
326 Kind = MCBinaryExpr::Or;
327 return 3;
328 case AsmToken::Caret:
329 Kind = MCBinaryExpr::Xor;
330 return 3;
331 case AsmToken::Amp:
332 Kind = MCBinaryExpr::And;
333 return 3;
335 // Highest Precedence: *, /, %, <<, >>
336 case AsmToken::Star:
337 Kind = MCBinaryExpr::Mul;
338 return 4;
339 case AsmToken::Slash:
340 Kind = MCBinaryExpr::Div;
341 return 4;
342 case AsmToken::Percent:
343 Kind = MCBinaryExpr::Mod;
344 return 4;
345 case AsmToken::LessLess:
346 Kind = MCBinaryExpr::Shl;
347 return 4;
348 case AsmToken::GreaterGreater:
349 Kind = MCBinaryExpr::Shr;
350 return 4;
355 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
356 /// Res contains the LHS of the expression on input.
357 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res) {
358 while (1) {
359 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
360 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
362 // If the next token is lower precedence than we are allowed to eat, return
363 // successfully with what we ate already.
364 if (TokPrec < Precedence)
365 return false;
367 Lexer.Lex();
369 // Eat the next primary expression.
370 const MCExpr *RHS;
371 if (ParsePrimaryExpr(RHS)) return true;
373 // If BinOp binds less tightly with RHS than the operator after RHS, let
374 // the pending operator take RHS as its LHS.
375 MCBinaryExpr::Opcode Dummy;
376 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
377 if (TokPrec < NextTokPrec) {
378 if (ParseBinOpRHS(Precedence+1, RHS)) return true;
381 // Merge LHS and RHS according to operator.
382 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
389 /// ParseStatement:
390 /// ::= EndOfStatement
391 /// ::= Label* Directive ...Operands... EndOfStatement
392 /// ::= Label* Identifier OperandList* EndOfStatement
393 bool AsmParser::ParseStatement() {
394 if (Lexer.is(AsmToken::EndOfStatement)) {
395 Lexer.Lex();
396 return false;
399 // Statements always start with an identifier.
400 AsmToken ID = Lexer.getTok();
401 SMLoc IDLoc = ID.getLoc();
402 StringRef IDVal;
403 if (ParseIdentifier(IDVal))
404 return TokError("unexpected token at start of statement");
406 // FIXME: Recurse on local labels?
408 // See what kind of statement we have.
409 switch (Lexer.getKind()) {
410 case AsmToken::Colon: {
411 // identifier ':' -> Label.
412 Lexer.Lex();
414 // Diagnose attempt to use a variable as a label.
416 // FIXME: Diagnostics. Note the location of the definition as a label.
417 // FIXME: This doesn't diagnose assignment to a symbol which has been
418 // implicitly marked as external.
419 MCSymbol *Sym = CreateSymbol(IDVal);
420 if (!Sym->isUndefined())
421 return Error(IDLoc, "invalid symbol redefinition");
423 // Emit the label.
424 Out.EmitLabel(Sym);
426 return ParseStatement();
429 case AsmToken::Equal:
430 // identifier '=' ... -> assignment statement
431 Lexer.Lex();
433 return ParseAssignment(IDVal);
435 default: // Normal instruction or directive.
436 break;
439 // Otherwise, we have a normal instruction or directive.
440 if (IDVal[0] == '.') {
441 // FIXME: This should be driven based on a hash lookup and callback.
442 if (IDVal == ".section")
443 return ParseDirectiveDarwinSection();
444 if (IDVal == ".text")
445 // FIXME: This changes behavior based on the -static flag to the
446 // assembler.
447 return ParseDirectiveSectionSwitch("__TEXT", "__text",
448 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS);
449 if (IDVal == ".const")
450 return ParseDirectiveSectionSwitch("__TEXT", "__const");
451 if (IDVal == ".static_const")
452 return ParseDirectiveSectionSwitch("__TEXT", "__static_const");
453 if (IDVal == ".cstring")
454 return ParseDirectiveSectionSwitch("__TEXT","__cstring",
455 MCSectionMachO::S_CSTRING_LITERALS);
456 if (IDVal == ".literal4")
457 return ParseDirectiveSectionSwitch("__TEXT", "__literal4",
458 MCSectionMachO::S_4BYTE_LITERALS,
460 if (IDVal == ".literal8")
461 return ParseDirectiveSectionSwitch("__TEXT", "__literal8",
462 MCSectionMachO::S_8BYTE_LITERALS,
464 if (IDVal == ".literal16")
465 return ParseDirectiveSectionSwitch("__TEXT","__literal16",
466 MCSectionMachO::S_16BYTE_LITERALS,
467 16);
468 if (IDVal == ".constructor")
469 return ParseDirectiveSectionSwitch("__TEXT","__constructor");
470 if (IDVal == ".destructor")
471 return ParseDirectiveSectionSwitch("__TEXT","__destructor");
472 if (IDVal == ".fvmlib_init0")
473 return ParseDirectiveSectionSwitch("__TEXT","__fvmlib_init0");
474 if (IDVal == ".fvmlib_init1")
475 return ParseDirectiveSectionSwitch("__TEXT","__fvmlib_init1");
477 // FIXME: The assembler manual claims that this has the self modify code
478 // flag, at least on x86-32, but that does not appear to be correct.
479 if (IDVal == ".symbol_stub")
480 return ParseDirectiveSectionSwitch("__TEXT","__symbol_stub",
481 MCSectionMachO::S_SYMBOL_STUBS |
482 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
483 // FIXME: Different on PPC and ARM.
484 0, 16);
485 // FIXME: PowerPC only?
486 if (IDVal == ".picsymbol_stub")
487 return ParseDirectiveSectionSwitch("__TEXT","__picsymbol_stub",
488 MCSectionMachO::S_SYMBOL_STUBS |
489 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
490 0, 26);
491 if (IDVal == ".data")
492 return ParseDirectiveSectionSwitch("__DATA", "__data");
493 if (IDVal == ".static_data")
494 return ParseDirectiveSectionSwitch("__DATA", "__static_data");
496 // FIXME: The section names of these two are misspelled in the assembler
497 // manual.
498 if (IDVal == ".non_lazy_symbol_pointer")
499 return ParseDirectiveSectionSwitch("__DATA", "__nl_symbol_ptr",
500 MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS,
502 if (IDVal == ".lazy_symbol_pointer")
503 return ParseDirectiveSectionSwitch("__DATA", "__la_symbol_ptr",
504 MCSectionMachO::S_LAZY_SYMBOL_POINTERS,
507 if (IDVal == ".dyld")
508 return ParseDirectiveSectionSwitch("__DATA", "__dyld");
509 if (IDVal == ".mod_init_func")
510 return ParseDirectiveSectionSwitch("__DATA", "__mod_init_func",
511 MCSectionMachO::S_MOD_INIT_FUNC_POINTERS,
513 if (IDVal == ".mod_term_func")
514 return ParseDirectiveSectionSwitch("__DATA", "__mod_term_func",
515 MCSectionMachO::S_MOD_TERM_FUNC_POINTERS,
517 if (IDVal == ".const_data")
518 return ParseDirectiveSectionSwitch("__DATA", "__const");
521 if (IDVal == ".objc_class")
522 return ParseDirectiveSectionSwitch("__OBJC", "__class",
523 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
524 if (IDVal == ".objc_meta_class")
525 return ParseDirectiveSectionSwitch("__OBJC", "__meta_class",
526 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
527 if (IDVal == ".objc_cat_cls_meth")
528 return ParseDirectiveSectionSwitch("__OBJC", "__cat_cls_meth",
529 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
530 if (IDVal == ".objc_cat_inst_meth")
531 return ParseDirectiveSectionSwitch("__OBJC", "__cat_inst_meth",
532 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
533 if (IDVal == ".objc_protocol")
534 return ParseDirectiveSectionSwitch("__OBJC", "__protocol",
535 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
536 if (IDVal == ".objc_string_object")
537 return ParseDirectiveSectionSwitch("__OBJC", "__string_object",
538 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
539 if (IDVal == ".objc_cls_meth")
540 return ParseDirectiveSectionSwitch("__OBJC", "__cls_meth",
541 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
542 if (IDVal == ".objc_inst_meth")
543 return ParseDirectiveSectionSwitch("__OBJC", "__inst_meth",
544 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
545 if (IDVal == ".objc_cls_refs")
546 return ParseDirectiveSectionSwitch("__OBJC", "__cls_refs",
547 MCSectionMachO::S_ATTR_NO_DEAD_STRIP |
548 MCSectionMachO::S_LITERAL_POINTERS,
550 if (IDVal == ".objc_message_refs")
551 return ParseDirectiveSectionSwitch("__OBJC", "__message_refs",
552 MCSectionMachO::S_ATTR_NO_DEAD_STRIP |
553 MCSectionMachO::S_LITERAL_POINTERS,
555 if (IDVal == ".objc_symbols")
556 return ParseDirectiveSectionSwitch("__OBJC", "__symbols",
557 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
558 if (IDVal == ".objc_category")
559 return ParseDirectiveSectionSwitch("__OBJC", "__category",
560 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
561 if (IDVal == ".objc_class_vars")
562 return ParseDirectiveSectionSwitch("__OBJC", "__class_vars",
563 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
564 if (IDVal == ".objc_instance_vars")
565 return ParseDirectiveSectionSwitch("__OBJC", "__instance_vars",
566 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
567 if (IDVal == ".objc_module_info")
568 return ParseDirectiveSectionSwitch("__OBJC", "__module_info",
569 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
570 if (IDVal == ".objc_class_names")
571 return ParseDirectiveSectionSwitch("__TEXT", "__cstring",
572 MCSectionMachO::S_CSTRING_LITERALS);
573 if (IDVal == ".objc_meth_var_types")
574 return ParseDirectiveSectionSwitch("__TEXT", "__cstring",
575 MCSectionMachO::S_CSTRING_LITERALS);
576 if (IDVal == ".objc_meth_var_names")
577 return ParseDirectiveSectionSwitch("__TEXT", "__cstring",
578 MCSectionMachO::S_CSTRING_LITERALS);
579 if (IDVal == ".objc_selector_strs")
580 return ParseDirectiveSectionSwitch("__OBJC", "__selector_strs",
581 MCSectionMachO::S_CSTRING_LITERALS);
583 // Assembler features
584 if (IDVal == ".set")
585 return ParseDirectiveSet();
587 // Data directives
589 if (IDVal == ".ascii")
590 return ParseDirectiveAscii(false);
591 if (IDVal == ".asciz")
592 return ParseDirectiveAscii(true);
594 if (IDVal == ".byte")
595 return ParseDirectiveValue(1);
596 if (IDVal == ".short")
597 return ParseDirectiveValue(2);
598 if (IDVal == ".long")
599 return ParseDirectiveValue(4);
600 if (IDVal == ".quad")
601 return ParseDirectiveValue(8);
603 // FIXME: Target hooks for IsPow2.
604 if (IDVal == ".align")
605 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
606 if (IDVal == ".align32")
607 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
608 if (IDVal == ".balign")
609 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
610 if (IDVal == ".balignw")
611 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
612 if (IDVal == ".balignl")
613 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
614 if (IDVal == ".p2align")
615 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
616 if (IDVal == ".p2alignw")
617 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
618 if (IDVal == ".p2alignl")
619 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
621 if (IDVal == ".org")
622 return ParseDirectiveOrg();
624 if (IDVal == ".fill")
625 return ParseDirectiveFill();
626 if (IDVal == ".space")
627 return ParseDirectiveSpace();
629 // Symbol attribute directives
631 if (IDVal == ".globl" || IDVal == ".global")
632 return ParseDirectiveSymbolAttribute(MCStreamer::Global);
633 if (IDVal == ".hidden")
634 return ParseDirectiveSymbolAttribute(MCStreamer::Hidden);
635 if (IDVal == ".indirect_symbol")
636 return ParseDirectiveSymbolAttribute(MCStreamer::IndirectSymbol);
637 if (IDVal == ".internal")
638 return ParseDirectiveSymbolAttribute(MCStreamer::Internal);
639 if (IDVal == ".lazy_reference")
640 return ParseDirectiveSymbolAttribute(MCStreamer::LazyReference);
641 if (IDVal == ".no_dead_strip")
642 return ParseDirectiveSymbolAttribute(MCStreamer::NoDeadStrip);
643 if (IDVal == ".private_extern")
644 return ParseDirectiveSymbolAttribute(MCStreamer::PrivateExtern);
645 if (IDVal == ".protected")
646 return ParseDirectiveSymbolAttribute(MCStreamer::Protected);
647 if (IDVal == ".reference")
648 return ParseDirectiveSymbolAttribute(MCStreamer::Reference);
649 if (IDVal == ".weak")
650 return ParseDirectiveSymbolAttribute(MCStreamer::Weak);
651 if (IDVal == ".weak_definition")
652 return ParseDirectiveSymbolAttribute(MCStreamer::WeakDefinition);
653 if (IDVal == ".weak_reference")
654 return ParseDirectiveSymbolAttribute(MCStreamer::WeakReference);
656 if (IDVal == ".comm")
657 return ParseDirectiveComm(/*IsLocal=*/false);
658 if (IDVal == ".lcomm")
659 return ParseDirectiveComm(/*IsLocal=*/true);
660 if (IDVal == ".zerofill")
661 return ParseDirectiveDarwinZerofill();
662 if (IDVal == ".desc")
663 return ParseDirectiveDarwinSymbolDesc();
664 if (IDVal == ".lsym")
665 return ParseDirectiveDarwinLsym();
667 if (IDVal == ".subsections_via_symbols")
668 return ParseDirectiveDarwinSubsectionsViaSymbols();
669 if (IDVal == ".abort")
670 return ParseDirectiveAbort();
671 if (IDVal == ".include")
672 return ParseDirectiveInclude();
673 if (IDVal == ".dump")
674 return ParseDirectiveDarwinDumpOrLoad(IDLoc, /*IsDump=*/true);
675 if (IDVal == ".load")
676 return ParseDirectiveDarwinDumpOrLoad(IDLoc, /*IsLoad=*/false);
678 // Debugging directives
680 if (IDVal == ".file")
681 return ParseDirectiveFile(IDLoc);
682 if (IDVal == ".line")
683 return ParseDirectiveLine(IDLoc);
684 if (IDVal == ".loc")
685 return ParseDirectiveLoc(IDLoc);
687 // Target hook for parsing target specific directives.
688 if (!getTargetParser().ParseDirective(ID))
689 return false;
691 Warning(IDLoc, "ignoring directive for now");
692 EatToEndOfStatement();
693 return false;
696 MCInst Inst;
697 if (getTargetParser().ParseInstruction(IDVal, Inst))
698 return true;
700 if (Lexer.isNot(AsmToken::EndOfStatement))
701 return TokError("unexpected token in argument list");
703 // Eat the end of statement marker.
704 Lexer.Lex();
706 // Instruction is good, process it.
707 Out.EmitInstruction(Inst);
709 // Skip to end of line for now.
710 return false;
713 bool AsmParser::ParseAssignment(const StringRef &Name) {
714 // FIXME: Use better location, we should use proper tokens.
715 SMLoc EqualLoc = Lexer.getLoc();
717 const MCExpr *Value;
718 SMLoc StartLoc = Lexer.getLoc();
719 if (ParseExpression(Value))
720 return true;
722 if (Lexer.isNot(AsmToken::EndOfStatement))
723 return TokError("unexpected token in assignment");
725 // Eat the end of statement marker.
726 Lexer.Lex();
728 // Diagnose assignment to a label.
730 // FIXME: Diagnostics. Note the location of the definition as a label.
731 // FIXME: Handle '.'.
732 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
733 MCSymbol *Sym = CreateSymbol(Name);
734 if (!Sym->isUndefined() && !Sym->isAbsolute())
735 return Error(EqualLoc, "symbol has already been defined");
737 // Do the assignment.
738 Out.EmitAssignment(Sym, Value);
740 return false;
743 /// ParseIdentifier:
744 /// ::= identifier
745 /// ::= string
746 bool AsmParser::ParseIdentifier(StringRef &Res) {
747 if (Lexer.isNot(AsmToken::Identifier) &&
748 Lexer.isNot(AsmToken::String))
749 return true;
751 Res = Lexer.getTok().getIdentifier();
753 Lexer.Lex(); // Consume the identifier token.
755 return false;
758 /// ParseDirectiveSet:
759 /// ::= .set identifier ',' expression
760 bool AsmParser::ParseDirectiveSet() {
761 StringRef Name;
763 if (ParseIdentifier(Name))
764 return TokError("expected identifier after '.set' directive");
766 if (Lexer.isNot(AsmToken::Comma))
767 return TokError("unexpected token in '.set'");
768 Lexer.Lex();
770 return ParseAssignment(Name);
773 /// ParseDirectiveSection:
774 /// ::= .section identifier (',' identifier)*
775 /// FIXME: This should actually parse out the segment, section, attributes and
776 /// sizeof_stub fields.
777 bool AsmParser::ParseDirectiveDarwinSection() {
778 SMLoc Loc = Lexer.getLoc();
780 StringRef SectionName;
781 if (ParseIdentifier(SectionName))
782 return Error(Loc, "expected identifier after '.section' directive");
784 // Verify there is a following comma.
785 if (!Lexer.is(AsmToken::Comma))
786 return TokError("unexpected token in '.section' directive");
788 std::string SectionSpec = SectionName;
789 SectionSpec += ",";
791 // Add all the tokens until the end of the line, ParseSectionSpecifier will
792 // handle this.
793 StringRef EOL = Lexer.LexUntilEndOfStatement();
794 SectionSpec.append(EOL.begin(), EOL.end());
796 Lexer.Lex();
797 if (Lexer.isNot(AsmToken::EndOfStatement))
798 return TokError("unexpected token in '.section' directive");
799 Lexer.Lex();
802 StringRef Segment, Section;
803 unsigned TAA, StubSize;
804 std::string ErrorStr =
805 MCSectionMachO::ParseSectionSpecifier(SectionSpec, Segment, Section,
806 TAA, StubSize);
808 if (!ErrorStr.empty())
809 return Error(Loc, ErrorStr.c_str());
811 // FIXME: Arch specific.
812 Out.SwitchSection(getMachOSection(Segment, Section, TAA, StubSize,
813 SectionKind()));
814 return false;
817 /// ParseDirectiveSectionSwitch -
818 bool AsmParser::ParseDirectiveSectionSwitch(const char *Segment,
819 const char *Section,
820 unsigned TAA, unsigned Align,
821 unsigned StubSize) {
822 if (Lexer.isNot(AsmToken::EndOfStatement))
823 return TokError("unexpected token in section switching directive");
824 Lexer.Lex();
826 // FIXME: Arch specific.
827 Out.SwitchSection(getMachOSection(Segment, Section, TAA, StubSize,
828 SectionKind()));
830 // Set the implicit alignment, if any.
832 // FIXME: This isn't really what 'as' does; I think it just uses the implicit
833 // alignment on the section (e.g., if one manually inserts bytes into the
834 // section, then just issueing the section switch directive will not realign
835 // the section. However, this is arguably more reasonable behavior, and there
836 // is no good reason for someone to intentionally emit incorrectly sized
837 // values into the implicitly aligned sections.
838 if (Align)
839 Out.EmitValueToAlignment(Align, 0, 1, 0);
841 return false;
844 bool AsmParser::ParseEscapedString(std::string &Data) {
845 assert(Lexer.is(AsmToken::String) && "Unexpected current token!");
847 Data = "";
848 StringRef Str = Lexer.getTok().getStringContents();
849 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
850 if (Str[i] != '\\') {
851 Data += Str[i];
852 continue;
855 // Recognize escaped characters. Note that this escape semantics currently
856 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
857 ++i;
858 if (i == e)
859 return TokError("unexpected backslash at end of string");
861 // Recognize octal sequences.
862 if ((unsigned) (Str[i] - '0') <= 7) {
863 // Consume up to three octal characters.
864 unsigned Value = Str[i] - '0';
866 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
867 ++i;
868 Value = Value * 8 + (Str[i] - '0');
870 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
871 ++i;
872 Value = Value * 8 + (Str[i] - '0');
876 if (Value > 255)
877 return TokError("invalid octal escape sequence (out of range)");
879 Data += (unsigned char) Value;
880 continue;
883 // Otherwise recognize individual escapes.
884 switch (Str[i]) {
885 default:
886 // Just reject invalid escape sequences for now.
887 return TokError("invalid escape sequence (unrecognized character)");
889 case 'b': Data += '\b'; break;
890 case 'f': Data += '\f'; break;
891 case 'n': Data += '\n'; break;
892 case 'r': Data += '\r'; break;
893 case 't': Data += '\t'; break;
894 case '"': Data += '"'; break;
895 case '\\': Data += '\\'; break;
899 return false;
902 /// ParseDirectiveAscii:
903 /// ::= ( .ascii | .asciz ) [ "string" ( , "string" )* ]
904 bool AsmParser::ParseDirectiveAscii(bool ZeroTerminated) {
905 if (Lexer.isNot(AsmToken::EndOfStatement)) {
906 for (;;) {
907 if (Lexer.isNot(AsmToken::String))
908 return TokError("expected string in '.ascii' or '.asciz' directive");
910 std::string Data;
911 if (ParseEscapedString(Data))
912 return true;
914 Out.EmitBytes(Data);
915 if (ZeroTerminated)
916 Out.EmitBytes(StringRef("\0", 1));
918 Lexer.Lex();
920 if (Lexer.is(AsmToken::EndOfStatement))
921 break;
923 if (Lexer.isNot(AsmToken::Comma))
924 return TokError("unexpected token in '.ascii' or '.asciz' directive");
925 Lexer.Lex();
929 Lexer.Lex();
930 return false;
933 /// ParseDirectiveValue
934 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
935 bool AsmParser::ParseDirectiveValue(unsigned Size) {
936 if (Lexer.isNot(AsmToken::EndOfStatement)) {
937 for (;;) {
938 const MCExpr *Value;
939 SMLoc StartLoc = Lexer.getLoc();
940 if (ParseExpression(Value))
941 return true;
943 Out.EmitValue(Value, Size);
945 if (Lexer.is(AsmToken::EndOfStatement))
946 break;
948 // FIXME: Improve diagnostic.
949 if (Lexer.isNot(AsmToken::Comma))
950 return TokError("unexpected token in directive");
951 Lexer.Lex();
955 Lexer.Lex();
956 return false;
959 /// ParseDirectiveSpace
960 /// ::= .space expression [ , expression ]
961 bool AsmParser::ParseDirectiveSpace() {
962 int64_t NumBytes;
963 if (ParseAbsoluteExpression(NumBytes))
964 return true;
966 int64_t FillExpr = 0;
967 bool HasFillExpr = false;
968 if (Lexer.isNot(AsmToken::EndOfStatement)) {
969 if (Lexer.isNot(AsmToken::Comma))
970 return TokError("unexpected token in '.space' directive");
971 Lexer.Lex();
973 if (ParseAbsoluteExpression(FillExpr))
974 return true;
976 HasFillExpr = true;
978 if (Lexer.isNot(AsmToken::EndOfStatement))
979 return TokError("unexpected token in '.space' directive");
982 Lexer.Lex();
984 if (NumBytes <= 0)
985 return TokError("invalid number of bytes in '.space' directive");
987 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
988 for (uint64_t i = 0, e = NumBytes; i != e; ++i)
989 Out.EmitValue(MCConstantExpr::Create(FillExpr, getContext()), 1);
991 return false;
994 /// ParseDirectiveFill
995 /// ::= .fill expression , expression , expression
996 bool AsmParser::ParseDirectiveFill() {
997 int64_t NumValues;
998 if (ParseAbsoluteExpression(NumValues))
999 return true;
1001 if (Lexer.isNot(AsmToken::Comma))
1002 return TokError("unexpected token in '.fill' directive");
1003 Lexer.Lex();
1005 int64_t FillSize;
1006 if (ParseAbsoluteExpression(FillSize))
1007 return true;
1009 if (Lexer.isNot(AsmToken::Comma))
1010 return TokError("unexpected token in '.fill' directive");
1011 Lexer.Lex();
1013 int64_t FillExpr;
1014 if (ParseAbsoluteExpression(FillExpr))
1015 return true;
1017 if (Lexer.isNot(AsmToken::EndOfStatement))
1018 return TokError("unexpected token in '.fill' directive");
1020 Lexer.Lex();
1022 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1023 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1025 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1026 Out.EmitValue(MCConstantExpr::Create(FillExpr, getContext()), FillSize);
1028 return false;
1031 /// ParseDirectiveOrg
1032 /// ::= .org expression [ , expression ]
1033 bool AsmParser::ParseDirectiveOrg() {
1034 const MCExpr *Offset;
1035 SMLoc StartLoc = Lexer.getLoc();
1036 if (ParseExpression(Offset))
1037 return true;
1039 // Parse optional fill expression.
1040 int64_t FillExpr = 0;
1041 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1042 if (Lexer.isNot(AsmToken::Comma))
1043 return TokError("unexpected token in '.org' directive");
1044 Lexer.Lex();
1046 if (ParseAbsoluteExpression(FillExpr))
1047 return true;
1049 if (Lexer.isNot(AsmToken::EndOfStatement))
1050 return TokError("unexpected token in '.org' directive");
1053 Lexer.Lex();
1055 // FIXME: Only limited forms of relocatable expressions are accepted here, it
1056 // has to be relative to the current section.
1057 Out.EmitValueToOffset(Offset, FillExpr);
1059 return false;
1062 /// ParseDirectiveAlign
1063 /// ::= {.align, ...} expression [ , expression [ , expression ]]
1064 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1065 SMLoc AlignmentLoc = Lexer.getLoc();
1066 int64_t Alignment;
1067 if (ParseAbsoluteExpression(Alignment))
1068 return true;
1070 SMLoc MaxBytesLoc;
1071 bool HasFillExpr = false;
1072 int64_t FillExpr = 0;
1073 int64_t MaxBytesToFill = 0;
1074 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1075 if (Lexer.isNot(AsmToken::Comma))
1076 return TokError("unexpected token in directive");
1077 Lexer.Lex();
1079 // The fill expression can be omitted while specifying a maximum number of
1080 // alignment bytes, e.g:
1081 // .align 3,,4
1082 if (Lexer.isNot(AsmToken::Comma)) {
1083 HasFillExpr = true;
1084 if (ParseAbsoluteExpression(FillExpr))
1085 return true;
1088 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1089 if (Lexer.isNot(AsmToken::Comma))
1090 return TokError("unexpected token in directive");
1091 Lexer.Lex();
1093 MaxBytesLoc = Lexer.getLoc();
1094 if (ParseAbsoluteExpression(MaxBytesToFill))
1095 return true;
1097 if (Lexer.isNot(AsmToken::EndOfStatement))
1098 return TokError("unexpected token in directive");
1102 Lexer.Lex();
1104 if (!HasFillExpr) {
1105 // FIXME: Sometimes fill with nop.
1106 FillExpr = 0;
1109 // Compute alignment in bytes.
1110 if (IsPow2) {
1111 // FIXME: Diagnose overflow.
1112 if (Alignment >= 32) {
1113 Error(AlignmentLoc, "invalid alignment value");
1114 Alignment = 31;
1117 Alignment = 1ULL << Alignment;
1120 // Diagnose non-sensical max bytes to align.
1121 if (MaxBytesLoc.isValid()) {
1122 if (MaxBytesToFill < 1) {
1123 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
1124 "many bytes, ignoring maximum bytes expression");
1125 MaxBytesToFill = 0;
1128 if (MaxBytesToFill >= Alignment) {
1129 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
1130 "has no effect");
1131 MaxBytesToFill = 0;
1135 // FIXME: Target specific behavior about how the "extra" bytes are filled.
1136 Out.EmitValueToAlignment(Alignment, FillExpr, ValueSize, MaxBytesToFill);
1138 return false;
1141 /// ParseDirectiveSymbolAttribute
1142 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
1143 bool AsmParser::ParseDirectiveSymbolAttribute(MCStreamer::SymbolAttr Attr) {
1144 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1145 for (;;) {
1146 StringRef Name;
1148 if (ParseIdentifier(Name))
1149 return TokError("expected identifier in directive");
1151 MCSymbol *Sym = CreateSymbol(Name);
1153 Out.EmitSymbolAttribute(Sym, Attr);
1155 if (Lexer.is(AsmToken::EndOfStatement))
1156 break;
1158 if (Lexer.isNot(AsmToken::Comma))
1159 return TokError("unexpected token in directive");
1160 Lexer.Lex();
1164 Lexer.Lex();
1165 return false;
1168 /// ParseDirectiveDarwinSymbolDesc
1169 /// ::= .desc identifier , expression
1170 bool AsmParser::ParseDirectiveDarwinSymbolDesc() {
1171 StringRef Name;
1172 if (ParseIdentifier(Name))
1173 return TokError("expected identifier in directive");
1175 // Handle the identifier as the key symbol.
1176 MCSymbol *Sym = CreateSymbol(Name);
1178 if (Lexer.isNot(AsmToken::Comma))
1179 return TokError("unexpected token in '.desc' directive");
1180 Lexer.Lex();
1182 SMLoc DescLoc = Lexer.getLoc();
1183 int64_t DescValue;
1184 if (ParseAbsoluteExpression(DescValue))
1185 return true;
1187 if (Lexer.isNot(AsmToken::EndOfStatement))
1188 return TokError("unexpected token in '.desc' directive");
1190 Lexer.Lex();
1192 // Set the n_desc field of this Symbol to this DescValue
1193 Out.EmitSymbolDesc(Sym, DescValue);
1195 return false;
1198 /// ParseDirectiveComm
1199 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
1200 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
1201 SMLoc IDLoc = Lexer.getLoc();
1202 StringRef Name;
1203 if (ParseIdentifier(Name))
1204 return TokError("expected identifier in directive");
1206 // Handle the identifier as the key symbol.
1207 MCSymbol *Sym = CreateSymbol(Name);
1209 if (Lexer.isNot(AsmToken::Comma))
1210 return TokError("unexpected token in directive");
1211 Lexer.Lex();
1213 int64_t Size;
1214 SMLoc SizeLoc = Lexer.getLoc();
1215 if (ParseAbsoluteExpression(Size))
1216 return true;
1218 int64_t Pow2Alignment = 0;
1219 SMLoc Pow2AlignmentLoc;
1220 if (Lexer.is(AsmToken::Comma)) {
1221 Lexer.Lex();
1222 Pow2AlignmentLoc = Lexer.getLoc();
1223 if (ParseAbsoluteExpression(Pow2Alignment))
1224 return true;
1227 if (Lexer.isNot(AsmToken::EndOfStatement))
1228 return TokError("unexpected token in '.comm' or '.lcomm' directive");
1230 Lexer.Lex();
1232 // NOTE: a size of zero for a .comm should create a undefined symbol
1233 // but a size of .lcomm creates a bss symbol of size zero.
1234 if (Size < 0)
1235 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
1236 "be less than zero");
1238 // NOTE: The alignment in the directive is a power of 2 value, the assember
1239 // may internally end up wanting an alignment in bytes.
1240 // FIXME: Diagnose overflow.
1241 if (Pow2Alignment < 0)
1242 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
1243 "alignment, can't be less than zero");
1245 if (!Sym->isUndefined())
1246 return Error(IDLoc, "invalid symbol redefinition");
1248 // '.lcomm' is equivalent to '.zerofill'.
1249 // Create the Symbol as a common or local common with Size and Pow2Alignment
1250 if (IsLocal) {
1251 Out.EmitZerofill(getMachOSection("__DATA", "__bss",
1252 MCSectionMachO::S_ZEROFILL, 0,
1253 SectionKind()),
1254 Sym, Size, 1 << Pow2Alignment);
1255 return false;
1258 Out.EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
1259 return false;
1262 /// ParseDirectiveDarwinZerofill
1263 /// ::= .zerofill segname , sectname [, identifier , size_expression [
1264 /// , align_expression ]]
1265 bool AsmParser::ParseDirectiveDarwinZerofill() {
1266 // FIXME: Handle quoted names here.
1268 if (Lexer.isNot(AsmToken::Identifier))
1269 return TokError("expected segment name after '.zerofill' directive");
1270 StringRef Segment = Lexer.getTok().getString();
1271 Lexer.Lex();
1273 if (Lexer.isNot(AsmToken::Comma))
1274 return TokError("unexpected token in directive");
1275 Lexer.Lex();
1277 if (Lexer.isNot(AsmToken::Identifier))
1278 return TokError("expected section name after comma in '.zerofill' "
1279 "directive");
1280 StringRef Section = Lexer.getTok().getString();
1281 Lexer.Lex();
1283 // If this is the end of the line all that was wanted was to create the
1284 // the section but with no symbol.
1285 if (Lexer.is(AsmToken::EndOfStatement)) {
1286 // Create the zerofill section but no symbol
1287 Out.EmitZerofill(getMachOSection(Segment, Section,
1288 MCSectionMachO::S_ZEROFILL, 0,
1289 SectionKind()));
1290 return false;
1293 if (Lexer.isNot(AsmToken::Comma))
1294 return TokError("unexpected token in directive");
1295 Lexer.Lex();
1297 if (Lexer.isNot(AsmToken::Identifier))
1298 return TokError("expected identifier in directive");
1300 // handle the identifier as the key symbol.
1301 SMLoc IDLoc = Lexer.getLoc();
1302 MCSymbol *Sym = CreateSymbol(Lexer.getTok().getString());
1303 Lexer.Lex();
1305 if (Lexer.isNot(AsmToken::Comma))
1306 return TokError("unexpected token in directive");
1307 Lexer.Lex();
1309 int64_t Size;
1310 SMLoc SizeLoc = Lexer.getLoc();
1311 if (ParseAbsoluteExpression(Size))
1312 return true;
1314 int64_t Pow2Alignment = 0;
1315 SMLoc Pow2AlignmentLoc;
1316 if (Lexer.is(AsmToken::Comma)) {
1317 Lexer.Lex();
1318 Pow2AlignmentLoc = Lexer.getLoc();
1319 if (ParseAbsoluteExpression(Pow2Alignment))
1320 return true;
1323 if (Lexer.isNot(AsmToken::EndOfStatement))
1324 return TokError("unexpected token in '.zerofill' directive");
1326 Lexer.Lex();
1328 if (Size < 0)
1329 return Error(SizeLoc, "invalid '.zerofill' directive size, can't be less "
1330 "than zero");
1332 // NOTE: The alignment in the directive is a power of 2 value, the assember
1333 // may internally end up wanting an alignment in bytes.
1334 // FIXME: Diagnose overflow.
1335 if (Pow2Alignment < 0)
1336 return Error(Pow2AlignmentLoc, "invalid '.zerofill' directive alignment, "
1337 "can't be less than zero");
1339 if (!Sym->isUndefined())
1340 return Error(IDLoc, "invalid symbol redefinition");
1342 // Create the zerofill Symbol with Size and Pow2Alignment
1344 // FIXME: Arch specific.
1345 Out.EmitZerofill(getMachOSection(Segment, Section,
1346 MCSectionMachO::S_ZEROFILL, 0,
1347 SectionKind()),
1348 Sym, Size, 1 << Pow2Alignment);
1350 return false;
1353 /// ParseDirectiveDarwinSubsectionsViaSymbols
1354 /// ::= .subsections_via_symbols
1355 bool AsmParser::ParseDirectiveDarwinSubsectionsViaSymbols() {
1356 if (Lexer.isNot(AsmToken::EndOfStatement))
1357 return TokError("unexpected token in '.subsections_via_symbols' directive");
1359 Lexer.Lex();
1361 Out.EmitAssemblerFlag(MCStreamer::SubsectionsViaSymbols);
1363 return false;
1366 /// ParseDirectiveAbort
1367 /// ::= .abort [ "abort_string" ]
1368 bool AsmParser::ParseDirectiveAbort() {
1369 // FIXME: Use loc from directive.
1370 SMLoc Loc = Lexer.getLoc();
1372 StringRef Str = "";
1373 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1374 if (Lexer.isNot(AsmToken::String))
1375 return TokError("expected string in '.abort' directive");
1377 Str = Lexer.getTok().getString();
1379 Lexer.Lex();
1382 if (Lexer.isNot(AsmToken::EndOfStatement))
1383 return TokError("unexpected token in '.abort' directive");
1385 Lexer.Lex();
1387 // FIXME: Handle here.
1388 if (Str.empty())
1389 Error(Loc, ".abort detected. Assembly stopping.");
1390 else
1391 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
1393 return false;
1396 /// ParseDirectiveLsym
1397 /// ::= .lsym identifier , expression
1398 bool AsmParser::ParseDirectiveDarwinLsym() {
1399 StringRef Name;
1400 if (ParseIdentifier(Name))
1401 return TokError("expected identifier in directive");
1403 // Handle the identifier as the key symbol.
1404 MCSymbol *Sym = CreateSymbol(Name);
1406 if (Lexer.isNot(AsmToken::Comma))
1407 return TokError("unexpected token in '.lsym' directive");
1408 Lexer.Lex();
1410 const MCExpr *Value;
1411 SMLoc StartLoc = Lexer.getLoc();
1412 if (ParseExpression(Value))
1413 return true;
1415 if (Lexer.isNot(AsmToken::EndOfStatement))
1416 return TokError("unexpected token in '.lsym' directive");
1418 Lexer.Lex();
1420 // We don't currently support this directive.
1422 // FIXME: Diagnostic location!
1423 (void) Sym;
1424 return TokError("directive '.lsym' is unsupported");
1427 /// ParseDirectiveInclude
1428 /// ::= .include "filename"
1429 bool AsmParser::ParseDirectiveInclude() {
1430 if (Lexer.isNot(AsmToken::String))
1431 return TokError("expected string in '.include' directive");
1433 std::string Filename = Lexer.getTok().getString();
1434 SMLoc IncludeLoc = Lexer.getLoc();
1435 Lexer.Lex();
1437 if (Lexer.isNot(AsmToken::EndOfStatement))
1438 return TokError("unexpected token in '.include' directive");
1440 // Strip the quotes.
1441 Filename = Filename.substr(1, Filename.size()-2);
1443 // Attempt to switch the lexer to the included file before consuming the end
1444 // of statement to avoid losing it when we switch.
1445 if (Lexer.EnterIncludeFile(Filename)) {
1446 Lexer.PrintMessage(IncludeLoc,
1447 "Could not find include file '" + Filename + "'",
1448 "error");
1449 return true;
1452 return false;
1455 /// ParseDirectiveDarwinDumpOrLoad
1456 /// ::= ( .dump | .load ) "filename"
1457 bool AsmParser::ParseDirectiveDarwinDumpOrLoad(SMLoc IDLoc, bool IsDump) {
1458 if (Lexer.isNot(AsmToken::String))
1459 return TokError("expected string in '.dump' or '.load' directive");
1461 Lexer.Lex();
1463 if (Lexer.isNot(AsmToken::EndOfStatement))
1464 return TokError("unexpected token in '.dump' or '.load' directive");
1466 Lexer.Lex();
1468 // FIXME: If/when .dump and .load are implemented they will be done in the
1469 // the assembly parser and not have any need for an MCStreamer API.
1470 if (IsDump)
1471 Warning(IDLoc, "ignoring directive .dump for now");
1472 else
1473 Warning(IDLoc, "ignoring directive .load for now");
1475 return false;
1478 /// ParseDirectiveIf
1479 /// ::= .if expression
1480 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
1481 // Consume the identifier that was the .if directive
1482 Lexer.Lex();
1484 TheCondStack.push_back(TheCondState);
1485 TheCondState.TheCond = AsmCond::IfCond;
1486 if(TheCondState.Ignore) {
1487 EatToEndOfStatement();
1489 else {
1490 int64_t ExprValue;
1491 if (ParseAbsoluteExpression(ExprValue))
1492 return true;
1494 if (Lexer.isNot(AsmToken::EndOfStatement))
1495 return TokError("unexpected token in '.if' directive");
1497 Lexer.Lex();
1499 TheCondState.CondMet = ExprValue;
1500 TheCondState.Ignore = !TheCondState.CondMet;
1503 return false;
1506 /// ParseDirectiveElseIf
1507 /// ::= .elseif expression
1508 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
1509 if (TheCondState.TheCond != AsmCond::IfCond &&
1510 TheCondState.TheCond != AsmCond::ElseIfCond)
1511 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
1512 " an .elseif");
1513 TheCondState.TheCond = AsmCond::ElseIfCond;
1515 // Consume the identifier that was the .elseif directive
1516 Lexer.Lex();
1518 bool LastIgnoreState = false;
1519 if (!TheCondStack.empty())
1520 LastIgnoreState = TheCondStack.back().Ignore;
1521 if (LastIgnoreState || TheCondState.CondMet) {
1522 TheCondState.Ignore = true;
1523 EatToEndOfStatement();
1525 else {
1526 int64_t ExprValue;
1527 if (ParseAbsoluteExpression(ExprValue))
1528 return true;
1530 if (Lexer.isNot(AsmToken::EndOfStatement))
1531 return TokError("unexpected token in '.elseif' directive");
1533 Lexer.Lex();
1534 TheCondState.CondMet = ExprValue;
1535 TheCondState.Ignore = !TheCondState.CondMet;
1538 return false;
1541 /// ParseDirectiveElse
1542 /// ::= .else
1543 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
1544 // Consume the identifier that was the .else directive
1545 Lexer.Lex();
1547 if (Lexer.isNot(AsmToken::EndOfStatement))
1548 return TokError("unexpected token in '.else' directive");
1550 Lexer.Lex();
1552 if (TheCondState.TheCond != AsmCond::IfCond &&
1553 TheCondState.TheCond != AsmCond::ElseIfCond)
1554 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
1555 ".elseif");
1556 TheCondState.TheCond = AsmCond::ElseCond;
1557 bool LastIgnoreState = false;
1558 if (!TheCondStack.empty())
1559 LastIgnoreState = TheCondStack.back().Ignore;
1560 if (LastIgnoreState || TheCondState.CondMet)
1561 TheCondState.Ignore = true;
1562 else
1563 TheCondState.Ignore = false;
1565 return false;
1568 /// ParseDirectiveEndIf
1569 /// ::= .endif
1570 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
1571 // Consume the identifier that was the .endif directive
1572 Lexer.Lex();
1574 if (Lexer.isNot(AsmToken::EndOfStatement))
1575 return TokError("unexpected token in '.endif' directive");
1577 Lexer.Lex();
1579 if ((TheCondState.TheCond == AsmCond::NoCond) ||
1580 TheCondStack.empty())
1581 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
1582 ".else");
1583 if (!TheCondStack.empty()) {
1584 TheCondState = TheCondStack.back();
1585 TheCondStack.pop_back();
1588 return false;
1591 /// ParseDirectiveFile
1592 /// ::= .file [number] string
1593 bool AsmParser::ParseDirectiveFile(SMLoc DirectiveLoc) {
1594 // FIXME: I'm not sure what this is.
1595 int64_t FileNumber = -1;
1596 if (Lexer.is(AsmToken::Integer)) {
1597 FileNumber = Lexer.getTok().getIntVal();
1598 Lexer.Lex();
1600 if (FileNumber < 1)
1601 return TokError("file number less than one");
1604 if (Lexer.isNot(AsmToken::String))
1605 return TokError("unexpected token in '.file' directive");
1607 StringRef FileName = Lexer.getTok().getString();
1608 Lexer.Lex();
1610 if (Lexer.isNot(AsmToken::EndOfStatement))
1611 return TokError("unexpected token in '.file' directive");
1613 // FIXME: Do something with the .file.
1615 return false;
1618 /// ParseDirectiveLine
1619 /// ::= .line [number]
1620 bool AsmParser::ParseDirectiveLine(SMLoc DirectiveLoc) {
1621 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1622 if (Lexer.isNot(AsmToken::Integer))
1623 return TokError("unexpected token in '.line' directive");
1625 int64_t LineNumber = Lexer.getTok().getIntVal();
1626 (void) LineNumber;
1627 Lexer.Lex();
1629 // FIXME: Do something with the .line.
1632 if (Lexer.isNot(AsmToken::EndOfStatement))
1633 return TokError("unexpected token in '.file' directive");
1635 return false;
1639 /// ParseDirectiveLoc
1640 /// ::= .loc number [number [number]]
1641 bool AsmParser::ParseDirectiveLoc(SMLoc DirectiveLoc) {
1642 if (Lexer.isNot(AsmToken::Integer))
1643 return TokError("unexpected token in '.loc' directive");
1645 // FIXME: What are these fields?
1646 int64_t FileNumber = Lexer.getTok().getIntVal();
1647 (void) FileNumber;
1648 // FIXME: Validate file.
1650 Lexer.Lex();
1651 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1652 if (Lexer.isNot(AsmToken::Integer))
1653 return TokError("unexpected token in '.loc' directive");
1655 int64_t Param2 = Lexer.getTok().getIntVal();
1656 (void) Param2;
1657 Lexer.Lex();
1659 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1660 if (Lexer.isNot(AsmToken::Integer))
1661 return TokError("unexpected token in '.loc' directive");
1663 int64_t Param3 = Lexer.getTok().getIntVal();
1664 (void) Param3;
1665 Lexer.Lex();
1667 // FIXME: Do something with the .loc.
1671 if (Lexer.isNot(AsmToken::EndOfStatement))
1672 return TokError("unexpected token in '.file' directive");
1674 return false;