1 //===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This class implements the parser for assembly files.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/MC/MCParser/AsmParser.h"
15 #include "llvm/ADT/SmallString.h"
16 #include "llvm/ADT/Twine.h"
17 #include "llvm/MC/MCContext.h"
18 #include "llvm/MC/MCExpr.h"
19 #include "llvm/MC/MCInst.h"
20 #include "llvm/MC/MCSectionMachO.h"
21 #include "llvm/MC/MCStreamer.h"
22 #include "llvm/MC/MCSymbol.h"
23 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
24 #include "llvm/Support/Compiler.h"
25 #include "llvm/Support/SourceMgr.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/Target/TargetAsmParser.h"
31 enum { DEFAULT_ADDRSPACE = 0 };
33 // Mach-O section uniquing.
35 // FIXME: Figure out where this should live, it should be shared by
36 // TargetLoweringObjectFile.
37 typedef StringMap<const MCSectionMachO*> MachOUniqueMapTy;
39 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx, MCStreamer &_Out,
40 const MCAsmInfo &_MAI)
41 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), SrcMgr(_SM), TargetParser(0),
42 CurBuffer(0), SectionUniquingMap(0) {
43 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
45 // Debugging directives.
46 AddDirectiveHandler(".file", &AsmParser::ParseDirectiveFile);
47 AddDirectiveHandler(".line", &AsmParser::ParseDirectiveLine);
48 AddDirectiveHandler(".loc", &AsmParser::ParseDirectiveLoc);
53 AsmParser::~AsmParser() {
54 // If we have the MachO uniquing map, free it.
55 delete (MachOUniqueMapTy*)SectionUniquingMap;
58 const MCSection *AsmParser::getMachOSection(const StringRef &Segment,
59 const StringRef &Section,
60 unsigned TypeAndAttributes,
62 SectionKind Kind) const {
63 // We unique sections by their segment/section pair. The returned section
64 // may not have the same flags as the requested section, if so this should be
65 // diagnosed by the client as an error.
67 // Create the map if it doesn't already exist.
68 if (SectionUniquingMap == 0)
69 SectionUniquingMap = new MachOUniqueMapTy();
70 MachOUniqueMapTy &Map = *(MachOUniqueMapTy*)SectionUniquingMap;
72 // Form the name to look up.
78 // Do the lookup, if we have a hit, return it.
79 const MCSectionMachO *&Entry = Map[Name.str()];
81 // FIXME: This should validate the type and attributes.
82 if (Entry) return Entry;
84 // Otherwise, return a new section.
85 return Entry = MCSectionMachO::Create(Segment, Section, TypeAndAttributes,
86 Reserved2, Kind, Ctx);
89 void AsmParser::Warning(SMLoc L, const Twine &Msg) {
90 PrintMessage(L, Msg.str(), "warning");
93 bool AsmParser::Error(SMLoc L, const Twine &Msg) {
94 PrintMessage(L, Msg.str(), "error");
98 bool AsmParser::TokError(const char *Msg) {
99 PrintMessage(Lexer.getLoc(), Msg, "error");
103 void AsmParser::PrintMessage(SMLoc Loc, const std::string &Msg,
104 const char *Type) const {
105 SrcMgr.PrintMessage(Loc, Msg, Type);
108 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
109 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc());
115 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
120 const AsmToken &AsmParser::Lex() {
121 const AsmToken *tok = &Lexer.Lex();
123 if (tok->is(AsmToken::Eof)) {
124 // If this is the end of an included file, pop the parent file off the
126 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
127 if (ParentIncludeLoc != SMLoc()) {
128 CurBuffer = SrcMgr.FindBufferContainingLoc(ParentIncludeLoc);
129 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer),
130 ParentIncludeLoc.getPointer());
135 if (tok->is(AsmToken::Error))
136 PrintMessage(Lexer.getErrLoc(), Lexer.getErr(), "error");
141 bool AsmParser::Run(bool NoInitialTextSection) {
142 // Create the initial section, if requested.
144 // FIXME: Target hook & command line option for initial section.
145 if (!NoInitialTextSection)
146 Out.SwitchSection(getMachOSection("__TEXT", "__text",
147 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
148 0, SectionKind::getText()));
153 bool HadError = false;
155 AsmCond StartingCondState = TheCondState;
157 // While we have input, parse each statement.
158 while (Lexer.isNot(AsmToken::Eof)) {
159 // Handle conditional assembly here before calling ParseStatement()
160 if (Lexer.getKind() == AsmToken::Identifier) {
161 // If we have an identifier, handle it as the key symbol.
162 AsmToken ID = getTok();
163 SMLoc IDLoc = ID.getLoc();
164 StringRef IDVal = ID.getString();
166 if (IDVal == ".if" ||
167 IDVal == ".elseif" ||
170 if (!ParseConditionalAssemblyDirectives(IDVal, IDLoc))
173 EatToEndOfStatement();
177 if (TheCondState.Ignore) {
178 EatToEndOfStatement();
182 if (!ParseStatement()) continue;
184 // We had an error, remember it and recover by skipping to the next line.
186 EatToEndOfStatement();
189 if (TheCondState.TheCond != StartingCondState.TheCond ||
190 TheCondState.Ignore != StartingCondState.Ignore)
191 return TokError("unmatched .ifs or .elses");
199 /// ParseConditionalAssemblyDirectives - parse the conditional assembly
201 bool AsmParser::ParseConditionalAssemblyDirectives(StringRef Directive,
202 SMLoc DirectiveLoc) {
203 if (Directive == ".if")
204 return ParseDirectiveIf(DirectiveLoc);
205 if (Directive == ".elseif")
206 return ParseDirectiveElseIf(DirectiveLoc);
207 if (Directive == ".else")
208 return ParseDirectiveElse(DirectiveLoc);
209 if (Directive == ".endif")
210 return ParseDirectiveEndIf(DirectiveLoc);
214 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
215 void AsmParser::EatToEndOfStatement() {
216 while (Lexer.isNot(AsmToken::EndOfStatement) &&
217 Lexer.isNot(AsmToken::Eof))
221 if (Lexer.is(AsmToken::EndOfStatement))
226 /// ParseParenExpr - Parse a paren expression and return it.
227 /// NOTE: This assumes the leading '(' has already been consumed.
229 /// parenexpr ::= expr)
231 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
232 if (ParseExpression(Res)) return true;
233 if (Lexer.isNot(AsmToken::RParen))
234 return TokError("expected ')' in parentheses expression");
235 EndLoc = Lexer.getLoc();
240 MCSymbol *AsmParser::CreateSymbol(StringRef Name) {
241 // FIXME: Inline into callers.
242 return Ctx.GetOrCreateSymbol(Name);
245 /// ParsePrimaryExpr - Parse a primary expression and return it.
246 /// primaryexpr ::= (parenexpr
247 /// primaryexpr ::= symbol
248 /// primaryexpr ::= number
249 /// primaryexpr ::= ~,+,- primaryexpr
250 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
251 switch (Lexer.getKind()) {
253 return TokError("unknown token in expression");
254 case AsmToken::Exclaim:
255 Lex(); // Eat the operator.
256 if (ParsePrimaryExpr(Res, EndLoc))
258 Res = MCUnaryExpr::CreateLNot(Res, getContext());
260 case AsmToken::String:
261 case AsmToken::Identifier: {
262 // This is a symbol reference.
263 std::pair<StringRef, StringRef> Split = getTok().getIdentifier().split('@');
264 MCSymbol *Sym = CreateSymbol(Split.first);
266 // Lookup the symbol variant if used.
267 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
268 if (Split.first.size() != getTok().getIdentifier().size())
269 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
271 EndLoc = Lexer.getLoc();
272 Lex(); // Eat identifier.
274 // If this is an absolute variable reference, substitute it now to preserve
275 // semantics in the face of reassignment.
276 if (Sym->getValue() && isa<MCConstantExpr>(Sym->getValue())) {
278 return Error(EndLoc, "unexpected modified on variable reference");
280 Res = Sym->getValue();
284 // Otherwise create a symbol ref.
285 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
288 case AsmToken::Integer:
289 Res = MCConstantExpr::Create(getTok().getIntVal(), getContext());
290 EndLoc = Lexer.getLoc();
293 case AsmToken::LParen:
294 Lex(); // Eat the '('.
295 return ParseParenExpr(Res, EndLoc);
296 case AsmToken::Minus:
297 Lex(); // Eat the operator.
298 if (ParsePrimaryExpr(Res, EndLoc))
300 Res = MCUnaryExpr::CreateMinus(Res, getContext());
303 Lex(); // Eat the operator.
304 if (ParsePrimaryExpr(Res, EndLoc))
306 Res = MCUnaryExpr::CreatePlus(Res, getContext());
308 case AsmToken::Tilde:
309 Lex(); // Eat the operator.
310 if (ParsePrimaryExpr(Res, EndLoc))
312 Res = MCUnaryExpr::CreateNot(Res, getContext());
317 bool AsmParser::ParseExpression(const MCExpr *&Res) {
319 return ParseExpression(Res, EndLoc);
322 /// ParseExpression - Parse an expression and return it.
324 /// expr ::= expr +,- expr -> lowest.
325 /// expr ::= expr |,^,&,! expr -> middle.
326 /// expr ::= expr *,/,%,<<,>> expr -> highest.
327 /// expr ::= primaryexpr
329 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
330 // Parse the expression.
332 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
335 // Try to constant fold it up front, if possible.
337 if (Res->EvaluateAsAbsolute(Value))
338 Res = MCConstantExpr::Create(Value, getContext());
343 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
345 return ParseParenExpr(Res, EndLoc) ||
346 ParseBinOpRHS(1, Res, EndLoc);
349 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
352 SMLoc StartLoc = Lexer.getLoc();
353 if (ParseExpression(Expr))
356 if (!Expr->EvaluateAsAbsolute(Res))
357 return Error(StartLoc, "expected absolute expression");
362 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
363 MCBinaryExpr::Opcode &Kind) {
366 return 0; // not a binop.
368 // Lowest Precedence: &&, ||
369 case AsmToken::AmpAmp:
370 Kind = MCBinaryExpr::LAnd;
372 case AsmToken::PipePipe:
373 Kind = MCBinaryExpr::LOr;
376 // Low Precedence: +, -, ==, !=, <>, <, <=, >, >=
378 Kind = MCBinaryExpr::Add;
380 case AsmToken::Minus:
381 Kind = MCBinaryExpr::Sub;
383 case AsmToken::EqualEqual:
384 Kind = MCBinaryExpr::EQ;
386 case AsmToken::ExclaimEqual:
387 case AsmToken::LessGreater:
388 Kind = MCBinaryExpr::NE;
391 Kind = MCBinaryExpr::LT;
393 case AsmToken::LessEqual:
394 Kind = MCBinaryExpr::LTE;
396 case AsmToken::Greater:
397 Kind = MCBinaryExpr::GT;
399 case AsmToken::GreaterEqual:
400 Kind = MCBinaryExpr::GTE;
403 // Intermediate Precedence: |, &, ^
405 // FIXME: gas seems to support '!' as an infix operator?
407 Kind = MCBinaryExpr::Or;
409 case AsmToken::Caret:
410 Kind = MCBinaryExpr::Xor;
413 Kind = MCBinaryExpr::And;
416 // Highest Precedence: *, /, %, <<, >>
418 Kind = MCBinaryExpr::Mul;
420 case AsmToken::Slash:
421 Kind = MCBinaryExpr::Div;
423 case AsmToken::Percent:
424 Kind = MCBinaryExpr::Mod;
426 case AsmToken::LessLess:
427 Kind = MCBinaryExpr::Shl;
429 case AsmToken::GreaterGreater:
430 Kind = MCBinaryExpr::Shr;
436 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
437 /// Res contains the LHS of the expression on input.
438 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
441 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
442 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
444 // If the next token is lower precedence than we are allowed to eat, return
445 // successfully with what we ate already.
446 if (TokPrec < Precedence)
451 // Eat the next primary expression.
453 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
455 // If BinOp binds less tightly with RHS than the operator after RHS, let
456 // the pending operator take RHS as its LHS.
457 MCBinaryExpr::Opcode Dummy;
458 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
459 if (TokPrec < NextTokPrec) {
460 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
463 // Merge LHS and RHS according to operator.
464 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
472 /// ::= EndOfStatement
473 /// ::= Label* Directive ...Operands... EndOfStatement
474 /// ::= Label* Identifier OperandList* EndOfStatement
475 bool AsmParser::ParseStatement() {
476 if (Lexer.is(AsmToken::EndOfStatement)) {
481 // Statements always start with an identifier.
482 AsmToken ID = getTok();
483 SMLoc IDLoc = ID.getLoc();
485 if (ParseIdentifier(IDVal))
486 return TokError("unexpected token at start of statement");
488 // FIXME: Recurse on local labels?
490 // See what kind of statement we have.
491 switch (Lexer.getKind()) {
492 case AsmToken::Colon: {
493 // identifier ':' -> Label.
496 // Diagnose attempt to use a variable as a label.
498 // FIXME: Diagnostics. Note the location of the definition as a label.
499 // FIXME: This doesn't diagnose assignment to a symbol which has been
500 // implicitly marked as external.
501 MCSymbol *Sym = CreateSymbol(IDVal);
502 if (!Sym->isUndefined())
503 return Error(IDLoc, "invalid symbol redefinition");
508 return ParseStatement();
511 case AsmToken::Equal:
512 // identifier '=' ... -> assignment statement
515 return ParseAssignment(IDVal);
517 default: // Normal instruction or directive.
521 // Otherwise, we have a normal instruction or directive.
522 if (IDVal[0] == '.') {
523 // FIXME: This should be driven based on a hash lookup and callback.
524 if (IDVal == ".section")
525 return ParseDirectiveDarwinSection();
526 if (IDVal == ".text")
527 // FIXME: This changes behavior based on the -static flag to the
529 return ParseDirectiveSectionSwitch("__TEXT", "__text",
530 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS);
531 if (IDVal == ".const")
532 return ParseDirectiveSectionSwitch("__TEXT", "__const");
533 if (IDVal == ".static_const")
534 return ParseDirectiveSectionSwitch("__TEXT", "__static_const");
535 if (IDVal == ".cstring")
536 return ParseDirectiveSectionSwitch("__TEXT","__cstring",
537 MCSectionMachO::S_CSTRING_LITERALS);
538 if (IDVal == ".literal4")
539 return ParseDirectiveSectionSwitch("__TEXT", "__literal4",
540 MCSectionMachO::S_4BYTE_LITERALS,
542 if (IDVal == ".literal8")
543 return ParseDirectiveSectionSwitch("__TEXT", "__literal8",
544 MCSectionMachO::S_8BYTE_LITERALS,
546 if (IDVal == ".literal16")
547 return ParseDirectiveSectionSwitch("__TEXT","__literal16",
548 MCSectionMachO::S_16BYTE_LITERALS,
550 if (IDVal == ".constructor")
551 return ParseDirectiveSectionSwitch("__TEXT","__constructor");
552 if (IDVal == ".destructor")
553 return ParseDirectiveSectionSwitch("__TEXT","__destructor");
554 if (IDVal == ".fvmlib_init0")
555 return ParseDirectiveSectionSwitch("__TEXT","__fvmlib_init0");
556 if (IDVal == ".fvmlib_init1")
557 return ParseDirectiveSectionSwitch("__TEXT","__fvmlib_init1");
559 // FIXME: The assembler manual claims that this has the self modify code
560 // flag, at least on x86-32, but that does not appear to be correct.
561 if (IDVal == ".symbol_stub")
562 return ParseDirectiveSectionSwitch("__TEXT","__symbol_stub",
563 MCSectionMachO::S_SYMBOL_STUBS |
564 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
565 // FIXME: Different on PPC and ARM.
567 // FIXME: PowerPC only?
568 if (IDVal == ".picsymbol_stub")
569 return ParseDirectiveSectionSwitch("__TEXT","__picsymbol_stub",
570 MCSectionMachO::S_SYMBOL_STUBS |
571 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
573 if (IDVal == ".data")
574 return ParseDirectiveSectionSwitch("__DATA", "__data");
575 if (IDVal == ".static_data")
576 return ParseDirectiveSectionSwitch("__DATA", "__static_data");
578 // FIXME: The section names of these two are misspelled in the assembler
580 if (IDVal == ".non_lazy_symbol_pointer")
581 return ParseDirectiveSectionSwitch("__DATA", "__nl_symbol_ptr",
582 MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS,
584 if (IDVal == ".lazy_symbol_pointer")
585 return ParseDirectiveSectionSwitch("__DATA", "__la_symbol_ptr",
586 MCSectionMachO::S_LAZY_SYMBOL_POINTERS,
589 if (IDVal == ".dyld")
590 return ParseDirectiveSectionSwitch("__DATA", "__dyld");
591 if (IDVal == ".mod_init_func")
592 return ParseDirectiveSectionSwitch("__DATA", "__mod_init_func",
593 MCSectionMachO::S_MOD_INIT_FUNC_POINTERS,
595 if (IDVal == ".mod_term_func")
596 return ParseDirectiveSectionSwitch("__DATA", "__mod_term_func",
597 MCSectionMachO::S_MOD_TERM_FUNC_POINTERS,
599 if (IDVal == ".const_data")
600 return ParseDirectiveSectionSwitch("__DATA", "__const");
603 if (IDVal == ".objc_class")
604 return ParseDirectiveSectionSwitch("__OBJC", "__class",
605 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
606 if (IDVal == ".objc_meta_class")
607 return ParseDirectiveSectionSwitch("__OBJC", "__meta_class",
608 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
609 if (IDVal == ".objc_cat_cls_meth")
610 return ParseDirectiveSectionSwitch("__OBJC", "__cat_cls_meth",
611 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
612 if (IDVal == ".objc_cat_inst_meth")
613 return ParseDirectiveSectionSwitch("__OBJC", "__cat_inst_meth",
614 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
615 if (IDVal == ".objc_protocol")
616 return ParseDirectiveSectionSwitch("__OBJC", "__protocol",
617 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
618 if (IDVal == ".objc_string_object")
619 return ParseDirectiveSectionSwitch("__OBJC", "__string_object",
620 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
621 if (IDVal == ".objc_cls_meth")
622 return ParseDirectiveSectionSwitch("__OBJC", "__cls_meth",
623 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
624 if (IDVal == ".objc_inst_meth")
625 return ParseDirectiveSectionSwitch("__OBJC", "__inst_meth",
626 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
627 if (IDVal == ".objc_cls_refs")
628 return ParseDirectiveSectionSwitch("__OBJC", "__cls_refs",
629 MCSectionMachO::S_ATTR_NO_DEAD_STRIP |
630 MCSectionMachO::S_LITERAL_POINTERS,
632 if (IDVal == ".objc_message_refs")
633 return ParseDirectiveSectionSwitch("__OBJC", "__message_refs",
634 MCSectionMachO::S_ATTR_NO_DEAD_STRIP |
635 MCSectionMachO::S_LITERAL_POINTERS,
637 if (IDVal == ".objc_symbols")
638 return ParseDirectiveSectionSwitch("__OBJC", "__symbols",
639 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
640 if (IDVal == ".objc_category")
641 return ParseDirectiveSectionSwitch("__OBJC", "__category",
642 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
643 if (IDVal == ".objc_class_vars")
644 return ParseDirectiveSectionSwitch("__OBJC", "__class_vars",
645 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
646 if (IDVal == ".objc_instance_vars")
647 return ParseDirectiveSectionSwitch("__OBJC", "__instance_vars",
648 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
649 if (IDVal == ".objc_module_info")
650 return ParseDirectiveSectionSwitch("__OBJC", "__module_info",
651 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
652 if (IDVal == ".objc_class_names")
653 return ParseDirectiveSectionSwitch("__TEXT", "__cstring",
654 MCSectionMachO::S_CSTRING_LITERALS);
655 if (IDVal == ".objc_meth_var_types")
656 return ParseDirectiveSectionSwitch("__TEXT", "__cstring",
657 MCSectionMachO::S_CSTRING_LITERALS);
658 if (IDVal == ".objc_meth_var_names")
659 return ParseDirectiveSectionSwitch("__TEXT", "__cstring",
660 MCSectionMachO::S_CSTRING_LITERALS);
661 if (IDVal == ".objc_selector_strs")
662 return ParseDirectiveSectionSwitch("__OBJC", "__selector_strs",
663 MCSectionMachO::S_CSTRING_LITERALS);
665 // Assembler features
667 return ParseDirectiveSet();
671 if (IDVal == ".ascii")
672 return ParseDirectiveAscii(false);
673 if (IDVal == ".asciz")
674 return ParseDirectiveAscii(true);
676 if (IDVal == ".byte")
677 return ParseDirectiveValue(1);
678 if (IDVal == ".short")
679 return ParseDirectiveValue(2);
680 if (IDVal == ".long")
681 return ParseDirectiveValue(4);
682 if (IDVal == ".quad")
683 return ParseDirectiveValue(8);
685 // FIXME: Target hooks for IsPow2.
686 if (IDVal == ".align")
687 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
688 if (IDVal == ".align32")
689 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
690 if (IDVal == ".balign")
691 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
692 if (IDVal == ".balignw")
693 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
694 if (IDVal == ".balignl")
695 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
696 if (IDVal == ".p2align")
697 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
698 if (IDVal == ".p2alignw")
699 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
700 if (IDVal == ".p2alignl")
701 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
704 return ParseDirectiveOrg();
706 if (IDVal == ".fill")
707 return ParseDirectiveFill();
708 if (IDVal == ".space")
709 return ParseDirectiveSpace();
711 // Symbol attribute directives
713 if (IDVal == ".globl" || IDVal == ".global")
714 return ParseDirectiveSymbolAttribute(MCSA_Global);
715 if (IDVal == ".hidden")
716 return ParseDirectiveSymbolAttribute(MCSA_Hidden);
717 if (IDVal == ".indirect_symbol")
718 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
719 if (IDVal == ".internal")
720 return ParseDirectiveSymbolAttribute(MCSA_Internal);
721 if (IDVal == ".lazy_reference")
722 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
723 if (IDVal == ".no_dead_strip")
724 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
725 if (IDVal == ".private_extern")
726 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
727 if (IDVal == ".protected")
728 return ParseDirectiveSymbolAttribute(MCSA_Protected);
729 if (IDVal == ".reference")
730 return ParseDirectiveSymbolAttribute(MCSA_Reference);
731 if (IDVal == ".weak")
732 return ParseDirectiveSymbolAttribute(MCSA_Weak);
733 if (IDVal == ".weak_definition")
734 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
735 if (IDVal == ".weak_reference")
736 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
738 if (IDVal == ".comm")
739 return ParseDirectiveComm(/*IsLocal=*/false);
740 if (IDVal == ".lcomm")
741 return ParseDirectiveComm(/*IsLocal=*/true);
742 if (IDVal == ".zerofill")
743 return ParseDirectiveDarwinZerofill();
744 if (IDVal == ".desc")
745 return ParseDirectiveDarwinSymbolDesc();
746 if (IDVal == ".lsym")
747 return ParseDirectiveDarwinLsym();
749 if (IDVal == ".subsections_via_symbols")
750 return ParseDirectiveDarwinSubsectionsViaSymbols();
751 if (IDVal == ".abort")
752 return ParseDirectiveAbort();
753 if (IDVal == ".include")
754 return ParseDirectiveInclude();
755 if (IDVal == ".dump")
756 return ParseDirectiveDarwinDumpOrLoad(IDLoc, /*IsDump=*/true);
757 if (IDVal == ".load")
758 return ParseDirectiveDarwinDumpOrLoad(IDLoc, /*IsLoad=*/false);
760 // Look up the handler in the handler table,
761 bool(AsmParser::*Handler)(StringRef, SMLoc) = DirectiveMap[IDVal];
763 return (this->*Handler)(IDVal, IDLoc);
765 // Target hook for parsing target specific directives.
766 if (!getTargetParser().ParseDirective(ID))
769 Warning(IDLoc, "ignoring directive for now");
770 EatToEndOfStatement();
775 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
776 if (getTargetParser().ParseInstruction(IDVal, IDLoc, ParsedOperands))
777 // FIXME: Leaking ParsedOperands on failure.
780 if (Lexer.isNot(AsmToken::EndOfStatement))
781 // FIXME: Leaking ParsedOperands on failure.
782 return TokError("unexpected token in argument list");
784 // Eat the end of statement marker.
790 bool MatchFail = getTargetParser().MatchInstruction(ParsedOperands, Inst);
792 // Free any parsed operands.
793 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
794 delete ParsedOperands[i];
797 // FIXME: We should give nicer diagnostics about the exact failure.
798 Error(IDLoc, "unrecognized instruction");
802 // Instruction is good, process it.
803 Out.EmitInstruction(Inst);
805 // Skip to end of line for now.
809 bool AsmParser::ParseAssignment(const StringRef &Name) {
810 // FIXME: Use better location, we should use proper tokens.
811 SMLoc EqualLoc = Lexer.getLoc();
814 SMLoc StartLoc = Lexer.getLoc();
815 if (ParseExpression(Value))
818 if (Lexer.isNot(AsmToken::EndOfStatement))
819 return TokError("unexpected token in assignment");
821 // Eat the end of statement marker.
824 // Validate that the LHS is allowed to be a variable (either it has not been
825 // used as a symbol, or it is an absolute symbol).
826 MCSymbol *Sym = getContext().LookupSymbol(Name);
828 // Diagnose assignment to a label.
830 // FIXME: Diagnostics. Note the location of the definition as a label.
831 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
832 if (!Sym->isUndefined() && !Sym->isAbsolute())
833 return Error(EqualLoc, "redefinition of '" + Name + "'");
834 else if (!Sym->isVariable())
835 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
836 else if (!isa<MCConstantExpr>(Sym->getValue()))
837 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
840 Sym = CreateSymbol(Name);
842 // FIXME: Handle '.'.
844 // Do the assignment.
845 Out.EmitAssignment(Sym, Value);
853 bool AsmParser::ParseIdentifier(StringRef &Res) {
854 if (Lexer.isNot(AsmToken::Identifier) &&
855 Lexer.isNot(AsmToken::String))
858 Res = getTok().getIdentifier();
860 Lex(); // Consume the identifier token.
865 /// ParseDirectiveSet:
866 /// ::= .set identifier ',' expression
867 bool AsmParser::ParseDirectiveSet() {
870 if (ParseIdentifier(Name))
871 return TokError("expected identifier after '.set' directive");
873 if (Lexer.isNot(AsmToken::Comma))
874 return TokError("unexpected token in '.set'");
877 return ParseAssignment(Name);
880 /// ParseDirectiveSection:
881 /// ::= .section identifier (',' identifier)*
882 /// FIXME: This should actually parse out the segment, section, attributes and
883 /// sizeof_stub fields.
884 bool AsmParser::ParseDirectiveDarwinSection() {
885 SMLoc Loc = Lexer.getLoc();
887 StringRef SectionName;
888 if (ParseIdentifier(SectionName))
889 return Error(Loc, "expected identifier after '.section' directive");
891 // Verify there is a following comma.
892 if (!Lexer.is(AsmToken::Comma))
893 return TokError("unexpected token in '.section' directive");
895 std::string SectionSpec = SectionName;
898 // Add all the tokens until the end of the line, ParseSectionSpecifier will
900 StringRef EOL = Lexer.LexUntilEndOfStatement();
901 SectionSpec.append(EOL.begin(), EOL.end());
904 if (Lexer.isNot(AsmToken::EndOfStatement))
905 return TokError("unexpected token in '.section' directive");
909 StringRef Segment, Section;
910 unsigned TAA, StubSize;
911 std::string ErrorStr =
912 MCSectionMachO::ParseSectionSpecifier(SectionSpec, Segment, Section,
915 if (!ErrorStr.empty())
916 return Error(Loc, ErrorStr.c_str());
918 // FIXME: Arch specific.
919 bool isText = Segment == "__TEXT"; // FIXME: Hack.
920 Out.SwitchSection(getMachOSection(Segment, Section, TAA, StubSize,
921 isText ? SectionKind::getText()
922 : SectionKind::getDataRel()));
926 /// ParseDirectiveSectionSwitch -
927 bool AsmParser::ParseDirectiveSectionSwitch(const char *Segment,
929 unsigned TAA, unsigned Align,
931 if (Lexer.isNot(AsmToken::EndOfStatement))
932 return TokError("unexpected token in section switching directive");
935 // FIXME: Arch specific.
936 bool isText = StringRef(Segment) == "__TEXT"; // FIXME: Hack.
937 Out.SwitchSection(getMachOSection(Segment, Section, TAA, StubSize,
938 isText ? SectionKind::getText()
939 : SectionKind::getDataRel()));
941 // Set the implicit alignment, if any.
943 // FIXME: This isn't really what 'as' does; I think it just uses the implicit
944 // alignment on the section (e.g., if one manually inserts bytes into the
945 // section, then just issueing the section switch directive will not realign
946 // the section. However, this is arguably more reasonable behavior, and there
947 // is no good reason for someone to intentionally emit incorrectly sized
948 // values into the implicitly aligned sections.
950 Out.EmitValueToAlignment(Align, 0, 1, 0);
955 bool AsmParser::ParseEscapedString(std::string &Data) {
956 assert(Lexer.is(AsmToken::String) && "Unexpected current token!");
959 StringRef Str = getTok().getStringContents();
960 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
961 if (Str[i] != '\\') {
966 // Recognize escaped characters. Note that this escape semantics currently
967 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
970 return TokError("unexpected backslash at end of string");
972 // Recognize octal sequences.
973 if ((unsigned) (Str[i] - '0') <= 7) {
974 // Consume up to three octal characters.
975 unsigned Value = Str[i] - '0';
977 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
979 Value = Value * 8 + (Str[i] - '0');
981 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
983 Value = Value * 8 + (Str[i] - '0');
988 return TokError("invalid octal escape sequence (out of range)");
990 Data += (unsigned char) Value;
994 // Otherwise recognize individual escapes.
997 // Just reject invalid escape sequences for now.
998 return TokError("invalid escape sequence (unrecognized character)");
1000 case 'b': Data += '\b'; break;
1001 case 'f': Data += '\f'; break;
1002 case 'n': Data += '\n'; break;
1003 case 'r': Data += '\r'; break;
1004 case 't': Data += '\t'; break;
1005 case '"': Data += '"'; break;
1006 case '\\': Data += '\\'; break;
1013 /// ParseDirectiveAscii:
1014 /// ::= ( .ascii | .asciz ) [ "string" ( , "string" )* ]
1015 bool AsmParser::ParseDirectiveAscii(bool ZeroTerminated) {
1016 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1018 if (Lexer.isNot(AsmToken::String))
1019 return TokError("expected string in '.ascii' or '.asciz' directive");
1022 if (ParseEscapedString(Data))
1025 Out.EmitBytes(Data, DEFAULT_ADDRSPACE);
1027 Out.EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1031 if (Lexer.is(AsmToken::EndOfStatement))
1034 if (Lexer.isNot(AsmToken::Comma))
1035 return TokError("unexpected token in '.ascii' or '.asciz' directive");
1044 /// ParseDirectiveValue
1045 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1046 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1047 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1049 const MCExpr *Value;
1050 SMLoc ATTRIBUTE_UNUSED StartLoc = Lexer.getLoc();
1051 if (ParseExpression(Value))
1054 Out.EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1056 if (Lexer.is(AsmToken::EndOfStatement))
1059 // FIXME: Improve diagnostic.
1060 if (Lexer.isNot(AsmToken::Comma))
1061 return TokError("unexpected token in directive");
1070 /// ParseDirectiveSpace
1071 /// ::= .space expression [ , expression ]
1072 bool AsmParser::ParseDirectiveSpace() {
1074 if (ParseAbsoluteExpression(NumBytes))
1077 int64_t FillExpr = 0;
1078 bool HasFillExpr = false;
1079 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1080 if (Lexer.isNot(AsmToken::Comma))
1081 return TokError("unexpected token in '.space' directive");
1084 if (ParseAbsoluteExpression(FillExpr))
1089 if (Lexer.isNot(AsmToken::EndOfStatement))
1090 return TokError("unexpected token in '.space' directive");
1096 return TokError("invalid number of bytes in '.space' directive");
1098 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1099 Out.EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1104 /// ParseDirectiveFill
1105 /// ::= .fill expression , expression , expression
1106 bool AsmParser::ParseDirectiveFill() {
1108 if (ParseAbsoluteExpression(NumValues))
1111 if (Lexer.isNot(AsmToken::Comma))
1112 return TokError("unexpected token in '.fill' directive");
1116 if (ParseAbsoluteExpression(FillSize))
1119 if (Lexer.isNot(AsmToken::Comma))
1120 return TokError("unexpected token in '.fill' directive");
1124 if (ParseAbsoluteExpression(FillExpr))
1127 if (Lexer.isNot(AsmToken::EndOfStatement))
1128 return TokError("unexpected token in '.fill' directive");
1132 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1133 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1135 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1136 Out.EmitValue(MCConstantExpr::Create(FillExpr, getContext()), FillSize,
1142 /// ParseDirectiveOrg
1143 /// ::= .org expression [ , expression ]
1144 bool AsmParser::ParseDirectiveOrg() {
1145 const MCExpr *Offset;
1146 SMLoc StartLoc = Lexer.getLoc();
1147 if (ParseExpression(Offset))
1150 // Parse optional fill expression.
1151 int64_t FillExpr = 0;
1152 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1153 if (Lexer.isNot(AsmToken::Comma))
1154 return TokError("unexpected token in '.org' directive");
1157 if (ParseAbsoluteExpression(FillExpr))
1160 if (Lexer.isNot(AsmToken::EndOfStatement))
1161 return TokError("unexpected token in '.org' directive");
1166 // FIXME: Only limited forms of relocatable expressions are accepted here, it
1167 // has to be relative to the current section.
1168 Out.EmitValueToOffset(Offset, FillExpr);
1173 /// ParseDirectiveAlign
1174 /// ::= {.align, ...} expression [ , expression [ , expression ]]
1175 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1176 SMLoc AlignmentLoc = Lexer.getLoc();
1178 if (ParseAbsoluteExpression(Alignment))
1182 bool HasFillExpr = false;
1183 int64_t FillExpr = 0;
1184 int64_t MaxBytesToFill = 0;
1185 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1186 if (Lexer.isNot(AsmToken::Comma))
1187 return TokError("unexpected token in directive");
1190 // The fill expression can be omitted while specifying a maximum number of
1191 // alignment bytes, e.g:
1193 if (Lexer.isNot(AsmToken::Comma)) {
1195 if (ParseAbsoluteExpression(FillExpr))
1199 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1200 if (Lexer.isNot(AsmToken::Comma))
1201 return TokError("unexpected token in directive");
1204 MaxBytesLoc = Lexer.getLoc();
1205 if (ParseAbsoluteExpression(MaxBytesToFill))
1208 if (Lexer.isNot(AsmToken::EndOfStatement))
1209 return TokError("unexpected token in directive");
1216 // FIXME: Sometimes fill with nop.
1220 // Compute alignment in bytes.
1222 // FIXME: Diagnose overflow.
1223 if (Alignment >= 32) {
1224 Error(AlignmentLoc, "invalid alignment value");
1228 Alignment = 1ULL << Alignment;
1231 // Diagnose non-sensical max bytes to align.
1232 if (MaxBytesLoc.isValid()) {
1233 if (MaxBytesToFill < 1) {
1234 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
1235 "many bytes, ignoring maximum bytes expression");
1239 if (MaxBytesToFill >= Alignment) {
1240 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
1246 // FIXME: hard code the parser to use EmitCodeAlignment for text when using
1247 // the TextAlignFillValue.
1248 if(Out.getCurrentSection()->getKind().isText() &&
1249 Lexer.getMAI().getTextAlignFillValue() == FillExpr)
1250 Out.EmitCodeAlignment(Alignment, MaxBytesToFill);
1252 // FIXME: Target specific behavior about how the "extra" bytes are filled.
1253 Out.EmitValueToAlignment(Alignment, FillExpr, ValueSize, MaxBytesToFill);
1258 /// ParseDirectiveSymbolAttribute
1259 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
1260 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
1261 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1265 if (ParseIdentifier(Name))
1266 return TokError("expected identifier in directive");
1268 MCSymbol *Sym = CreateSymbol(Name);
1270 Out.EmitSymbolAttribute(Sym, Attr);
1272 if (Lexer.is(AsmToken::EndOfStatement))
1275 if (Lexer.isNot(AsmToken::Comma))
1276 return TokError("unexpected token in directive");
1285 /// ParseDirectiveDarwinSymbolDesc
1286 /// ::= .desc identifier , expression
1287 bool AsmParser::ParseDirectiveDarwinSymbolDesc() {
1289 if (ParseIdentifier(Name))
1290 return TokError("expected identifier in directive");
1292 // Handle the identifier as the key symbol.
1293 MCSymbol *Sym = CreateSymbol(Name);
1295 if (Lexer.isNot(AsmToken::Comma))
1296 return TokError("unexpected token in '.desc' directive");
1299 SMLoc DescLoc = Lexer.getLoc();
1301 if (ParseAbsoluteExpression(DescValue))
1304 if (Lexer.isNot(AsmToken::EndOfStatement))
1305 return TokError("unexpected token in '.desc' directive");
1309 // Set the n_desc field of this Symbol to this DescValue
1310 Out.EmitSymbolDesc(Sym, DescValue);
1315 /// ParseDirectiveComm
1316 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
1317 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
1318 SMLoc IDLoc = Lexer.getLoc();
1320 if (ParseIdentifier(Name))
1321 return TokError("expected identifier in directive");
1323 // Handle the identifier as the key symbol.
1324 MCSymbol *Sym = CreateSymbol(Name);
1326 if (Lexer.isNot(AsmToken::Comma))
1327 return TokError("unexpected token in directive");
1331 SMLoc SizeLoc = Lexer.getLoc();
1332 if (ParseAbsoluteExpression(Size))
1335 int64_t Pow2Alignment = 0;
1336 SMLoc Pow2AlignmentLoc;
1337 if (Lexer.is(AsmToken::Comma)) {
1339 Pow2AlignmentLoc = Lexer.getLoc();
1340 if (ParseAbsoluteExpression(Pow2Alignment))
1343 // If this target takes alignments in bytes (not log) validate and convert.
1344 if (Lexer.getMAI().getAlignmentIsInBytes()) {
1345 if (!isPowerOf2_64(Pow2Alignment))
1346 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
1347 Pow2Alignment = Log2_64(Pow2Alignment);
1351 if (Lexer.isNot(AsmToken::EndOfStatement))
1352 return TokError("unexpected token in '.comm' or '.lcomm' directive");
1356 // NOTE: a size of zero for a .comm should create a undefined symbol
1357 // but a size of .lcomm creates a bss symbol of size zero.
1359 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
1360 "be less than zero");
1362 // NOTE: The alignment in the directive is a power of 2 value, the assember
1363 // may internally end up wanting an alignment in bytes.
1364 // FIXME: Diagnose overflow.
1365 if (Pow2Alignment < 0)
1366 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
1367 "alignment, can't be less than zero");
1369 if (!Sym->isUndefined())
1370 return Error(IDLoc, "invalid symbol redefinition");
1372 // '.lcomm' is equivalent to '.zerofill'.
1373 // Create the Symbol as a common or local common with Size and Pow2Alignment
1375 Out.EmitZerofill(getMachOSection("__DATA", "__bss",
1376 MCSectionMachO::S_ZEROFILL, 0,
1377 SectionKind::getBSS()),
1378 Sym, Size, 1 << Pow2Alignment);
1382 Out.EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
1386 /// ParseDirectiveDarwinZerofill
1387 /// ::= .zerofill segname , sectname [, identifier , size_expression [
1388 /// , align_expression ]]
1389 bool AsmParser::ParseDirectiveDarwinZerofill() {
1390 // FIXME: Handle quoted names here.
1392 if (Lexer.isNot(AsmToken::Identifier))
1393 return TokError("expected segment name after '.zerofill' directive");
1394 StringRef Segment = getTok().getString();
1397 if (Lexer.isNot(AsmToken::Comma))
1398 return TokError("unexpected token in directive");
1401 if (Lexer.isNot(AsmToken::Identifier))
1402 return TokError("expected section name after comma in '.zerofill' "
1404 StringRef Section = getTok().getString();
1407 // If this is the end of the line all that was wanted was to create the
1408 // the section but with no symbol.
1409 if (Lexer.is(AsmToken::EndOfStatement)) {
1410 // Create the zerofill section but no symbol
1411 Out.EmitZerofill(getMachOSection(Segment, Section,
1412 MCSectionMachO::S_ZEROFILL, 0,
1413 SectionKind::getBSS()));
1417 if (Lexer.isNot(AsmToken::Comma))
1418 return TokError("unexpected token in directive");
1421 if (Lexer.isNot(AsmToken::Identifier))
1422 return TokError("expected identifier in directive");
1424 // handle the identifier as the key symbol.
1425 SMLoc IDLoc = Lexer.getLoc();
1426 MCSymbol *Sym = CreateSymbol(getTok().getString());
1429 if (Lexer.isNot(AsmToken::Comma))
1430 return TokError("unexpected token in directive");
1434 SMLoc SizeLoc = Lexer.getLoc();
1435 if (ParseAbsoluteExpression(Size))
1438 int64_t Pow2Alignment = 0;
1439 SMLoc Pow2AlignmentLoc;
1440 if (Lexer.is(AsmToken::Comma)) {
1442 Pow2AlignmentLoc = Lexer.getLoc();
1443 if (ParseAbsoluteExpression(Pow2Alignment))
1447 if (Lexer.isNot(AsmToken::EndOfStatement))
1448 return TokError("unexpected token in '.zerofill' directive");
1453 return Error(SizeLoc, "invalid '.zerofill' directive size, can't be less "
1456 // NOTE: The alignment in the directive is a power of 2 value, the assember
1457 // may internally end up wanting an alignment in bytes.
1458 // FIXME: Diagnose overflow.
1459 if (Pow2Alignment < 0)
1460 return Error(Pow2AlignmentLoc, "invalid '.zerofill' directive alignment, "
1461 "can't be less than zero");
1463 if (!Sym->isUndefined())
1464 return Error(IDLoc, "invalid symbol redefinition");
1466 // Create the zerofill Symbol with Size and Pow2Alignment
1468 // FIXME: Arch specific.
1469 Out.EmitZerofill(getMachOSection(Segment, Section,
1470 MCSectionMachO::S_ZEROFILL, 0,
1471 SectionKind::getBSS()),
1472 Sym, Size, 1 << Pow2Alignment);
1477 /// ParseDirectiveDarwinSubsectionsViaSymbols
1478 /// ::= .subsections_via_symbols
1479 bool AsmParser::ParseDirectiveDarwinSubsectionsViaSymbols() {
1480 if (Lexer.isNot(AsmToken::EndOfStatement))
1481 return TokError("unexpected token in '.subsections_via_symbols' directive");
1485 Out.EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
1490 /// ParseDirectiveAbort
1491 /// ::= .abort [ "abort_string" ]
1492 bool AsmParser::ParseDirectiveAbort() {
1493 // FIXME: Use loc from directive.
1494 SMLoc Loc = Lexer.getLoc();
1497 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1498 if (Lexer.isNot(AsmToken::String))
1499 return TokError("expected string in '.abort' directive");
1501 Str = getTok().getString();
1506 if (Lexer.isNot(AsmToken::EndOfStatement))
1507 return TokError("unexpected token in '.abort' directive");
1511 // FIXME: Handle here.
1513 Error(Loc, ".abort detected. Assembly stopping.");
1515 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
1520 /// ParseDirectiveLsym
1521 /// ::= .lsym identifier , expression
1522 bool AsmParser::ParseDirectiveDarwinLsym() {
1524 if (ParseIdentifier(Name))
1525 return TokError("expected identifier in directive");
1527 // Handle the identifier as the key symbol.
1528 MCSymbol *Sym = CreateSymbol(Name);
1530 if (Lexer.isNot(AsmToken::Comma))
1531 return TokError("unexpected token in '.lsym' directive");
1534 const MCExpr *Value;
1535 SMLoc StartLoc = Lexer.getLoc();
1536 if (ParseExpression(Value))
1539 if (Lexer.isNot(AsmToken::EndOfStatement))
1540 return TokError("unexpected token in '.lsym' directive");
1544 // We don't currently support this directive.
1546 // FIXME: Diagnostic location!
1548 return TokError("directive '.lsym' is unsupported");
1551 /// ParseDirectiveInclude
1552 /// ::= .include "filename"
1553 bool AsmParser::ParseDirectiveInclude() {
1554 if (Lexer.isNot(AsmToken::String))
1555 return TokError("expected string in '.include' directive");
1557 std::string Filename = getTok().getString();
1558 SMLoc IncludeLoc = Lexer.getLoc();
1561 if (Lexer.isNot(AsmToken::EndOfStatement))
1562 return TokError("unexpected token in '.include' directive");
1564 // Strip the quotes.
1565 Filename = Filename.substr(1, Filename.size()-2);
1567 // Attempt to switch the lexer to the included file before consuming the end
1568 // of statement to avoid losing it when we switch.
1569 if (EnterIncludeFile(Filename)) {
1570 PrintMessage(IncludeLoc,
1571 "Could not find include file '" + Filename + "'",
1579 /// ParseDirectiveDarwinDumpOrLoad
1580 /// ::= ( .dump | .load ) "filename"
1581 bool AsmParser::ParseDirectiveDarwinDumpOrLoad(SMLoc IDLoc, bool IsDump) {
1582 if (Lexer.isNot(AsmToken::String))
1583 return TokError("expected string in '.dump' or '.load' directive");
1587 if (Lexer.isNot(AsmToken::EndOfStatement))
1588 return TokError("unexpected token in '.dump' or '.load' directive");
1592 // FIXME: If/when .dump and .load are implemented they will be done in the
1593 // the assembly parser and not have any need for an MCStreamer API.
1595 Warning(IDLoc, "ignoring directive .dump for now");
1597 Warning(IDLoc, "ignoring directive .load for now");
1602 /// ParseDirectiveIf
1603 /// ::= .if expression
1604 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
1605 // Consume the identifier that was the .if directive
1608 TheCondStack.push_back(TheCondState);
1609 TheCondState.TheCond = AsmCond::IfCond;
1610 if(TheCondState.Ignore) {
1611 EatToEndOfStatement();
1615 if (ParseAbsoluteExpression(ExprValue))
1618 if (Lexer.isNot(AsmToken::EndOfStatement))
1619 return TokError("unexpected token in '.if' directive");
1623 TheCondState.CondMet = ExprValue;
1624 TheCondState.Ignore = !TheCondState.CondMet;
1630 /// ParseDirectiveElseIf
1631 /// ::= .elseif expression
1632 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
1633 if (TheCondState.TheCond != AsmCond::IfCond &&
1634 TheCondState.TheCond != AsmCond::ElseIfCond)
1635 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
1637 TheCondState.TheCond = AsmCond::ElseIfCond;
1639 // Consume the identifier that was the .elseif directive
1642 bool LastIgnoreState = false;
1643 if (!TheCondStack.empty())
1644 LastIgnoreState = TheCondStack.back().Ignore;
1645 if (LastIgnoreState || TheCondState.CondMet) {
1646 TheCondState.Ignore = true;
1647 EatToEndOfStatement();
1651 if (ParseAbsoluteExpression(ExprValue))
1654 if (Lexer.isNot(AsmToken::EndOfStatement))
1655 return TokError("unexpected token in '.elseif' directive");
1658 TheCondState.CondMet = ExprValue;
1659 TheCondState.Ignore = !TheCondState.CondMet;
1665 /// ParseDirectiveElse
1667 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
1668 // Consume the identifier that was the .else directive
1671 if (Lexer.isNot(AsmToken::EndOfStatement))
1672 return TokError("unexpected token in '.else' directive");
1676 if (TheCondState.TheCond != AsmCond::IfCond &&
1677 TheCondState.TheCond != AsmCond::ElseIfCond)
1678 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
1680 TheCondState.TheCond = AsmCond::ElseCond;
1681 bool LastIgnoreState = false;
1682 if (!TheCondStack.empty())
1683 LastIgnoreState = TheCondStack.back().Ignore;
1684 if (LastIgnoreState || TheCondState.CondMet)
1685 TheCondState.Ignore = true;
1687 TheCondState.Ignore = false;
1692 /// ParseDirectiveEndIf
1694 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
1695 // Consume the identifier that was the .endif directive
1698 if (Lexer.isNot(AsmToken::EndOfStatement))
1699 return TokError("unexpected token in '.endif' directive");
1703 if ((TheCondState.TheCond == AsmCond::NoCond) ||
1704 TheCondStack.empty())
1705 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
1707 if (!TheCondStack.empty()) {
1708 TheCondState = TheCondStack.back();
1709 TheCondStack.pop_back();
1715 /// ParseDirectiveFile
1716 /// ::= .file [number] string
1717 bool AsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
1718 // FIXME: I'm not sure what this is.
1719 int64_t FileNumber = -1;
1720 if (Lexer.is(AsmToken::Integer)) {
1721 FileNumber = getTok().getIntVal();
1725 return TokError("file number less than one");
1728 if (Lexer.isNot(AsmToken::String))
1729 return TokError("unexpected token in '.file' directive");
1731 StringRef Filename = getTok().getString();
1732 Filename = Filename.substr(1, Filename.size()-2);
1735 if (Lexer.isNot(AsmToken::EndOfStatement))
1736 return TokError("unexpected token in '.file' directive");
1738 if (FileNumber == -1)
1739 Out.EmitFileDirective(Filename);
1741 Out.EmitDwarfFileDirective(FileNumber, Filename);
1746 /// ParseDirectiveLine
1747 /// ::= .line [number]
1748 bool AsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
1749 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1750 if (Lexer.isNot(AsmToken::Integer))
1751 return TokError("unexpected token in '.line' directive");
1753 int64_t LineNumber = getTok().getIntVal();
1757 // FIXME: Do something with the .line.
1760 if (Lexer.isNot(AsmToken::EndOfStatement))
1761 return TokError("unexpected token in '.file' directive");
1767 /// ParseDirectiveLoc
1768 /// ::= .loc number [number [number]]
1769 bool AsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
1770 if (Lexer.isNot(AsmToken::Integer))
1771 return TokError("unexpected token in '.loc' directive");
1773 // FIXME: What are these fields?
1774 int64_t FileNumber = getTok().getIntVal();
1776 // FIXME: Validate file.
1779 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1780 if (Lexer.isNot(AsmToken::Integer))
1781 return TokError("unexpected token in '.loc' directive");
1783 int64_t Param2 = getTok().getIntVal();
1787 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1788 if (Lexer.isNot(AsmToken::Integer))
1789 return TokError("unexpected token in '.loc' directive");
1791 int64_t Param3 = getTok().getIntVal();
1795 // FIXME: Do something with the .loc.
1799 if (Lexer.isNot(AsmToken::EndOfStatement))
1800 return TokError("unexpected token in '.file' directive");