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/MCValue.h"
24 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
25 #include "llvm/Support/Compiler.h"
26 #include "llvm/Support/SourceMgr.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/Target/TargetAsmParser.h"
32 enum { DEFAULT_ADDRSPACE = 0 };
34 // Mach-O section uniquing.
36 // FIXME: Figure out where this should live, it should be shared by
37 // TargetLoweringObjectFile.
38 typedef StringMap<const MCSectionMachO*> MachOUniqueMapTy;
40 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx, MCStreamer &_Out,
41 const MCAsmInfo &_MAI)
42 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), SrcMgr(_SM), TargetParser(0),
43 CurBuffer(0), SectionUniquingMap(0) {
44 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
46 // Debugging directives.
47 AddDirectiveHandler(".file", &AsmParser::ParseDirectiveFile);
48 AddDirectiveHandler(".line", &AsmParser::ParseDirectiveLine);
49 AddDirectiveHandler(".loc", &AsmParser::ParseDirectiveLoc);
54 AsmParser::~AsmParser() {
55 // If we have the MachO uniquing map, free it.
56 delete (MachOUniqueMapTy*)SectionUniquingMap;
59 const MCSection *AsmParser::getMachOSection(const StringRef &Segment,
60 const StringRef &Section,
61 unsigned TypeAndAttributes,
63 SectionKind Kind) const {
64 // We unique sections by their segment/section pair. The returned section
65 // may not have the same flags as the requested section, if so this should be
66 // diagnosed by the client as an error.
68 // Create the map if it doesn't already exist.
69 if (SectionUniquingMap == 0)
70 SectionUniquingMap = new MachOUniqueMapTy();
71 MachOUniqueMapTy &Map = *(MachOUniqueMapTy*)SectionUniquingMap;
73 // Form the name to look up.
79 // Do the lookup, if we have a hit, return it.
80 const MCSectionMachO *&Entry = Map[Name.str()];
82 // FIXME: This should validate the type and attributes.
83 if (Entry) return Entry;
85 // Otherwise, return a new section.
86 return Entry = MCSectionMachO::Create(Segment, Section, TypeAndAttributes,
87 Reserved2, Kind, Ctx);
90 void AsmParser::Warning(SMLoc L, const Twine &Msg) {
91 PrintMessage(L, Msg.str(), "warning");
94 bool AsmParser::Error(SMLoc L, const Twine &Msg) {
95 PrintMessage(L, Msg.str(), "error");
99 bool AsmParser::TokError(const char *Msg) {
100 PrintMessage(Lexer.getLoc(), Msg, "error");
104 void AsmParser::PrintMessage(SMLoc Loc, const std::string &Msg,
105 const char *Type) const {
106 SrcMgr.PrintMessage(Loc, Msg, Type);
109 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
110 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc());
116 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
121 const AsmToken &AsmParser::Lex() {
122 const AsmToken *tok = &Lexer.Lex();
124 if (tok->is(AsmToken::Eof)) {
125 // If this is the end of an included file, pop the parent file off the
127 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
128 if (ParentIncludeLoc != SMLoc()) {
129 CurBuffer = SrcMgr.FindBufferContainingLoc(ParentIncludeLoc);
130 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer),
131 ParentIncludeLoc.getPointer());
136 if (tok->is(AsmToken::Error))
137 PrintMessage(Lexer.getErrLoc(), Lexer.getErr(), "error");
142 bool AsmParser::Run() {
143 // Create the initial section.
145 // FIXME: Support -n.
146 // FIXME: Target hook & command line option for initial section.
147 Out.SwitchSection(getMachOSection("__TEXT", "__text",
148 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
149 0, SectionKind::getText()));
155 bool HadError = false;
157 AsmCond StartingCondState = TheCondState;
159 // While we have input, parse each statement.
160 while (Lexer.isNot(AsmToken::Eof)) {
161 // Handle conditional assembly here before calling ParseStatement()
162 if (Lexer.getKind() == AsmToken::Identifier) {
163 // If we have an identifier, handle it as the key symbol.
164 AsmToken ID = getTok();
165 SMLoc IDLoc = ID.getLoc();
166 StringRef IDVal = ID.getString();
168 if (IDVal == ".if" ||
169 IDVal == ".elseif" ||
172 if (!ParseConditionalAssemblyDirectives(IDVal, IDLoc))
175 EatToEndOfStatement();
179 if (TheCondState.Ignore) {
180 EatToEndOfStatement();
184 if (!ParseStatement()) continue;
186 // We had an error, remember it and recover by skipping to the next line.
188 EatToEndOfStatement();
191 if (TheCondState.TheCond != StartingCondState.TheCond ||
192 TheCondState.Ignore != StartingCondState.Ignore)
193 return TokError("unmatched .ifs or .elses");
201 /// ParseConditionalAssemblyDirectives - parse the conditional assembly
203 bool AsmParser::ParseConditionalAssemblyDirectives(StringRef Directive,
204 SMLoc DirectiveLoc) {
205 if (Directive == ".if")
206 return ParseDirectiveIf(DirectiveLoc);
207 if (Directive == ".elseif")
208 return ParseDirectiveElseIf(DirectiveLoc);
209 if (Directive == ".else")
210 return ParseDirectiveElse(DirectiveLoc);
211 if (Directive == ".endif")
212 return ParseDirectiveEndIf(DirectiveLoc);
216 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
217 void AsmParser::EatToEndOfStatement() {
218 while (Lexer.isNot(AsmToken::EndOfStatement) &&
219 Lexer.isNot(AsmToken::Eof))
223 if (Lexer.is(AsmToken::EndOfStatement))
228 /// ParseParenExpr - Parse a paren expression and return it.
229 /// NOTE: This assumes the leading '(' has already been consumed.
231 /// parenexpr ::= expr)
233 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
234 if (ParseExpression(Res)) return true;
235 if (Lexer.isNot(AsmToken::RParen))
236 return TokError("expected ')' in parentheses expression");
237 EndLoc = Lexer.getLoc();
242 MCSymbol *AsmParser::CreateSymbol(StringRef Name) {
243 // If the label starts with L it is an assembler temporary label.
244 if (Name.startswith("L"))
245 return Ctx.GetOrCreateTemporarySymbol(Name);
246 return Ctx.GetOrCreateSymbol(Name);
249 /// ParsePrimaryExpr - Parse a primary expression and return it.
250 /// primaryexpr ::= (parenexpr
251 /// primaryexpr ::= symbol
252 /// primaryexpr ::= number
253 /// primaryexpr ::= ~,+,- primaryexpr
254 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
255 switch (Lexer.getKind()) {
257 return TokError("unknown token in expression");
258 case AsmToken::Exclaim:
259 Lex(); // Eat the operator.
260 if (ParsePrimaryExpr(Res, EndLoc))
262 Res = MCUnaryExpr::CreateLNot(Res, getContext());
264 case AsmToken::String:
265 case AsmToken::Identifier: {
266 // This is a symbol reference.
267 MCSymbol *Sym = CreateSymbol(getTok().getIdentifier());
268 EndLoc = Lexer.getLoc();
269 Lex(); // Eat identifier.
271 // If this is an absolute variable reference, substitute it now to preserve
272 // semantics in the face of reassignment.
273 if (Sym->getValue() && isa<MCConstantExpr>(Sym->getValue())) {
274 Res = Sym->getValue();
278 // Otherwise create a symbol ref.
279 Res = MCSymbolRefExpr::Create(Sym, getContext());
282 case AsmToken::Integer:
283 Res = MCConstantExpr::Create(getTok().getIntVal(), getContext());
284 EndLoc = Lexer.getLoc();
287 case AsmToken::LParen:
288 Lex(); // Eat the '('.
289 return ParseParenExpr(Res, EndLoc);
290 case AsmToken::Minus:
291 Lex(); // Eat the operator.
292 if (ParsePrimaryExpr(Res, EndLoc))
294 Res = MCUnaryExpr::CreateMinus(Res, getContext());
297 Lex(); // Eat the operator.
298 if (ParsePrimaryExpr(Res, EndLoc))
300 Res = MCUnaryExpr::CreatePlus(Res, getContext());
302 case AsmToken::Tilde:
303 Lex(); // Eat the operator.
304 if (ParsePrimaryExpr(Res, EndLoc))
306 Res = MCUnaryExpr::CreateNot(Res, getContext());
311 bool AsmParser::ParseExpression(const MCExpr *&Res) {
313 return ParseExpression(Res, EndLoc);
316 /// ParseExpression - Parse an expression and return it.
318 /// expr ::= expr +,- expr -> lowest.
319 /// expr ::= expr |,^,&,! expr -> middle.
320 /// expr ::= expr *,/,%,<<,>> expr -> highest.
321 /// expr ::= primaryexpr
323 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
324 // Parse the expression.
326 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
329 // Try to constant fold it up front, if possible.
331 if (Res->EvaluateAsAbsolute(Value))
332 Res = MCConstantExpr::Create(Value, getContext());
337 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
339 return ParseParenExpr(Res, EndLoc) ||
340 ParseBinOpRHS(1, Res, EndLoc);
343 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
346 SMLoc StartLoc = Lexer.getLoc();
347 if (ParseExpression(Expr))
350 if (!Expr->EvaluateAsAbsolute(Res))
351 return Error(StartLoc, "expected absolute expression");
356 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
357 MCBinaryExpr::Opcode &Kind) {
360 return 0; // not a binop.
362 // Lowest Precedence: &&, ||
363 case AsmToken::AmpAmp:
364 Kind = MCBinaryExpr::LAnd;
366 case AsmToken::PipePipe:
367 Kind = MCBinaryExpr::LOr;
370 // Low Precedence: +, -, ==, !=, <>, <, <=, >, >=
372 Kind = MCBinaryExpr::Add;
374 case AsmToken::Minus:
375 Kind = MCBinaryExpr::Sub;
377 case AsmToken::EqualEqual:
378 Kind = MCBinaryExpr::EQ;
380 case AsmToken::ExclaimEqual:
381 case AsmToken::LessGreater:
382 Kind = MCBinaryExpr::NE;
385 Kind = MCBinaryExpr::LT;
387 case AsmToken::LessEqual:
388 Kind = MCBinaryExpr::LTE;
390 case AsmToken::Greater:
391 Kind = MCBinaryExpr::GT;
393 case AsmToken::GreaterEqual:
394 Kind = MCBinaryExpr::GTE;
397 // Intermediate Precedence: |, &, ^
399 // FIXME: gas seems to support '!' as an infix operator?
401 Kind = MCBinaryExpr::Or;
403 case AsmToken::Caret:
404 Kind = MCBinaryExpr::Xor;
407 Kind = MCBinaryExpr::And;
410 // Highest Precedence: *, /, %, <<, >>
412 Kind = MCBinaryExpr::Mul;
414 case AsmToken::Slash:
415 Kind = MCBinaryExpr::Div;
417 case AsmToken::Percent:
418 Kind = MCBinaryExpr::Mod;
420 case AsmToken::LessLess:
421 Kind = MCBinaryExpr::Shl;
423 case AsmToken::GreaterGreater:
424 Kind = MCBinaryExpr::Shr;
430 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
431 /// Res contains the LHS of the expression on input.
432 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
435 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
436 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
438 // If the next token is lower precedence than we are allowed to eat, return
439 // successfully with what we ate already.
440 if (TokPrec < Precedence)
445 // Eat the next primary expression.
447 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
449 // If BinOp binds less tightly with RHS than the operator after RHS, let
450 // the pending operator take RHS as its LHS.
451 MCBinaryExpr::Opcode Dummy;
452 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
453 if (TokPrec < NextTokPrec) {
454 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
457 // Merge LHS and RHS according to operator.
458 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
466 /// ::= EndOfStatement
467 /// ::= Label* Directive ...Operands... EndOfStatement
468 /// ::= Label* Identifier OperandList* EndOfStatement
469 bool AsmParser::ParseStatement() {
470 if (Lexer.is(AsmToken::EndOfStatement)) {
475 // Statements always start with an identifier.
476 AsmToken ID = getTok();
477 SMLoc IDLoc = ID.getLoc();
479 if (ParseIdentifier(IDVal))
480 return TokError("unexpected token at start of statement");
482 // FIXME: Recurse on local labels?
484 // See what kind of statement we have.
485 switch (Lexer.getKind()) {
486 case AsmToken::Colon: {
487 // identifier ':' -> Label.
490 // Diagnose attempt to use a variable as a label.
492 // FIXME: Diagnostics. Note the location of the definition as a label.
493 // FIXME: This doesn't diagnose assignment to a symbol which has been
494 // implicitly marked as external.
495 MCSymbol *Sym = CreateSymbol(IDVal);
496 if (!Sym->isUndefined())
497 return Error(IDLoc, "invalid symbol redefinition");
502 return ParseStatement();
505 case AsmToken::Equal:
506 // identifier '=' ... -> assignment statement
509 return ParseAssignment(IDVal);
511 default: // Normal instruction or directive.
515 // Otherwise, we have a normal instruction or directive.
516 if (IDVal[0] == '.') {
517 // FIXME: This should be driven based on a hash lookup and callback.
518 if (IDVal == ".section")
519 return ParseDirectiveDarwinSection();
520 if (IDVal == ".text")
521 // FIXME: This changes behavior based on the -static flag to the
523 return ParseDirectiveSectionSwitch("__TEXT", "__text",
524 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS);
525 if (IDVal == ".const")
526 return ParseDirectiveSectionSwitch("__TEXT", "__const");
527 if (IDVal == ".static_const")
528 return ParseDirectiveSectionSwitch("__TEXT", "__static_const");
529 if (IDVal == ".cstring")
530 return ParseDirectiveSectionSwitch("__TEXT","__cstring",
531 MCSectionMachO::S_CSTRING_LITERALS);
532 if (IDVal == ".literal4")
533 return ParseDirectiveSectionSwitch("__TEXT", "__literal4",
534 MCSectionMachO::S_4BYTE_LITERALS,
536 if (IDVal == ".literal8")
537 return ParseDirectiveSectionSwitch("__TEXT", "__literal8",
538 MCSectionMachO::S_8BYTE_LITERALS,
540 if (IDVal == ".literal16")
541 return ParseDirectiveSectionSwitch("__TEXT","__literal16",
542 MCSectionMachO::S_16BYTE_LITERALS,
544 if (IDVal == ".constructor")
545 return ParseDirectiveSectionSwitch("__TEXT","__constructor");
546 if (IDVal == ".destructor")
547 return ParseDirectiveSectionSwitch("__TEXT","__destructor");
548 if (IDVal == ".fvmlib_init0")
549 return ParseDirectiveSectionSwitch("__TEXT","__fvmlib_init0");
550 if (IDVal == ".fvmlib_init1")
551 return ParseDirectiveSectionSwitch("__TEXT","__fvmlib_init1");
553 // FIXME: The assembler manual claims that this has the self modify code
554 // flag, at least on x86-32, but that does not appear to be correct.
555 if (IDVal == ".symbol_stub")
556 return ParseDirectiveSectionSwitch("__TEXT","__symbol_stub",
557 MCSectionMachO::S_SYMBOL_STUBS |
558 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
559 // FIXME: Different on PPC and ARM.
561 // FIXME: PowerPC only?
562 if (IDVal == ".picsymbol_stub")
563 return ParseDirectiveSectionSwitch("__TEXT","__picsymbol_stub",
564 MCSectionMachO::S_SYMBOL_STUBS |
565 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
567 if (IDVal == ".data")
568 return ParseDirectiveSectionSwitch("__DATA", "__data");
569 if (IDVal == ".static_data")
570 return ParseDirectiveSectionSwitch("__DATA", "__static_data");
572 // FIXME: The section names of these two are misspelled in the assembler
574 if (IDVal == ".non_lazy_symbol_pointer")
575 return ParseDirectiveSectionSwitch("__DATA", "__nl_symbol_ptr",
576 MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS,
578 if (IDVal == ".lazy_symbol_pointer")
579 return ParseDirectiveSectionSwitch("__DATA", "__la_symbol_ptr",
580 MCSectionMachO::S_LAZY_SYMBOL_POINTERS,
583 if (IDVal == ".dyld")
584 return ParseDirectiveSectionSwitch("__DATA", "__dyld");
585 if (IDVal == ".mod_init_func")
586 return ParseDirectiveSectionSwitch("__DATA", "__mod_init_func",
587 MCSectionMachO::S_MOD_INIT_FUNC_POINTERS,
589 if (IDVal == ".mod_term_func")
590 return ParseDirectiveSectionSwitch("__DATA", "__mod_term_func",
591 MCSectionMachO::S_MOD_TERM_FUNC_POINTERS,
593 if (IDVal == ".const_data")
594 return ParseDirectiveSectionSwitch("__DATA", "__const");
597 if (IDVal == ".objc_class")
598 return ParseDirectiveSectionSwitch("__OBJC", "__class",
599 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
600 if (IDVal == ".objc_meta_class")
601 return ParseDirectiveSectionSwitch("__OBJC", "__meta_class",
602 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
603 if (IDVal == ".objc_cat_cls_meth")
604 return ParseDirectiveSectionSwitch("__OBJC", "__cat_cls_meth",
605 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
606 if (IDVal == ".objc_cat_inst_meth")
607 return ParseDirectiveSectionSwitch("__OBJC", "__cat_inst_meth",
608 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
609 if (IDVal == ".objc_protocol")
610 return ParseDirectiveSectionSwitch("__OBJC", "__protocol",
611 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
612 if (IDVal == ".objc_string_object")
613 return ParseDirectiveSectionSwitch("__OBJC", "__string_object",
614 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
615 if (IDVal == ".objc_cls_meth")
616 return ParseDirectiveSectionSwitch("__OBJC", "__cls_meth",
617 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
618 if (IDVal == ".objc_inst_meth")
619 return ParseDirectiveSectionSwitch("__OBJC", "__inst_meth",
620 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
621 if (IDVal == ".objc_cls_refs")
622 return ParseDirectiveSectionSwitch("__OBJC", "__cls_refs",
623 MCSectionMachO::S_ATTR_NO_DEAD_STRIP |
624 MCSectionMachO::S_LITERAL_POINTERS,
626 if (IDVal == ".objc_message_refs")
627 return ParseDirectiveSectionSwitch("__OBJC", "__message_refs",
628 MCSectionMachO::S_ATTR_NO_DEAD_STRIP |
629 MCSectionMachO::S_LITERAL_POINTERS,
631 if (IDVal == ".objc_symbols")
632 return ParseDirectiveSectionSwitch("__OBJC", "__symbols",
633 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
634 if (IDVal == ".objc_category")
635 return ParseDirectiveSectionSwitch("__OBJC", "__category",
636 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
637 if (IDVal == ".objc_class_vars")
638 return ParseDirectiveSectionSwitch("__OBJC", "__class_vars",
639 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
640 if (IDVal == ".objc_instance_vars")
641 return ParseDirectiveSectionSwitch("__OBJC", "__instance_vars",
642 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
643 if (IDVal == ".objc_module_info")
644 return ParseDirectiveSectionSwitch("__OBJC", "__module_info",
645 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
646 if (IDVal == ".objc_class_names")
647 return ParseDirectiveSectionSwitch("__TEXT", "__cstring",
648 MCSectionMachO::S_CSTRING_LITERALS);
649 if (IDVal == ".objc_meth_var_types")
650 return ParseDirectiveSectionSwitch("__TEXT", "__cstring",
651 MCSectionMachO::S_CSTRING_LITERALS);
652 if (IDVal == ".objc_meth_var_names")
653 return ParseDirectiveSectionSwitch("__TEXT", "__cstring",
654 MCSectionMachO::S_CSTRING_LITERALS);
655 if (IDVal == ".objc_selector_strs")
656 return ParseDirectiveSectionSwitch("__OBJC", "__selector_strs",
657 MCSectionMachO::S_CSTRING_LITERALS);
659 // Assembler features
661 return ParseDirectiveSet();
665 if (IDVal == ".ascii")
666 return ParseDirectiveAscii(false);
667 if (IDVal == ".asciz")
668 return ParseDirectiveAscii(true);
670 if (IDVal == ".byte")
671 return ParseDirectiveValue(1);
672 if (IDVal == ".short")
673 return ParseDirectiveValue(2);
674 if (IDVal == ".long")
675 return ParseDirectiveValue(4);
676 if (IDVal == ".quad")
677 return ParseDirectiveValue(8);
679 // FIXME: Target hooks for IsPow2.
680 if (IDVal == ".align")
681 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
682 if (IDVal == ".align32")
683 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
684 if (IDVal == ".balign")
685 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
686 if (IDVal == ".balignw")
687 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
688 if (IDVal == ".balignl")
689 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
690 if (IDVal == ".p2align")
691 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
692 if (IDVal == ".p2alignw")
693 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
694 if (IDVal == ".p2alignl")
695 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
698 return ParseDirectiveOrg();
700 if (IDVal == ".fill")
701 return ParseDirectiveFill();
702 if (IDVal == ".space")
703 return ParseDirectiveSpace();
705 // Symbol attribute directives
707 if (IDVal == ".globl" || IDVal == ".global")
708 return ParseDirectiveSymbolAttribute(MCSA_Global);
709 if (IDVal == ".hidden")
710 return ParseDirectiveSymbolAttribute(MCSA_Hidden);
711 if (IDVal == ".indirect_symbol")
712 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
713 if (IDVal == ".internal")
714 return ParseDirectiveSymbolAttribute(MCSA_Internal);
715 if (IDVal == ".lazy_reference")
716 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
717 if (IDVal == ".no_dead_strip")
718 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
719 if (IDVal == ".private_extern")
720 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
721 if (IDVal == ".protected")
722 return ParseDirectiveSymbolAttribute(MCSA_Protected);
723 if (IDVal == ".reference")
724 return ParseDirectiveSymbolAttribute(MCSA_Reference);
725 if (IDVal == ".weak")
726 return ParseDirectiveSymbolAttribute(MCSA_Weak);
727 if (IDVal == ".weak_definition")
728 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
729 if (IDVal == ".weak_reference")
730 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
732 if (IDVal == ".comm")
733 return ParseDirectiveComm(/*IsLocal=*/false);
734 if (IDVal == ".lcomm")
735 return ParseDirectiveComm(/*IsLocal=*/true);
736 if (IDVal == ".zerofill")
737 return ParseDirectiveDarwinZerofill();
738 if (IDVal == ".desc")
739 return ParseDirectiveDarwinSymbolDesc();
740 if (IDVal == ".lsym")
741 return ParseDirectiveDarwinLsym();
743 if (IDVal == ".subsections_via_symbols")
744 return ParseDirectiveDarwinSubsectionsViaSymbols();
745 if (IDVal == ".abort")
746 return ParseDirectiveAbort();
747 if (IDVal == ".include")
748 return ParseDirectiveInclude();
749 if (IDVal == ".dump")
750 return ParseDirectiveDarwinDumpOrLoad(IDLoc, /*IsDump=*/true);
751 if (IDVal == ".load")
752 return ParseDirectiveDarwinDumpOrLoad(IDLoc, /*IsLoad=*/false);
754 // Look up the handler in the handler table,
755 bool(AsmParser::*Handler)(StringRef, SMLoc) = DirectiveMap[IDVal];
757 return (this->*Handler)(IDVal, IDLoc);
759 // Target hook for parsing target specific directives.
760 if (!getTargetParser().ParseDirective(ID))
763 Warning(IDLoc, "ignoring directive for now");
764 EatToEndOfStatement();
769 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
770 if (getTargetParser().ParseInstruction(IDVal, IDLoc, ParsedOperands))
771 // FIXME: Leaking ParsedOperands on failure.
774 if (Lexer.isNot(AsmToken::EndOfStatement))
775 // FIXME: Leaking ParsedOperands on failure.
776 return TokError("unexpected token in argument list");
778 // Eat the end of statement marker.
784 bool MatchFail = getTargetParser().MatchInstruction(ParsedOperands, Inst);
786 // Free any parsed operands.
787 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
788 delete ParsedOperands[i];
791 // FIXME: We should give nicer diagnostics about the exact failure.
792 Error(IDLoc, "unrecognized instruction");
796 // Instruction is good, process it.
797 Out.EmitInstruction(Inst);
799 // Skip to end of line for now.
803 bool AsmParser::ParseAssignment(const StringRef &Name) {
804 // FIXME: Use better location, we should use proper tokens.
805 SMLoc EqualLoc = Lexer.getLoc();
808 SMLoc StartLoc = Lexer.getLoc();
809 if (ParseExpression(Value))
812 if (Lexer.isNot(AsmToken::EndOfStatement))
813 return TokError("unexpected token in assignment");
815 // Eat the end of statement marker.
818 // Validate that the LHS is allowed to be a variable (either it has not been
819 // used as a symbol, or it is an absolute symbol).
820 MCSymbol *Sym = getContext().LookupSymbol(Name);
822 // Diagnose assignment to a label.
824 // FIXME: Diagnostics. Note the location of the definition as a label.
825 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
826 if (!Sym->isUndefined() && !Sym->isAbsolute())
827 return Error(EqualLoc, "redefinition of '" + Name + "'");
828 else if (!Sym->isVariable())
829 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
830 else if (!isa<MCConstantExpr>(Sym->getValue()))
831 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
834 Sym = CreateSymbol(Name);
836 // FIXME: Handle '.'.
838 // Do the assignment.
839 Out.EmitAssignment(Sym, Value);
847 bool AsmParser::ParseIdentifier(StringRef &Res) {
848 if (Lexer.isNot(AsmToken::Identifier) &&
849 Lexer.isNot(AsmToken::String))
852 Res = getTok().getIdentifier();
854 Lex(); // Consume the identifier token.
859 /// ParseDirectiveSet:
860 /// ::= .set identifier ',' expression
861 bool AsmParser::ParseDirectiveSet() {
864 if (ParseIdentifier(Name))
865 return TokError("expected identifier after '.set' directive");
867 if (Lexer.isNot(AsmToken::Comma))
868 return TokError("unexpected token in '.set'");
871 return ParseAssignment(Name);
874 /// ParseDirectiveSection:
875 /// ::= .section identifier (',' identifier)*
876 /// FIXME: This should actually parse out the segment, section, attributes and
877 /// sizeof_stub fields.
878 bool AsmParser::ParseDirectiveDarwinSection() {
879 SMLoc Loc = Lexer.getLoc();
881 StringRef SectionName;
882 if (ParseIdentifier(SectionName))
883 return Error(Loc, "expected identifier after '.section' directive");
885 // Verify there is a following comma.
886 if (!Lexer.is(AsmToken::Comma))
887 return TokError("unexpected token in '.section' directive");
889 std::string SectionSpec = SectionName;
892 // Add all the tokens until the end of the line, ParseSectionSpecifier will
894 StringRef EOL = Lexer.LexUntilEndOfStatement();
895 SectionSpec.append(EOL.begin(), EOL.end());
898 if (Lexer.isNot(AsmToken::EndOfStatement))
899 return TokError("unexpected token in '.section' directive");
903 StringRef Segment, Section;
904 unsigned TAA, StubSize;
905 std::string ErrorStr =
906 MCSectionMachO::ParseSectionSpecifier(SectionSpec, Segment, Section,
909 if (!ErrorStr.empty())
910 return Error(Loc, ErrorStr.c_str());
912 // FIXME: Arch specific.
913 bool isText = Segment == "__TEXT"; // FIXME: Hack.
914 Out.SwitchSection(getMachOSection(Segment, Section, TAA, StubSize,
915 isText ? SectionKind::getText()
916 : SectionKind::getDataRel()));
920 /// ParseDirectiveSectionSwitch -
921 bool AsmParser::ParseDirectiveSectionSwitch(const char *Segment,
923 unsigned TAA, unsigned Align,
925 if (Lexer.isNot(AsmToken::EndOfStatement))
926 return TokError("unexpected token in section switching directive");
929 // FIXME: Arch specific.
930 bool isText = StringRef(Segment) == "__TEXT"; // FIXME: Hack.
931 Out.SwitchSection(getMachOSection(Segment, Section, TAA, StubSize,
932 isText ? SectionKind::getText()
933 : SectionKind::getDataRel()));
935 // Set the implicit alignment, if any.
937 // FIXME: This isn't really what 'as' does; I think it just uses the implicit
938 // alignment on the section (e.g., if one manually inserts bytes into the
939 // section, then just issueing the section switch directive will not realign
940 // the section. However, this is arguably more reasonable behavior, and there
941 // is no good reason for someone to intentionally emit incorrectly sized
942 // values into the implicitly aligned sections.
944 Out.EmitValueToAlignment(Align, 0, 1, 0);
949 bool AsmParser::ParseEscapedString(std::string &Data) {
950 assert(Lexer.is(AsmToken::String) && "Unexpected current token!");
953 StringRef Str = getTok().getStringContents();
954 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
955 if (Str[i] != '\\') {
960 // Recognize escaped characters. Note that this escape semantics currently
961 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
964 return TokError("unexpected backslash at end of string");
966 // Recognize octal sequences.
967 if ((unsigned) (Str[i] - '0') <= 7) {
968 // Consume up to three octal characters.
969 unsigned Value = Str[i] - '0';
971 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
973 Value = Value * 8 + (Str[i] - '0');
975 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
977 Value = Value * 8 + (Str[i] - '0');
982 return TokError("invalid octal escape sequence (out of range)");
984 Data += (unsigned char) Value;
988 // Otherwise recognize individual escapes.
991 // Just reject invalid escape sequences for now.
992 return TokError("invalid escape sequence (unrecognized character)");
994 case 'b': Data += '\b'; break;
995 case 'f': Data += '\f'; break;
996 case 'n': Data += '\n'; break;
997 case 'r': Data += '\r'; break;
998 case 't': Data += '\t'; break;
999 case '"': Data += '"'; break;
1000 case '\\': Data += '\\'; break;
1007 /// ParseDirectiveAscii:
1008 /// ::= ( .ascii | .asciz ) [ "string" ( , "string" )* ]
1009 bool AsmParser::ParseDirectiveAscii(bool ZeroTerminated) {
1010 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1012 if (Lexer.isNot(AsmToken::String))
1013 return TokError("expected string in '.ascii' or '.asciz' directive");
1016 if (ParseEscapedString(Data))
1019 Out.EmitBytes(Data, DEFAULT_ADDRSPACE);
1021 Out.EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1025 if (Lexer.is(AsmToken::EndOfStatement))
1028 if (Lexer.isNot(AsmToken::Comma))
1029 return TokError("unexpected token in '.ascii' or '.asciz' directive");
1038 /// ParseDirectiveValue
1039 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1040 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1041 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1043 const MCExpr *Value;
1044 SMLoc ATTRIBUTE_UNUSED StartLoc = Lexer.getLoc();
1045 if (ParseExpression(Value))
1048 Out.EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1050 if (Lexer.is(AsmToken::EndOfStatement))
1053 // FIXME: Improve diagnostic.
1054 if (Lexer.isNot(AsmToken::Comma))
1055 return TokError("unexpected token in directive");
1064 /// ParseDirectiveSpace
1065 /// ::= .space expression [ , expression ]
1066 bool AsmParser::ParseDirectiveSpace() {
1068 if (ParseAbsoluteExpression(NumBytes))
1071 int64_t FillExpr = 0;
1072 bool HasFillExpr = false;
1073 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1074 if (Lexer.isNot(AsmToken::Comma))
1075 return TokError("unexpected token in '.space' directive");
1078 if (ParseAbsoluteExpression(FillExpr))
1083 if (Lexer.isNot(AsmToken::EndOfStatement))
1084 return TokError("unexpected token in '.space' directive");
1090 return TokError("invalid number of bytes in '.space' directive");
1092 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1093 Out.EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1098 /// ParseDirectiveFill
1099 /// ::= .fill expression , expression , expression
1100 bool AsmParser::ParseDirectiveFill() {
1102 if (ParseAbsoluteExpression(NumValues))
1105 if (Lexer.isNot(AsmToken::Comma))
1106 return TokError("unexpected token in '.fill' directive");
1110 if (ParseAbsoluteExpression(FillSize))
1113 if (Lexer.isNot(AsmToken::Comma))
1114 return TokError("unexpected token in '.fill' directive");
1118 if (ParseAbsoluteExpression(FillExpr))
1121 if (Lexer.isNot(AsmToken::EndOfStatement))
1122 return TokError("unexpected token in '.fill' directive");
1126 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1127 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1129 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1130 Out.EmitValue(MCConstantExpr::Create(FillExpr, getContext()), FillSize,
1136 /// ParseDirectiveOrg
1137 /// ::= .org expression [ , expression ]
1138 bool AsmParser::ParseDirectiveOrg() {
1139 const MCExpr *Offset;
1140 SMLoc StartLoc = Lexer.getLoc();
1141 if (ParseExpression(Offset))
1144 // Parse optional fill expression.
1145 int64_t FillExpr = 0;
1146 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1147 if (Lexer.isNot(AsmToken::Comma))
1148 return TokError("unexpected token in '.org' directive");
1151 if (ParseAbsoluteExpression(FillExpr))
1154 if (Lexer.isNot(AsmToken::EndOfStatement))
1155 return TokError("unexpected token in '.org' directive");
1160 // FIXME: Only limited forms of relocatable expressions are accepted here, it
1161 // has to be relative to the current section.
1162 Out.EmitValueToOffset(Offset, FillExpr);
1167 /// ParseDirectiveAlign
1168 /// ::= {.align, ...} expression [ , expression [ , expression ]]
1169 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1170 SMLoc AlignmentLoc = Lexer.getLoc();
1172 if (ParseAbsoluteExpression(Alignment))
1176 bool HasFillExpr = false;
1177 int64_t FillExpr = 0;
1178 int64_t MaxBytesToFill = 0;
1179 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1180 if (Lexer.isNot(AsmToken::Comma))
1181 return TokError("unexpected token in directive");
1184 // The fill expression can be omitted while specifying a maximum number of
1185 // alignment bytes, e.g:
1187 if (Lexer.isNot(AsmToken::Comma)) {
1189 if (ParseAbsoluteExpression(FillExpr))
1193 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1194 if (Lexer.isNot(AsmToken::Comma))
1195 return TokError("unexpected token in directive");
1198 MaxBytesLoc = Lexer.getLoc();
1199 if (ParseAbsoluteExpression(MaxBytesToFill))
1202 if (Lexer.isNot(AsmToken::EndOfStatement))
1203 return TokError("unexpected token in directive");
1210 // FIXME: Sometimes fill with nop.
1214 // Compute alignment in bytes.
1216 // FIXME: Diagnose overflow.
1217 if (Alignment >= 32) {
1218 Error(AlignmentLoc, "invalid alignment value");
1222 Alignment = 1ULL << Alignment;
1225 // Diagnose non-sensical max bytes to align.
1226 if (MaxBytesLoc.isValid()) {
1227 if (MaxBytesToFill < 1) {
1228 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
1229 "many bytes, ignoring maximum bytes expression");
1233 if (MaxBytesToFill >= Alignment) {
1234 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
1240 // FIXME: hard code the parser to use EmitCodeAlignment for text when using
1241 // the TextAlignFillValue.
1242 if(Out.getCurrentSection()->getKind().isText() &&
1243 Lexer.getMAI().getTextAlignFillValue() == FillExpr)
1244 Out.EmitCodeAlignment(Alignment, MaxBytesToFill);
1246 // FIXME: Target specific behavior about how the "extra" bytes are filled.
1247 Out.EmitValueToAlignment(Alignment, FillExpr, ValueSize, MaxBytesToFill);
1252 /// ParseDirectiveSymbolAttribute
1253 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
1254 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
1255 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1259 if (ParseIdentifier(Name))
1260 return TokError("expected identifier in directive");
1262 MCSymbol *Sym = CreateSymbol(Name);
1264 Out.EmitSymbolAttribute(Sym, Attr);
1266 if (Lexer.is(AsmToken::EndOfStatement))
1269 if (Lexer.isNot(AsmToken::Comma))
1270 return TokError("unexpected token in directive");
1279 /// ParseDirectiveDarwinSymbolDesc
1280 /// ::= .desc identifier , expression
1281 bool AsmParser::ParseDirectiveDarwinSymbolDesc() {
1283 if (ParseIdentifier(Name))
1284 return TokError("expected identifier in directive");
1286 // Handle the identifier as the key symbol.
1287 MCSymbol *Sym = CreateSymbol(Name);
1289 if (Lexer.isNot(AsmToken::Comma))
1290 return TokError("unexpected token in '.desc' directive");
1293 SMLoc DescLoc = Lexer.getLoc();
1295 if (ParseAbsoluteExpression(DescValue))
1298 if (Lexer.isNot(AsmToken::EndOfStatement))
1299 return TokError("unexpected token in '.desc' directive");
1303 // Set the n_desc field of this Symbol to this DescValue
1304 Out.EmitSymbolDesc(Sym, DescValue);
1309 /// ParseDirectiveComm
1310 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
1311 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
1312 SMLoc IDLoc = Lexer.getLoc();
1314 if (ParseIdentifier(Name))
1315 return TokError("expected identifier in directive");
1317 // Handle the identifier as the key symbol.
1318 MCSymbol *Sym = CreateSymbol(Name);
1320 if (Lexer.isNot(AsmToken::Comma))
1321 return TokError("unexpected token in directive");
1325 SMLoc SizeLoc = Lexer.getLoc();
1326 if (ParseAbsoluteExpression(Size))
1329 int64_t Pow2Alignment = 0;
1330 SMLoc Pow2AlignmentLoc;
1331 if (Lexer.is(AsmToken::Comma)) {
1333 Pow2AlignmentLoc = Lexer.getLoc();
1334 if (ParseAbsoluteExpression(Pow2Alignment))
1337 // If this target takes alignments in bytes (not log) validate and convert.
1338 if (Lexer.getMAI().getAlignmentIsInBytes()) {
1339 if (!isPowerOf2_64(Pow2Alignment))
1340 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
1341 Pow2Alignment = Log2_64(Pow2Alignment);
1345 if (Lexer.isNot(AsmToken::EndOfStatement))
1346 return TokError("unexpected token in '.comm' or '.lcomm' directive");
1350 // NOTE: a size of zero for a .comm should create a undefined symbol
1351 // but a size of .lcomm creates a bss symbol of size zero.
1353 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
1354 "be less than zero");
1356 // NOTE: The alignment in the directive is a power of 2 value, the assember
1357 // may internally end up wanting an alignment in bytes.
1358 // FIXME: Diagnose overflow.
1359 if (Pow2Alignment < 0)
1360 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
1361 "alignment, can't be less than zero");
1363 if (!Sym->isUndefined())
1364 return Error(IDLoc, "invalid symbol redefinition");
1366 // '.lcomm' is equivalent to '.zerofill'.
1367 // Create the Symbol as a common or local common with Size and Pow2Alignment
1369 Out.EmitZerofill(getMachOSection("__DATA", "__bss",
1370 MCSectionMachO::S_ZEROFILL, 0,
1371 SectionKind::getBSS()),
1372 Sym, Size, 1 << Pow2Alignment);
1376 Out.EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
1380 /// ParseDirectiveDarwinZerofill
1381 /// ::= .zerofill segname , sectname [, identifier , size_expression [
1382 /// , align_expression ]]
1383 bool AsmParser::ParseDirectiveDarwinZerofill() {
1384 // FIXME: Handle quoted names here.
1386 if (Lexer.isNot(AsmToken::Identifier))
1387 return TokError("expected segment name after '.zerofill' directive");
1388 StringRef Segment = getTok().getString();
1391 if (Lexer.isNot(AsmToken::Comma))
1392 return TokError("unexpected token in directive");
1395 if (Lexer.isNot(AsmToken::Identifier))
1396 return TokError("expected section name after comma in '.zerofill' "
1398 StringRef Section = getTok().getString();
1401 // If this is the end of the line all that was wanted was to create the
1402 // the section but with no symbol.
1403 if (Lexer.is(AsmToken::EndOfStatement)) {
1404 // Create the zerofill section but no symbol
1405 Out.EmitZerofill(getMachOSection(Segment, Section,
1406 MCSectionMachO::S_ZEROFILL, 0,
1407 SectionKind::getBSS()));
1411 if (Lexer.isNot(AsmToken::Comma))
1412 return TokError("unexpected token in directive");
1415 if (Lexer.isNot(AsmToken::Identifier))
1416 return TokError("expected identifier in directive");
1418 // handle the identifier as the key symbol.
1419 SMLoc IDLoc = Lexer.getLoc();
1420 MCSymbol *Sym = CreateSymbol(getTok().getString());
1423 if (Lexer.isNot(AsmToken::Comma))
1424 return TokError("unexpected token in directive");
1428 SMLoc SizeLoc = Lexer.getLoc();
1429 if (ParseAbsoluteExpression(Size))
1432 int64_t Pow2Alignment = 0;
1433 SMLoc Pow2AlignmentLoc;
1434 if (Lexer.is(AsmToken::Comma)) {
1436 Pow2AlignmentLoc = Lexer.getLoc();
1437 if (ParseAbsoluteExpression(Pow2Alignment))
1441 if (Lexer.isNot(AsmToken::EndOfStatement))
1442 return TokError("unexpected token in '.zerofill' directive");
1447 return Error(SizeLoc, "invalid '.zerofill' directive size, can't be less "
1450 // NOTE: The alignment in the directive is a power of 2 value, the assember
1451 // may internally end up wanting an alignment in bytes.
1452 // FIXME: Diagnose overflow.
1453 if (Pow2Alignment < 0)
1454 return Error(Pow2AlignmentLoc, "invalid '.zerofill' directive alignment, "
1455 "can't be less than zero");
1457 if (!Sym->isUndefined())
1458 return Error(IDLoc, "invalid symbol redefinition");
1460 // Create the zerofill Symbol with Size and Pow2Alignment
1462 // FIXME: Arch specific.
1463 Out.EmitZerofill(getMachOSection(Segment, Section,
1464 MCSectionMachO::S_ZEROFILL, 0,
1465 SectionKind::getBSS()),
1466 Sym, Size, 1 << Pow2Alignment);
1471 /// ParseDirectiveDarwinSubsectionsViaSymbols
1472 /// ::= .subsections_via_symbols
1473 bool AsmParser::ParseDirectiveDarwinSubsectionsViaSymbols() {
1474 if (Lexer.isNot(AsmToken::EndOfStatement))
1475 return TokError("unexpected token in '.subsections_via_symbols' directive");
1479 Out.EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
1484 /// ParseDirectiveAbort
1485 /// ::= .abort [ "abort_string" ]
1486 bool AsmParser::ParseDirectiveAbort() {
1487 // FIXME: Use loc from directive.
1488 SMLoc Loc = Lexer.getLoc();
1491 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1492 if (Lexer.isNot(AsmToken::String))
1493 return TokError("expected string in '.abort' directive");
1495 Str = getTok().getString();
1500 if (Lexer.isNot(AsmToken::EndOfStatement))
1501 return TokError("unexpected token in '.abort' directive");
1505 // FIXME: Handle here.
1507 Error(Loc, ".abort detected. Assembly stopping.");
1509 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
1514 /// ParseDirectiveLsym
1515 /// ::= .lsym identifier , expression
1516 bool AsmParser::ParseDirectiveDarwinLsym() {
1518 if (ParseIdentifier(Name))
1519 return TokError("expected identifier in directive");
1521 // Handle the identifier as the key symbol.
1522 MCSymbol *Sym = CreateSymbol(Name);
1524 if (Lexer.isNot(AsmToken::Comma))
1525 return TokError("unexpected token in '.lsym' directive");
1528 const MCExpr *Value;
1529 SMLoc StartLoc = Lexer.getLoc();
1530 if (ParseExpression(Value))
1533 if (Lexer.isNot(AsmToken::EndOfStatement))
1534 return TokError("unexpected token in '.lsym' directive");
1538 // We don't currently support this directive.
1540 // FIXME: Diagnostic location!
1542 return TokError("directive '.lsym' is unsupported");
1545 /// ParseDirectiveInclude
1546 /// ::= .include "filename"
1547 bool AsmParser::ParseDirectiveInclude() {
1548 if (Lexer.isNot(AsmToken::String))
1549 return TokError("expected string in '.include' directive");
1551 std::string Filename = getTok().getString();
1552 SMLoc IncludeLoc = Lexer.getLoc();
1555 if (Lexer.isNot(AsmToken::EndOfStatement))
1556 return TokError("unexpected token in '.include' directive");
1558 // Strip the quotes.
1559 Filename = Filename.substr(1, Filename.size()-2);
1561 // Attempt to switch the lexer to the included file before consuming the end
1562 // of statement to avoid losing it when we switch.
1563 if (EnterIncludeFile(Filename)) {
1564 PrintMessage(IncludeLoc,
1565 "Could not find include file '" + Filename + "'",
1573 /// ParseDirectiveDarwinDumpOrLoad
1574 /// ::= ( .dump | .load ) "filename"
1575 bool AsmParser::ParseDirectiveDarwinDumpOrLoad(SMLoc IDLoc, bool IsDump) {
1576 if (Lexer.isNot(AsmToken::String))
1577 return TokError("expected string in '.dump' or '.load' directive");
1581 if (Lexer.isNot(AsmToken::EndOfStatement))
1582 return TokError("unexpected token in '.dump' or '.load' directive");
1586 // FIXME: If/when .dump and .load are implemented they will be done in the
1587 // the assembly parser and not have any need for an MCStreamer API.
1589 Warning(IDLoc, "ignoring directive .dump for now");
1591 Warning(IDLoc, "ignoring directive .load for now");
1596 /// ParseDirectiveIf
1597 /// ::= .if expression
1598 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
1599 // Consume the identifier that was the .if directive
1602 TheCondStack.push_back(TheCondState);
1603 TheCondState.TheCond = AsmCond::IfCond;
1604 if(TheCondState.Ignore) {
1605 EatToEndOfStatement();
1609 if (ParseAbsoluteExpression(ExprValue))
1612 if (Lexer.isNot(AsmToken::EndOfStatement))
1613 return TokError("unexpected token in '.if' directive");
1617 TheCondState.CondMet = ExprValue;
1618 TheCondState.Ignore = !TheCondState.CondMet;
1624 /// ParseDirectiveElseIf
1625 /// ::= .elseif expression
1626 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
1627 if (TheCondState.TheCond != AsmCond::IfCond &&
1628 TheCondState.TheCond != AsmCond::ElseIfCond)
1629 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
1631 TheCondState.TheCond = AsmCond::ElseIfCond;
1633 // Consume the identifier that was the .elseif directive
1636 bool LastIgnoreState = false;
1637 if (!TheCondStack.empty())
1638 LastIgnoreState = TheCondStack.back().Ignore;
1639 if (LastIgnoreState || TheCondState.CondMet) {
1640 TheCondState.Ignore = true;
1641 EatToEndOfStatement();
1645 if (ParseAbsoluteExpression(ExprValue))
1648 if (Lexer.isNot(AsmToken::EndOfStatement))
1649 return TokError("unexpected token in '.elseif' directive");
1652 TheCondState.CondMet = ExprValue;
1653 TheCondState.Ignore = !TheCondState.CondMet;
1659 /// ParseDirectiveElse
1661 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
1662 // Consume the identifier that was the .else directive
1665 if (Lexer.isNot(AsmToken::EndOfStatement))
1666 return TokError("unexpected token in '.else' directive");
1670 if (TheCondState.TheCond != AsmCond::IfCond &&
1671 TheCondState.TheCond != AsmCond::ElseIfCond)
1672 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
1674 TheCondState.TheCond = AsmCond::ElseCond;
1675 bool LastIgnoreState = false;
1676 if (!TheCondStack.empty())
1677 LastIgnoreState = TheCondStack.back().Ignore;
1678 if (LastIgnoreState || TheCondState.CondMet)
1679 TheCondState.Ignore = true;
1681 TheCondState.Ignore = false;
1686 /// ParseDirectiveEndIf
1688 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
1689 // Consume the identifier that was the .endif directive
1692 if (Lexer.isNot(AsmToken::EndOfStatement))
1693 return TokError("unexpected token in '.endif' directive");
1697 if ((TheCondState.TheCond == AsmCond::NoCond) ||
1698 TheCondStack.empty())
1699 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
1701 if (!TheCondStack.empty()) {
1702 TheCondState = TheCondStack.back();
1703 TheCondStack.pop_back();
1709 /// ParseDirectiveFile
1710 /// ::= .file [number] string
1711 bool AsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
1712 // FIXME: I'm not sure what this is.
1713 int64_t FileNumber = -1;
1714 if (Lexer.is(AsmToken::Integer)) {
1715 FileNumber = getTok().getIntVal();
1719 return TokError("file number less than one");
1722 if (Lexer.isNot(AsmToken::String))
1723 return TokError("unexpected token in '.file' directive");
1725 StringRef Filename = getTok().getString();
1726 Filename = Filename.substr(1, Filename.size()-2);
1729 if (Lexer.isNot(AsmToken::EndOfStatement))
1730 return TokError("unexpected token in '.file' directive");
1732 if (FileNumber == -1)
1733 Out.EmitFileDirective(Filename);
1735 Out.EmitDwarfFileDirective(FileNumber, Filename);
1740 /// ParseDirectiveLine
1741 /// ::= .line [number]
1742 bool AsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
1743 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1744 if (Lexer.isNot(AsmToken::Integer))
1745 return TokError("unexpected token in '.line' directive");
1747 int64_t LineNumber = getTok().getIntVal();
1751 // FIXME: Do something with the .line.
1754 if (Lexer.isNot(AsmToken::EndOfStatement))
1755 return TokError("unexpected token in '.file' directive");
1761 /// ParseDirectiveLoc
1762 /// ::= .loc number [number [number]]
1763 bool AsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
1764 if (Lexer.isNot(AsmToken::Integer))
1765 return TokError("unexpected token in '.loc' directive");
1767 // FIXME: What are these fields?
1768 int64_t FileNumber = getTok().getIntVal();
1770 // FIXME: Validate file.
1773 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1774 if (Lexer.isNot(AsmToken::Integer))
1775 return TokError("unexpected token in '.loc' directive");
1777 int64_t Param2 = getTok().getIntVal();
1781 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1782 if (Lexer.isNot(AsmToken::Integer))
1783 return TokError("unexpected token in '.loc' directive");
1785 int64_t Param3 = getTok().getIntVal();
1789 // FIXME: Do something with the .loc.
1793 if (Lexer.isNot(AsmToken::EndOfStatement))
1794 return TokError("unexpected token in '.file' directive");