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() {
142 // Create the initial section.
144 // FIXME: Support -n.
145 // FIXME: Target hook & command line option for initial section.
146 Out.SwitchSection(getMachOSection("__TEXT", "__text",
147 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
148 0, SectionKind::getText()));
154 bool HadError = false;
156 AsmCond StartingCondState = TheCondState;
158 // While we have input, parse each statement.
159 while (Lexer.isNot(AsmToken::Eof)) {
160 // Handle conditional assembly here before calling ParseStatement()
161 if (Lexer.getKind() == AsmToken::Identifier) {
162 // If we have an identifier, handle it as the key symbol.
163 AsmToken ID = getTok();
164 SMLoc IDLoc = ID.getLoc();
165 StringRef IDVal = ID.getString();
167 if (IDVal == ".if" ||
168 IDVal == ".elseif" ||
171 if (!ParseConditionalAssemblyDirectives(IDVal, IDLoc))
174 EatToEndOfStatement();
178 if (TheCondState.Ignore) {
179 EatToEndOfStatement();
183 if (!ParseStatement()) continue;
185 // We had an error, remember it and recover by skipping to the next line.
187 EatToEndOfStatement();
190 if (TheCondState.TheCond != StartingCondState.TheCond ||
191 TheCondState.Ignore != StartingCondState.Ignore)
192 return TokError("unmatched .ifs or .elses");
200 /// ParseConditionalAssemblyDirectives - parse the conditional assembly
202 bool AsmParser::ParseConditionalAssemblyDirectives(StringRef Directive,
203 SMLoc DirectiveLoc) {
204 if (Directive == ".if")
205 return ParseDirectiveIf(DirectiveLoc);
206 if (Directive == ".elseif")
207 return ParseDirectiveElseIf(DirectiveLoc);
208 if (Directive == ".else")
209 return ParseDirectiveElse(DirectiveLoc);
210 if (Directive == ".endif")
211 return ParseDirectiveEndIf(DirectiveLoc);
215 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
216 void AsmParser::EatToEndOfStatement() {
217 while (Lexer.isNot(AsmToken::EndOfStatement) &&
218 Lexer.isNot(AsmToken::Eof))
222 if (Lexer.is(AsmToken::EndOfStatement))
227 /// ParseParenExpr - Parse a paren expression and return it.
228 /// NOTE: This assumes the leading '(' has already been consumed.
230 /// parenexpr ::= expr)
232 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
233 if (ParseExpression(Res)) return true;
234 if (Lexer.isNot(AsmToken::RParen))
235 return TokError("expected ')' in parentheses expression");
236 EndLoc = Lexer.getLoc();
241 MCSymbol *AsmParser::CreateSymbol(StringRef Name) {
242 // If the label starts with L it is an assembler temporary label.
243 if (Name.startswith("L"))
244 return Ctx.GetOrCreateTemporarySymbol(Name);
245 return Ctx.GetOrCreateSymbol(Name);
248 /// ParsePrimaryExpr - Parse a primary expression and return it.
249 /// primaryexpr ::= (parenexpr
250 /// primaryexpr ::= symbol
251 /// primaryexpr ::= number
252 /// primaryexpr ::= ~,+,- primaryexpr
253 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
254 switch (Lexer.getKind()) {
256 return TokError("unknown token in expression");
257 case AsmToken::Exclaim:
258 Lex(); // Eat the operator.
259 if (ParsePrimaryExpr(Res, EndLoc))
261 Res = MCUnaryExpr::CreateLNot(Res, getContext());
263 case AsmToken::String:
264 case AsmToken::Identifier: {
265 // This is a symbol reference.
266 MCSymbol *Sym = CreateSymbol(getTok().getIdentifier());
267 EndLoc = Lexer.getLoc();
268 Lex(); // Eat identifier.
270 // If this is an absolute variable reference, substitute it now to preserve
271 // semantics in the face of reassignment.
272 if (Sym->getValue() && isa<MCConstantExpr>(Sym->getValue())) {
273 Res = Sym->getValue();
277 // Otherwise create a symbol ref.
278 Res = MCSymbolRefExpr::Create(Sym, getContext());
281 case AsmToken::Integer:
282 Res = MCConstantExpr::Create(getTok().getIntVal(), getContext());
283 EndLoc = Lexer.getLoc();
286 case AsmToken::LParen:
287 Lex(); // Eat the '('.
288 return ParseParenExpr(Res, EndLoc);
289 case AsmToken::Minus:
290 Lex(); // Eat the operator.
291 if (ParsePrimaryExpr(Res, EndLoc))
293 Res = MCUnaryExpr::CreateMinus(Res, getContext());
296 Lex(); // Eat the operator.
297 if (ParsePrimaryExpr(Res, EndLoc))
299 Res = MCUnaryExpr::CreatePlus(Res, getContext());
301 case AsmToken::Tilde:
302 Lex(); // Eat the operator.
303 if (ParsePrimaryExpr(Res, EndLoc))
305 Res = MCUnaryExpr::CreateNot(Res, getContext());
310 bool AsmParser::ParseExpression(const MCExpr *&Res) {
312 return ParseExpression(Res, EndLoc);
315 /// ParseExpression - Parse an expression and return it.
317 /// expr ::= expr +,- expr -> lowest.
318 /// expr ::= expr |,^,&,! expr -> middle.
319 /// expr ::= expr *,/,%,<<,>> expr -> highest.
320 /// expr ::= primaryexpr
322 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
323 // Parse the expression.
325 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
328 // Try to constant fold it up front, if possible.
330 if (Res->EvaluateAsAbsolute(Value))
331 Res = MCConstantExpr::Create(Value, getContext());
336 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
338 return ParseParenExpr(Res, EndLoc) ||
339 ParseBinOpRHS(1, Res, EndLoc);
342 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
345 SMLoc StartLoc = Lexer.getLoc();
346 if (ParseExpression(Expr))
349 if (!Expr->EvaluateAsAbsolute(Res))
350 return Error(StartLoc, "expected absolute expression");
355 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
356 MCBinaryExpr::Opcode &Kind) {
359 return 0; // not a binop.
361 // Lowest Precedence: &&, ||
362 case AsmToken::AmpAmp:
363 Kind = MCBinaryExpr::LAnd;
365 case AsmToken::PipePipe:
366 Kind = MCBinaryExpr::LOr;
369 // Low Precedence: +, -, ==, !=, <>, <, <=, >, >=
371 Kind = MCBinaryExpr::Add;
373 case AsmToken::Minus:
374 Kind = MCBinaryExpr::Sub;
376 case AsmToken::EqualEqual:
377 Kind = MCBinaryExpr::EQ;
379 case AsmToken::ExclaimEqual:
380 case AsmToken::LessGreater:
381 Kind = MCBinaryExpr::NE;
384 Kind = MCBinaryExpr::LT;
386 case AsmToken::LessEqual:
387 Kind = MCBinaryExpr::LTE;
389 case AsmToken::Greater:
390 Kind = MCBinaryExpr::GT;
392 case AsmToken::GreaterEqual:
393 Kind = MCBinaryExpr::GTE;
396 // Intermediate Precedence: |, &, ^
398 // FIXME: gas seems to support '!' as an infix operator?
400 Kind = MCBinaryExpr::Or;
402 case AsmToken::Caret:
403 Kind = MCBinaryExpr::Xor;
406 Kind = MCBinaryExpr::And;
409 // Highest Precedence: *, /, %, <<, >>
411 Kind = MCBinaryExpr::Mul;
413 case AsmToken::Slash:
414 Kind = MCBinaryExpr::Div;
416 case AsmToken::Percent:
417 Kind = MCBinaryExpr::Mod;
419 case AsmToken::LessLess:
420 Kind = MCBinaryExpr::Shl;
422 case AsmToken::GreaterGreater:
423 Kind = MCBinaryExpr::Shr;
429 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
430 /// Res contains the LHS of the expression on input.
431 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
434 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
435 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
437 // If the next token is lower precedence than we are allowed to eat, return
438 // successfully with what we ate already.
439 if (TokPrec < Precedence)
444 // Eat the next primary expression.
446 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
448 // If BinOp binds less tightly with RHS than the operator after RHS, let
449 // the pending operator take RHS as its LHS.
450 MCBinaryExpr::Opcode Dummy;
451 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
452 if (TokPrec < NextTokPrec) {
453 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
456 // Merge LHS and RHS according to operator.
457 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
465 /// ::= EndOfStatement
466 /// ::= Label* Directive ...Operands... EndOfStatement
467 /// ::= Label* Identifier OperandList* EndOfStatement
468 bool AsmParser::ParseStatement() {
469 if (Lexer.is(AsmToken::EndOfStatement)) {
474 // Statements always start with an identifier.
475 AsmToken ID = getTok();
476 SMLoc IDLoc = ID.getLoc();
478 if (ParseIdentifier(IDVal))
479 return TokError("unexpected token at start of statement");
481 // FIXME: Recurse on local labels?
483 // See what kind of statement we have.
484 switch (Lexer.getKind()) {
485 case AsmToken::Colon: {
486 // identifier ':' -> Label.
489 // Diagnose attempt to use a variable as a label.
491 // FIXME: Diagnostics. Note the location of the definition as a label.
492 // FIXME: This doesn't diagnose assignment to a symbol which has been
493 // implicitly marked as external.
494 MCSymbol *Sym = CreateSymbol(IDVal);
495 if (!Sym->isUndefined())
496 return Error(IDLoc, "invalid symbol redefinition");
501 return ParseStatement();
504 case AsmToken::Equal:
505 // identifier '=' ... -> assignment statement
508 return ParseAssignment(IDVal);
510 default: // Normal instruction or directive.
514 // Otherwise, we have a normal instruction or directive.
515 if (IDVal[0] == '.') {
516 // FIXME: This should be driven based on a hash lookup and callback.
517 if (IDVal == ".section")
518 return ParseDirectiveDarwinSection();
519 if (IDVal == ".text")
520 // FIXME: This changes behavior based on the -static flag to the
522 return ParseDirectiveSectionSwitch("__TEXT", "__text",
523 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS);
524 if (IDVal == ".const")
525 return ParseDirectiveSectionSwitch("__TEXT", "__const");
526 if (IDVal == ".static_const")
527 return ParseDirectiveSectionSwitch("__TEXT", "__static_const");
528 if (IDVal == ".cstring")
529 return ParseDirectiveSectionSwitch("__TEXT","__cstring",
530 MCSectionMachO::S_CSTRING_LITERALS);
531 if (IDVal == ".literal4")
532 return ParseDirectiveSectionSwitch("__TEXT", "__literal4",
533 MCSectionMachO::S_4BYTE_LITERALS,
535 if (IDVal == ".literal8")
536 return ParseDirectiveSectionSwitch("__TEXT", "__literal8",
537 MCSectionMachO::S_8BYTE_LITERALS,
539 if (IDVal == ".literal16")
540 return ParseDirectiveSectionSwitch("__TEXT","__literal16",
541 MCSectionMachO::S_16BYTE_LITERALS,
543 if (IDVal == ".constructor")
544 return ParseDirectiveSectionSwitch("__TEXT","__constructor");
545 if (IDVal == ".destructor")
546 return ParseDirectiveSectionSwitch("__TEXT","__destructor");
547 if (IDVal == ".fvmlib_init0")
548 return ParseDirectiveSectionSwitch("__TEXT","__fvmlib_init0");
549 if (IDVal == ".fvmlib_init1")
550 return ParseDirectiveSectionSwitch("__TEXT","__fvmlib_init1");
552 // FIXME: The assembler manual claims that this has the self modify code
553 // flag, at least on x86-32, but that does not appear to be correct.
554 if (IDVal == ".symbol_stub")
555 return ParseDirectiveSectionSwitch("__TEXT","__symbol_stub",
556 MCSectionMachO::S_SYMBOL_STUBS |
557 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
558 // FIXME: Different on PPC and ARM.
560 // FIXME: PowerPC only?
561 if (IDVal == ".picsymbol_stub")
562 return ParseDirectiveSectionSwitch("__TEXT","__picsymbol_stub",
563 MCSectionMachO::S_SYMBOL_STUBS |
564 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
566 if (IDVal == ".data")
567 return ParseDirectiveSectionSwitch("__DATA", "__data");
568 if (IDVal == ".static_data")
569 return ParseDirectiveSectionSwitch("__DATA", "__static_data");
571 // FIXME: The section names of these two are misspelled in the assembler
573 if (IDVal == ".non_lazy_symbol_pointer")
574 return ParseDirectiveSectionSwitch("__DATA", "__nl_symbol_ptr",
575 MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS,
577 if (IDVal == ".lazy_symbol_pointer")
578 return ParseDirectiveSectionSwitch("__DATA", "__la_symbol_ptr",
579 MCSectionMachO::S_LAZY_SYMBOL_POINTERS,
582 if (IDVal == ".dyld")
583 return ParseDirectiveSectionSwitch("__DATA", "__dyld");
584 if (IDVal == ".mod_init_func")
585 return ParseDirectiveSectionSwitch("__DATA", "__mod_init_func",
586 MCSectionMachO::S_MOD_INIT_FUNC_POINTERS,
588 if (IDVal == ".mod_term_func")
589 return ParseDirectiveSectionSwitch("__DATA", "__mod_term_func",
590 MCSectionMachO::S_MOD_TERM_FUNC_POINTERS,
592 if (IDVal == ".const_data")
593 return ParseDirectiveSectionSwitch("__DATA", "__const");
596 if (IDVal == ".objc_class")
597 return ParseDirectiveSectionSwitch("__OBJC", "__class",
598 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
599 if (IDVal == ".objc_meta_class")
600 return ParseDirectiveSectionSwitch("__OBJC", "__meta_class",
601 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
602 if (IDVal == ".objc_cat_cls_meth")
603 return ParseDirectiveSectionSwitch("__OBJC", "__cat_cls_meth",
604 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
605 if (IDVal == ".objc_cat_inst_meth")
606 return ParseDirectiveSectionSwitch("__OBJC", "__cat_inst_meth",
607 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
608 if (IDVal == ".objc_protocol")
609 return ParseDirectiveSectionSwitch("__OBJC", "__protocol",
610 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
611 if (IDVal == ".objc_string_object")
612 return ParseDirectiveSectionSwitch("__OBJC", "__string_object",
613 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
614 if (IDVal == ".objc_cls_meth")
615 return ParseDirectiveSectionSwitch("__OBJC", "__cls_meth",
616 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
617 if (IDVal == ".objc_inst_meth")
618 return ParseDirectiveSectionSwitch("__OBJC", "__inst_meth",
619 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
620 if (IDVal == ".objc_cls_refs")
621 return ParseDirectiveSectionSwitch("__OBJC", "__cls_refs",
622 MCSectionMachO::S_ATTR_NO_DEAD_STRIP |
623 MCSectionMachO::S_LITERAL_POINTERS,
625 if (IDVal == ".objc_message_refs")
626 return ParseDirectiveSectionSwitch("__OBJC", "__message_refs",
627 MCSectionMachO::S_ATTR_NO_DEAD_STRIP |
628 MCSectionMachO::S_LITERAL_POINTERS,
630 if (IDVal == ".objc_symbols")
631 return ParseDirectiveSectionSwitch("__OBJC", "__symbols",
632 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
633 if (IDVal == ".objc_category")
634 return ParseDirectiveSectionSwitch("__OBJC", "__category",
635 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
636 if (IDVal == ".objc_class_vars")
637 return ParseDirectiveSectionSwitch("__OBJC", "__class_vars",
638 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
639 if (IDVal == ".objc_instance_vars")
640 return ParseDirectiveSectionSwitch("__OBJC", "__instance_vars",
641 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
642 if (IDVal == ".objc_module_info")
643 return ParseDirectiveSectionSwitch("__OBJC", "__module_info",
644 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
645 if (IDVal == ".objc_class_names")
646 return ParseDirectiveSectionSwitch("__TEXT", "__cstring",
647 MCSectionMachO::S_CSTRING_LITERALS);
648 if (IDVal == ".objc_meth_var_types")
649 return ParseDirectiveSectionSwitch("__TEXT", "__cstring",
650 MCSectionMachO::S_CSTRING_LITERALS);
651 if (IDVal == ".objc_meth_var_names")
652 return ParseDirectiveSectionSwitch("__TEXT", "__cstring",
653 MCSectionMachO::S_CSTRING_LITERALS);
654 if (IDVal == ".objc_selector_strs")
655 return ParseDirectiveSectionSwitch("__OBJC", "__selector_strs",
656 MCSectionMachO::S_CSTRING_LITERALS);
658 // Assembler features
660 return ParseDirectiveSet();
664 if (IDVal == ".ascii")
665 return ParseDirectiveAscii(false);
666 if (IDVal == ".asciz")
667 return ParseDirectiveAscii(true);
669 if (IDVal == ".byte")
670 return ParseDirectiveValue(1);
671 if (IDVal == ".short")
672 return ParseDirectiveValue(2);
673 if (IDVal == ".long")
674 return ParseDirectiveValue(4);
675 if (IDVal == ".quad")
676 return ParseDirectiveValue(8);
678 // FIXME: Target hooks for IsPow2.
679 if (IDVal == ".align")
680 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
681 if (IDVal == ".align32")
682 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
683 if (IDVal == ".balign")
684 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
685 if (IDVal == ".balignw")
686 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
687 if (IDVal == ".balignl")
688 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
689 if (IDVal == ".p2align")
690 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
691 if (IDVal == ".p2alignw")
692 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
693 if (IDVal == ".p2alignl")
694 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
697 return ParseDirectiveOrg();
699 if (IDVal == ".fill")
700 return ParseDirectiveFill();
701 if (IDVal == ".space")
702 return ParseDirectiveSpace();
704 // Symbol attribute directives
706 if (IDVal == ".globl" || IDVal == ".global")
707 return ParseDirectiveSymbolAttribute(MCSA_Global);
708 if (IDVal == ".hidden")
709 return ParseDirectiveSymbolAttribute(MCSA_Hidden);
710 if (IDVal == ".indirect_symbol")
711 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
712 if (IDVal == ".internal")
713 return ParseDirectiveSymbolAttribute(MCSA_Internal);
714 if (IDVal == ".lazy_reference")
715 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
716 if (IDVal == ".no_dead_strip")
717 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
718 if (IDVal == ".private_extern")
719 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
720 if (IDVal == ".protected")
721 return ParseDirectiveSymbolAttribute(MCSA_Protected);
722 if (IDVal == ".reference")
723 return ParseDirectiveSymbolAttribute(MCSA_Reference);
724 if (IDVal == ".weak")
725 return ParseDirectiveSymbolAttribute(MCSA_Weak);
726 if (IDVal == ".weak_definition")
727 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
728 if (IDVal == ".weak_reference")
729 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
731 if (IDVal == ".comm")
732 return ParseDirectiveComm(/*IsLocal=*/false);
733 if (IDVal == ".lcomm")
734 return ParseDirectiveComm(/*IsLocal=*/true);
735 if (IDVal == ".zerofill")
736 return ParseDirectiveDarwinZerofill();
737 if (IDVal == ".desc")
738 return ParseDirectiveDarwinSymbolDesc();
739 if (IDVal == ".lsym")
740 return ParseDirectiveDarwinLsym();
742 if (IDVal == ".subsections_via_symbols")
743 return ParseDirectiveDarwinSubsectionsViaSymbols();
744 if (IDVal == ".abort")
745 return ParseDirectiveAbort();
746 if (IDVal == ".include")
747 return ParseDirectiveInclude();
748 if (IDVal == ".dump")
749 return ParseDirectiveDarwinDumpOrLoad(IDLoc, /*IsDump=*/true);
750 if (IDVal == ".load")
751 return ParseDirectiveDarwinDumpOrLoad(IDLoc, /*IsLoad=*/false);
753 // Look up the handler in the handler table,
754 bool(AsmParser::*Handler)(StringRef, SMLoc) = DirectiveMap[IDVal];
756 return (this->*Handler)(IDVal, IDLoc);
758 // Target hook for parsing target specific directives.
759 if (!getTargetParser().ParseDirective(ID))
762 Warning(IDLoc, "ignoring directive for now");
763 EatToEndOfStatement();
768 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
769 if (getTargetParser().ParseInstruction(IDVal, IDLoc, ParsedOperands))
770 // FIXME: Leaking ParsedOperands on failure.
773 if (Lexer.isNot(AsmToken::EndOfStatement))
774 // FIXME: Leaking ParsedOperands on failure.
775 return TokError("unexpected token in argument list");
777 // Eat the end of statement marker.
783 bool MatchFail = getTargetParser().MatchInstruction(ParsedOperands, Inst);
785 // Free any parsed operands.
786 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
787 delete ParsedOperands[i];
790 // FIXME: We should give nicer diagnostics about the exact failure.
791 Error(IDLoc, "unrecognized instruction");
795 // Instruction is good, process it.
796 Out.EmitInstruction(Inst);
798 // Skip to end of line for now.
802 bool AsmParser::ParseAssignment(const StringRef &Name) {
803 // FIXME: Use better location, we should use proper tokens.
804 SMLoc EqualLoc = Lexer.getLoc();
807 SMLoc StartLoc = Lexer.getLoc();
808 if (ParseExpression(Value))
811 if (Lexer.isNot(AsmToken::EndOfStatement))
812 return TokError("unexpected token in assignment");
814 // Eat the end of statement marker.
817 // Validate that the LHS is allowed to be a variable (either it has not been
818 // used as a symbol, or it is an absolute symbol).
819 MCSymbol *Sym = getContext().LookupSymbol(Name);
821 // Diagnose assignment to a label.
823 // FIXME: Diagnostics. Note the location of the definition as a label.
824 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
825 if (!Sym->isUndefined() && !Sym->isAbsolute())
826 return Error(EqualLoc, "redefinition of '" + Name + "'");
827 else if (!Sym->isVariable())
828 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
829 else if (!isa<MCConstantExpr>(Sym->getValue()))
830 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
833 Sym = CreateSymbol(Name);
835 // FIXME: Handle '.'.
837 // Do the assignment.
838 Out.EmitAssignment(Sym, Value);
846 bool AsmParser::ParseIdentifier(StringRef &Res) {
847 if (Lexer.isNot(AsmToken::Identifier) &&
848 Lexer.isNot(AsmToken::String))
851 Res = getTok().getIdentifier();
853 Lex(); // Consume the identifier token.
858 /// ParseDirectiveSet:
859 /// ::= .set identifier ',' expression
860 bool AsmParser::ParseDirectiveSet() {
863 if (ParseIdentifier(Name))
864 return TokError("expected identifier after '.set' directive");
866 if (Lexer.isNot(AsmToken::Comma))
867 return TokError("unexpected token in '.set'");
870 return ParseAssignment(Name);
873 /// ParseDirectiveSection:
874 /// ::= .section identifier (',' identifier)*
875 /// FIXME: This should actually parse out the segment, section, attributes and
876 /// sizeof_stub fields.
877 bool AsmParser::ParseDirectiveDarwinSection() {
878 SMLoc Loc = Lexer.getLoc();
880 StringRef SectionName;
881 if (ParseIdentifier(SectionName))
882 return Error(Loc, "expected identifier after '.section' directive");
884 // Verify there is a following comma.
885 if (!Lexer.is(AsmToken::Comma))
886 return TokError("unexpected token in '.section' directive");
888 std::string SectionSpec = SectionName;
891 // Add all the tokens until the end of the line, ParseSectionSpecifier will
893 StringRef EOL = Lexer.LexUntilEndOfStatement();
894 SectionSpec.append(EOL.begin(), EOL.end());
897 if (Lexer.isNot(AsmToken::EndOfStatement))
898 return TokError("unexpected token in '.section' directive");
902 StringRef Segment, Section;
903 unsigned TAA, StubSize;
904 std::string ErrorStr =
905 MCSectionMachO::ParseSectionSpecifier(SectionSpec, Segment, Section,
908 if (!ErrorStr.empty())
909 return Error(Loc, ErrorStr.c_str());
911 // FIXME: Arch specific.
912 bool isText = Segment == "__TEXT"; // FIXME: Hack.
913 Out.SwitchSection(getMachOSection(Segment, Section, TAA, StubSize,
914 isText ? SectionKind::getText()
915 : SectionKind::getDataRel()));
919 /// ParseDirectiveSectionSwitch -
920 bool AsmParser::ParseDirectiveSectionSwitch(const char *Segment,
922 unsigned TAA, unsigned Align,
924 if (Lexer.isNot(AsmToken::EndOfStatement))
925 return TokError("unexpected token in section switching directive");
928 // FIXME: Arch specific.
929 bool isText = StringRef(Segment) == "__TEXT"; // FIXME: Hack.
930 Out.SwitchSection(getMachOSection(Segment, Section, TAA, StubSize,
931 isText ? SectionKind::getText()
932 : SectionKind::getDataRel()));
934 // Set the implicit alignment, if any.
936 // FIXME: This isn't really what 'as' does; I think it just uses the implicit
937 // alignment on the section (e.g., if one manually inserts bytes into the
938 // section, then just issueing the section switch directive will not realign
939 // the section. However, this is arguably more reasonable behavior, and there
940 // is no good reason for someone to intentionally emit incorrectly sized
941 // values into the implicitly aligned sections.
943 Out.EmitValueToAlignment(Align, 0, 1, 0);
948 bool AsmParser::ParseEscapedString(std::string &Data) {
949 assert(Lexer.is(AsmToken::String) && "Unexpected current token!");
952 StringRef Str = getTok().getStringContents();
953 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
954 if (Str[i] != '\\') {
959 // Recognize escaped characters. Note that this escape semantics currently
960 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
963 return TokError("unexpected backslash at end of string");
965 // Recognize octal sequences.
966 if ((unsigned) (Str[i] - '0') <= 7) {
967 // Consume up to three octal characters.
968 unsigned Value = Str[i] - '0';
970 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
972 Value = Value * 8 + (Str[i] - '0');
974 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
976 Value = Value * 8 + (Str[i] - '0');
981 return TokError("invalid octal escape sequence (out of range)");
983 Data += (unsigned char) Value;
987 // Otherwise recognize individual escapes.
990 // Just reject invalid escape sequences for now.
991 return TokError("invalid escape sequence (unrecognized character)");
993 case 'b': Data += '\b'; break;
994 case 'f': Data += '\f'; break;
995 case 'n': Data += '\n'; break;
996 case 'r': Data += '\r'; break;
997 case 't': Data += '\t'; break;
998 case '"': Data += '"'; break;
999 case '\\': Data += '\\'; break;
1006 /// ParseDirectiveAscii:
1007 /// ::= ( .ascii | .asciz ) [ "string" ( , "string" )* ]
1008 bool AsmParser::ParseDirectiveAscii(bool ZeroTerminated) {
1009 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1011 if (Lexer.isNot(AsmToken::String))
1012 return TokError("expected string in '.ascii' or '.asciz' directive");
1015 if (ParseEscapedString(Data))
1018 Out.EmitBytes(Data, DEFAULT_ADDRSPACE);
1020 Out.EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1024 if (Lexer.is(AsmToken::EndOfStatement))
1027 if (Lexer.isNot(AsmToken::Comma))
1028 return TokError("unexpected token in '.ascii' or '.asciz' directive");
1037 /// ParseDirectiveValue
1038 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1039 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1040 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1042 const MCExpr *Value;
1043 SMLoc ATTRIBUTE_UNUSED StartLoc = Lexer.getLoc();
1044 if (ParseExpression(Value))
1047 Out.EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1049 if (Lexer.is(AsmToken::EndOfStatement))
1052 // FIXME: Improve diagnostic.
1053 if (Lexer.isNot(AsmToken::Comma))
1054 return TokError("unexpected token in directive");
1063 /// ParseDirectiveSpace
1064 /// ::= .space expression [ , expression ]
1065 bool AsmParser::ParseDirectiveSpace() {
1067 if (ParseAbsoluteExpression(NumBytes))
1070 int64_t FillExpr = 0;
1071 bool HasFillExpr = false;
1072 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1073 if (Lexer.isNot(AsmToken::Comma))
1074 return TokError("unexpected token in '.space' directive");
1077 if (ParseAbsoluteExpression(FillExpr))
1082 if (Lexer.isNot(AsmToken::EndOfStatement))
1083 return TokError("unexpected token in '.space' directive");
1089 return TokError("invalid number of bytes in '.space' directive");
1091 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1092 Out.EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1097 /// ParseDirectiveFill
1098 /// ::= .fill expression , expression , expression
1099 bool AsmParser::ParseDirectiveFill() {
1101 if (ParseAbsoluteExpression(NumValues))
1104 if (Lexer.isNot(AsmToken::Comma))
1105 return TokError("unexpected token in '.fill' directive");
1109 if (ParseAbsoluteExpression(FillSize))
1112 if (Lexer.isNot(AsmToken::Comma))
1113 return TokError("unexpected token in '.fill' directive");
1117 if (ParseAbsoluteExpression(FillExpr))
1120 if (Lexer.isNot(AsmToken::EndOfStatement))
1121 return TokError("unexpected token in '.fill' directive");
1125 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1126 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1128 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1129 Out.EmitValue(MCConstantExpr::Create(FillExpr, getContext()), FillSize,
1135 /// ParseDirectiveOrg
1136 /// ::= .org expression [ , expression ]
1137 bool AsmParser::ParseDirectiveOrg() {
1138 const MCExpr *Offset;
1139 SMLoc StartLoc = Lexer.getLoc();
1140 if (ParseExpression(Offset))
1143 // Parse optional fill expression.
1144 int64_t FillExpr = 0;
1145 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1146 if (Lexer.isNot(AsmToken::Comma))
1147 return TokError("unexpected token in '.org' directive");
1150 if (ParseAbsoluteExpression(FillExpr))
1153 if (Lexer.isNot(AsmToken::EndOfStatement))
1154 return TokError("unexpected token in '.org' directive");
1159 // FIXME: Only limited forms of relocatable expressions are accepted here, it
1160 // has to be relative to the current section.
1161 Out.EmitValueToOffset(Offset, FillExpr);
1166 /// ParseDirectiveAlign
1167 /// ::= {.align, ...} expression [ , expression [ , expression ]]
1168 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1169 SMLoc AlignmentLoc = Lexer.getLoc();
1171 if (ParseAbsoluteExpression(Alignment))
1175 bool HasFillExpr = false;
1176 int64_t FillExpr = 0;
1177 int64_t MaxBytesToFill = 0;
1178 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1179 if (Lexer.isNot(AsmToken::Comma))
1180 return TokError("unexpected token in directive");
1183 // The fill expression can be omitted while specifying a maximum number of
1184 // alignment bytes, e.g:
1186 if (Lexer.isNot(AsmToken::Comma)) {
1188 if (ParseAbsoluteExpression(FillExpr))
1192 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1193 if (Lexer.isNot(AsmToken::Comma))
1194 return TokError("unexpected token in directive");
1197 MaxBytesLoc = Lexer.getLoc();
1198 if (ParseAbsoluteExpression(MaxBytesToFill))
1201 if (Lexer.isNot(AsmToken::EndOfStatement))
1202 return TokError("unexpected token in directive");
1209 // FIXME: Sometimes fill with nop.
1213 // Compute alignment in bytes.
1215 // FIXME: Diagnose overflow.
1216 if (Alignment >= 32) {
1217 Error(AlignmentLoc, "invalid alignment value");
1221 Alignment = 1ULL << Alignment;
1224 // Diagnose non-sensical max bytes to align.
1225 if (MaxBytesLoc.isValid()) {
1226 if (MaxBytesToFill < 1) {
1227 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
1228 "many bytes, ignoring maximum bytes expression");
1232 if (MaxBytesToFill >= Alignment) {
1233 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
1239 // FIXME: hard code the parser to use EmitCodeAlignment for text when using
1240 // the TextAlignFillValue.
1241 if(Out.getCurrentSection()->getKind().isText() &&
1242 Lexer.getMAI().getTextAlignFillValue() == FillExpr)
1243 Out.EmitCodeAlignment(Alignment, MaxBytesToFill);
1245 // FIXME: Target specific behavior about how the "extra" bytes are filled.
1246 Out.EmitValueToAlignment(Alignment, FillExpr, ValueSize, MaxBytesToFill);
1251 /// ParseDirectiveSymbolAttribute
1252 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
1253 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
1254 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1258 if (ParseIdentifier(Name))
1259 return TokError("expected identifier in directive");
1261 MCSymbol *Sym = CreateSymbol(Name);
1263 Out.EmitSymbolAttribute(Sym, Attr);
1265 if (Lexer.is(AsmToken::EndOfStatement))
1268 if (Lexer.isNot(AsmToken::Comma))
1269 return TokError("unexpected token in directive");
1278 /// ParseDirectiveDarwinSymbolDesc
1279 /// ::= .desc identifier , expression
1280 bool AsmParser::ParseDirectiveDarwinSymbolDesc() {
1282 if (ParseIdentifier(Name))
1283 return TokError("expected identifier in directive");
1285 // Handle the identifier as the key symbol.
1286 MCSymbol *Sym = CreateSymbol(Name);
1288 if (Lexer.isNot(AsmToken::Comma))
1289 return TokError("unexpected token in '.desc' directive");
1292 SMLoc DescLoc = Lexer.getLoc();
1294 if (ParseAbsoluteExpression(DescValue))
1297 if (Lexer.isNot(AsmToken::EndOfStatement))
1298 return TokError("unexpected token in '.desc' directive");
1302 // Set the n_desc field of this Symbol to this DescValue
1303 Out.EmitSymbolDesc(Sym, DescValue);
1308 /// ParseDirectiveComm
1309 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
1310 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
1311 SMLoc IDLoc = Lexer.getLoc();
1313 if (ParseIdentifier(Name))
1314 return TokError("expected identifier in directive");
1316 // Handle the identifier as the key symbol.
1317 MCSymbol *Sym = CreateSymbol(Name);
1319 if (Lexer.isNot(AsmToken::Comma))
1320 return TokError("unexpected token in directive");
1324 SMLoc SizeLoc = Lexer.getLoc();
1325 if (ParseAbsoluteExpression(Size))
1328 int64_t Pow2Alignment = 0;
1329 SMLoc Pow2AlignmentLoc;
1330 if (Lexer.is(AsmToken::Comma)) {
1332 Pow2AlignmentLoc = Lexer.getLoc();
1333 if (ParseAbsoluteExpression(Pow2Alignment))
1336 // If this target takes alignments in bytes (not log) validate and convert.
1337 if (Lexer.getMAI().getAlignmentIsInBytes()) {
1338 if (!isPowerOf2_64(Pow2Alignment))
1339 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
1340 Pow2Alignment = Log2_64(Pow2Alignment);
1344 if (Lexer.isNot(AsmToken::EndOfStatement))
1345 return TokError("unexpected token in '.comm' or '.lcomm' directive");
1349 // NOTE: a size of zero for a .comm should create a undefined symbol
1350 // but a size of .lcomm creates a bss symbol of size zero.
1352 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
1353 "be less than zero");
1355 // NOTE: The alignment in the directive is a power of 2 value, the assember
1356 // may internally end up wanting an alignment in bytes.
1357 // FIXME: Diagnose overflow.
1358 if (Pow2Alignment < 0)
1359 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
1360 "alignment, can't be less than zero");
1362 if (!Sym->isUndefined())
1363 return Error(IDLoc, "invalid symbol redefinition");
1365 // '.lcomm' is equivalent to '.zerofill'.
1366 // Create the Symbol as a common or local common with Size and Pow2Alignment
1368 Out.EmitZerofill(getMachOSection("__DATA", "__bss",
1369 MCSectionMachO::S_ZEROFILL, 0,
1370 SectionKind::getBSS()),
1371 Sym, Size, 1 << Pow2Alignment);
1375 Out.EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
1379 /// ParseDirectiveDarwinZerofill
1380 /// ::= .zerofill segname , sectname [, identifier , size_expression [
1381 /// , align_expression ]]
1382 bool AsmParser::ParseDirectiveDarwinZerofill() {
1383 // FIXME: Handle quoted names here.
1385 if (Lexer.isNot(AsmToken::Identifier))
1386 return TokError("expected segment name after '.zerofill' directive");
1387 StringRef Segment = getTok().getString();
1390 if (Lexer.isNot(AsmToken::Comma))
1391 return TokError("unexpected token in directive");
1394 if (Lexer.isNot(AsmToken::Identifier))
1395 return TokError("expected section name after comma in '.zerofill' "
1397 StringRef Section = getTok().getString();
1400 // If this is the end of the line all that was wanted was to create the
1401 // the section but with no symbol.
1402 if (Lexer.is(AsmToken::EndOfStatement)) {
1403 // Create the zerofill section but no symbol
1404 Out.EmitZerofill(getMachOSection(Segment, Section,
1405 MCSectionMachO::S_ZEROFILL, 0,
1406 SectionKind::getBSS()));
1410 if (Lexer.isNot(AsmToken::Comma))
1411 return TokError("unexpected token in directive");
1414 if (Lexer.isNot(AsmToken::Identifier))
1415 return TokError("expected identifier in directive");
1417 // handle the identifier as the key symbol.
1418 SMLoc IDLoc = Lexer.getLoc();
1419 MCSymbol *Sym = CreateSymbol(getTok().getString());
1422 if (Lexer.isNot(AsmToken::Comma))
1423 return TokError("unexpected token in directive");
1427 SMLoc SizeLoc = Lexer.getLoc();
1428 if (ParseAbsoluteExpression(Size))
1431 int64_t Pow2Alignment = 0;
1432 SMLoc Pow2AlignmentLoc;
1433 if (Lexer.is(AsmToken::Comma)) {
1435 Pow2AlignmentLoc = Lexer.getLoc();
1436 if (ParseAbsoluteExpression(Pow2Alignment))
1440 if (Lexer.isNot(AsmToken::EndOfStatement))
1441 return TokError("unexpected token in '.zerofill' directive");
1446 return Error(SizeLoc, "invalid '.zerofill' directive size, can't be less "
1449 // NOTE: The alignment in the directive is a power of 2 value, the assember
1450 // may internally end up wanting an alignment in bytes.
1451 // FIXME: Diagnose overflow.
1452 if (Pow2Alignment < 0)
1453 return Error(Pow2AlignmentLoc, "invalid '.zerofill' directive alignment, "
1454 "can't be less than zero");
1456 if (!Sym->isUndefined())
1457 return Error(IDLoc, "invalid symbol redefinition");
1459 // Create the zerofill Symbol with Size and Pow2Alignment
1461 // FIXME: Arch specific.
1462 Out.EmitZerofill(getMachOSection(Segment, Section,
1463 MCSectionMachO::S_ZEROFILL, 0,
1464 SectionKind::getBSS()),
1465 Sym, Size, 1 << Pow2Alignment);
1470 /// ParseDirectiveDarwinSubsectionsViaSymbols
1471 /// ::= .subsections_via_symbols
1472 bool AsmParser::ParseDirectiveDarwinSubsectionsViaSymbols() {
1473 if (Lexer.isNot(AsmToken::EndOfStatement))
1474 return TokError("unexpected token in '.subsections_via_symbols' directive");
1478 Out.EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
1483 /// ParseDirectiveAbort
1484 /// ::= .abort [ "abort_string" ]
1485 bool AsmParser::ParseDirectiveAbort() {
1486 // FIXME: Use loc from directive.
1487 SMLoc Loc = Lexer.getLoc();
1490 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1491 if (Lexer.isNot(AsmToken::String))
1492 return TokError("expected string in '.abort' directive");
1494 Str = getTok().getString();
1499 if (Lexer.isNot(AsmToken::EndOfStatement))
1500 return TokError("unexpected token in '.abort' directive");
1504 // FIXME: Handle here.
1506 Error(Loc, ".abort detected. Assembly stopping.");
1508 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
1513 /// ParseDirectiveLsym
1514 /// ::= .lsym identifier , expression
1515 bool AsmParser::ParseDirectiveDarwinLsym() {
1517 if (ParseIdentifier(Name))
1518 return TokError("expected identifier in directive");
1520 // Handle the identifier as the key symbol.
1521 MCSymbol *Sym = CreateSymbol(Name);
1523 if (Lexer.isNot(AsmToken::Comma))
1524 return TokError("unexpected token in '.lsym' directive");
1527 const MCExpr *Value;
1528 SMLoc StartLoc = Lexer.getLoc();
1529 if (ParseExpression(Value))
1532 if (Lexer.isNot(AsmToken::EndOfStatement))
1533 return TokError("unexpected token in '.lsym' directive");
1537 // We don't currently support this directive.
1539 // FIXME: Diagnostic location!
1541 return TokError("directive '.lsym' is unsupported");
1544 /// ParseDirectiveInclude
1545 /// ::= .include "filename"
1546 bool AsmParser::ParseDirectiveInclude() {
1547 if (Lexer.isNot(AsmToken::String))
1548 return TokError("expected string in '.include' directive");
1550 std::string Filename = getTok().getString();
1551 SMLoc IncludeLoc = Lexer.getLoc();
1554 if (Lexer.isNot(AsmToken::EndOfStatement))
1555 return TokError("unexpected token in '.include' directive");
1557 // Strip the quotes.
1558 Filename = Filename.substr(1, Filename.size()-2);
1560 // Attempt to switch the lexer to the included file before consuming the end
1561 // of statement to avoid losing it when we switch.
1562 if (EnterIncludeFile(Filename)) {
1563 PrintMessage(IncludeLoc,
1564 "Could not find include file '" + Filename + "'",
1572 /// ParseDirectiveDarwinDumpOrLoad
1573 /// ::= ( .dump | .load ) "filename"
1574 bool AsmParser::ParseDirectiveDarwinDumpOrLoad(SMLoc IDLoc, bool IsDump) {
1575 if (Lexer.isNot(AsmToken::String))
1576 return TokError("expected string in '.dump' or '.load' directive");
1580 if (Lexer.isNot(AsmToken::EndOfStatement))
1581 return TokError("unexpected token in '.dump' or '.load' directive");
1585 // FIXME: If/when .dump and .load are implemented they will be done in the
1586 // the assembly parser and not have any need for an MCStreamer API.
1588 Warning(IDLoc, "ignoring directive .dump for now");
1590 Warning(IDLoc, "ignoring directive .load for now");
1595 /// ParseDirectiveIf
1596 /// ::= .if expression
1597 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
1598 // Consume the identifier that was the .if directive
1601 TheCondStack.push_back(TheCondState);
1602 TheCondState.TheCond = AsmCond::IfCond;
1603 if(TheCondState.Ignore) {
1604 EatToEndOfStatement();
1608 if (ParseAbsoluteExpression(ExprValue))
1611 if (Lexer.isNot(AsmToken::EndOfStatement))
1612 return TokError("unexpected token in '.if' directive");
1616 TheCondState.CondMet = ExprValue;
1617 TheCondState.Ignore = !TheCondState.CondMet;
1623 /// ParseDirectiveElseIf
1624 /// ::= .elseif expression
1625 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
1626 if (TheCondState.TheCond != AsmCond::IfCond &&
1627 TheCondState.TheCond != AsmCond::ElseIfCond)
1628 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
1630 TheCondState.TheCond = AsmCond::ElseIfCond;
1632 // Consume the identifier that was the .elseif directive
1635 bool LastIgnoreState = false;
1636 if (!TheCondStack.empty())
1637 LastIgnoreState = TheCondStack.back().Ignore;
1638 if (LastIgnoreState || TheCondState.CondMet) {
1639 TheCondState.Ignore = true;
1640 EatToEndOfStatement();
1644 if (ParseAbsoluteExpression(ExprValue))
1647 if (Lexer.isNot(AsmToken::EndOfStatement))
1648 return TokError("unexpected token in '.elseif' directive");
1651 TheCondState.CondMet = ExprValue;
1652 TheCondState.Ignore = !TheCondState.CondMet;
1658 /// ParseDirectiveElse
1660 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
1661 // Consume the identifier that was the .else directive
1664 if (Lexer.isNot(AsmToken::EndOfStatement))
1665 return TokError("unexpected token in '.else' directive");
1669 if (TheCondState.TheCond != AsmCond::IfCond &&
1670 TheCondState.TheCond != AsmCond::ElseIfCond)
1671 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
1673 TheCondState.TheCond = AsmCond::ElseCond;
1674 bool LastIgnoreState = false;
1675 if (!TheCondStack.empty())
1676 LastIgnoreState = TheCondStack.back().Ignore;
1677 if (LastIgnoreState || TheCondState.CondMet)
1678 TheCondState.Ignore = true;
1680 TheCondState.Ignore = false;
1685 /// ParseDirectiveEndIf
1687 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
1688 // Consume the identifier that was the .endif directive
1691 if (Lexer.isNot(AsmToken::EndOfStatement))
1692 return TokError("unexpected token in '.endif' directive");
1696 if ((TheCondState.TheCond == AsmCond::NoCond) ||
1697 TheCondStack.empty())
1698 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
1700 if (!TheCondStack.empty()) {
1701 TheCondState = TheCondStack.back();
1702 TheCondStack.pop_back();
1708 /// ParseDirectiveFile
1709 /// ::= .file [number] string
1710 bool AsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
1711 // FIXME: I'm not sure what this is.
1712 int64_t FileNumber = -1;
1713 if (Lexer.is(AsmToken::Integer)) {
1714 FileNumber = getTok().getIntVal();
1718 return TokError("file number less than one");
1721 if (Lexer.isNot(AsmToken::String))
1722 return TokError("unexpected token in '.file' directive");
1724 StringRef Filename = getTok().getString();
1725 Filename = Filename.substr(1, Filename.size()-2);
1728 if (Lexer.isNot(AsmToken::EndOfStatement))
1729 return TokError("unexpected token in '.file' directive");
1731 if (FileNumber == -1)
1732 Out.EmitFileDirective(Filename);
1734 Out.EmitDwarfFileDirective(FileNumber, Filename);
1739 /// ParseDirectiveLine
1740 /// ::= .line [number]
1741 bool AsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
1742 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1743 if (Lexer.isNot(AsmToken::Integer))
1744 return TokError("unexpected token in '.line' directive");
1746 int64_t LineNumber = getTok().getIntVal();
1750 // FIXME: Do something with the .line.
1753 if (Lexer.isNot(AsmToken::EndOfStatement))
1754 return TokError("unexpected token in '.file' directive");
1760 /// ParseDirectiveLoc
1761 /// ::= .loc number [number [number]]
1762 bool AsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
1763 if (Lexer.isNot(AsmToken::Integer))
1764 return TokError("unexpected token in '.loc' directive");
1766 // FIXME: What are these fields?
1767 int64_t FileNumber = getTok().getIntVal();
1769 // FIXME: Validate file.
1772 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1773 if (Lexer.isNot(AsmToken::Integer))
1774 return TokError("unexpected token in '.loc' directive");
1776 int64_t Param2 = getTok().getIntVal();
1780 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1781 if (Lexer.isNot(AsmToken::Integer))
1782 return TokError("unexpected token in '.loc' directive");
1784 int64_t Param3 = getTok().getIntVal();
1788 // FIXME: Do something with the .loc.
1792 if (Lexer.isNot(AsmToken::EndOfStatement))
1793 return TokError("unexpected token in '.file' directive");