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 (MCSymbol *S = Ctx.LookupSymbol(Name))
246 // If the label starts with L it is an assembler temporary label.
247 if (Name.startswith("L"))
248 return Ctx.CreateTemporarySymbol(Name);
250 return Ctx.CreateSymbol(Name);
253 /// ParsePrimaryExpr - Parse a primary expression and return it.
254 /// primaryexpr ::= (parenexpr
255 /// primaryexpr ::= symbol
256 /// primaryexpr ::= number
257 /// primaryexpr ::= ~,+,- primaryexpr
258 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
259 switch (Lexer.getKind()) {
261 return TokError("unknown token in expression");
262 case AsmToken::Exclaim:
263 Lex(); // Eat the operator.
264 if (ParsePrimaryExpr(Res, EndLoc))
266 Res = MCUnaryExpr::CreateLNot(Res, getContext());
268 case AsmToken::String:
269 case AsmToken::Identifier: {
270 // This is a symbol reference.
271 MCSymbol *Sym = CreateSymbol(getTok().getIdentifier());
272 EndLoc = Lexer.getLoc();
273 Lex(); // Eat identifier.
275 // If this is an absolute variable reference, substitute it now to preserve
276 // semantics in the face of reassignment.
277 if (Sym->getValue() && isa<MCConstantExpr>(Sym->getValue())) {
278 Res = Sym->getValue();
282 // Otherwise create a symbol ref.
283 Res = MCSymbolRefExpr::Create(Sym, getContext());
286 case AsmToken::Integer:
287 Res = MCConstantExpr::Create(getTok().getIntVal(), getContext());
288 EndLoc = Lexer.getLoc();
291 case AsmToken::LParen:
292 Lex(); // Eat the '('.
293 return ParseParenExpr(Res, EndLoc);
294 case AsmToken::Minus:
295 Lex(); // Eat the operator.
296 if (ParsePrimaryExpr(Res, EndLoc))
298 Res = MCUnaryExpr::CreateMinus(Res, getContext());
301 Lex(); // Eat the operator.
302 if (ParsePrimaryExpr(Res, EndLoc))
304 Res = MCUnaryExpr::CreatePlus(Res, getContext());
306 case AsmToken::Tilde:
307 Lex(); // Eat the operator.
308 if (ParsePrimaryExpr(Res, EndLoc))
310 Res = MCUnaryExpr::CreateNot(Res, getContext());
315 bool AsmParser::ParseExpression(const MCExpr *&Res) {
317 return ParseExpression(Res, EndLoc);
320 /// ParseExpression - Parse an expression and return it.
322 /// expr ::= expr +,- expr -> lowest.
323 /// expr ::= expr |,^,&,! expr -> middle.
324 /// expr ::= expr *,/,%,<<,>> expr -> highest.
325 /// expr ::= primaryexpr
327 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
328 // Parse the expression.
330 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
333 // Try to constant fold it up front, if possible.
335 if (Res->EvaluateAsAbsolute(Value))
336 Res = MCConstantExpr::Create(Value, getContext());
341 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
343 return ParseParenExpr(Res, EndLoc) ||
344 ParseBinOpRHS(1, Res, EndLoc);
347 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
350 SMLoc StartLoc = Lexer.getLoc();
351 if (ParseExpression(Expr))
354 if (!Expr->EvaluateAsAbsolute(Res))
355 return Error(StartLoc, "expected absolute expression");
360 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
361 MCBinaryExpr::Opcode &Kind) {
364 return 0; // not a binop.
366 // Lowest Precedence: &&, ||
367 case AsmToken::AmpAmp:
368 Kind = MCBinaryExpr::LAnd;
370 case AsmToken::PipePipe:
371 Kind = MCBinaryExpr::LOr;
374 // Low Precedence: +, -, ==, !=, <>, <, <=, >, >=
376 Kind = MCBinaryExpr::Add;
378 case AsmToken::Minus:
379 Kind = MCBinaryExpr::Sub;
381 case AsmToken::EqualEqual:
382 Kind = MCBinaryExpr::EQ;
384 case AsmToken::ExclaimEqual:
385 case AsmToken::LessGreater:
386 Kind = MCBinaryExpr::NE;
389 Kind = MCBinaryExpr::LT;
391 case AsmToken::LessEqual:
392 Kind = MCBinaryExpr::LTE;
394 case AsmToken::Greater:
395 Kind = MCBinaryExpr::GT;
397 case AsmToken::GreaterEqual:
398 Kind = MCBinaryExpr::GTE;
401 // Intermediate Precedence: |, &, ^
403 // FIXME: gas seems to support '!' as an infix operator?
405 Kind = MCBinaryExpr::Or;
407 case AsmToken::Caret:
408 Kind = MCBinaryExpr::Xor;
411 Kind = MCBinaryExpr::And;
414 // Highest Precedence: *, /, %, <<, >>
416 Kind = MCBinaryExpr::Mul;
418 case AsmToken::Slash:
419 Kind = MCBinaryExpr::Div;
421 case AsmToken::Percent:
422 Kind = MCBinaryExpr::Mod;
424 case AsmToken::LessLess:
425 Kind = MCBinaryExpr::Shl;
427 case AsmToken::GreaterGreater:
428 Kind = MCBinaryExpr::Shr;
434 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
435 /// Res contains the LHS of the expression on input.
436 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
439 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
440 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
442 // If the next token is lower precedence than we are allowed to eat, return
443 // successfully with what we ate already.
444 if (TokPrec < Precedence)
449 // Eat the next primary expression.
451 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
453 // If BinOp binds less tightly with RHS than the operator after RHS, let
454 // the pending operator take RHS as its LHS.
455 MCBinaryExpr::Opcode Dummy;
456 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
457 if (TokPrec < NextTokPrec) {
458 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
461 // Merge LHS and RHS according to operator.
462 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
470 /// ::= EndOfStatement
471 /// ::= Label* Directive ...Operands... EndOfStatement
472 /// ::= Label* Identifier OperandList* EndOfStatement
473 bool AsmParser::ParseStatement() {
474 if (Lexer.is(AsmToken::EndOfStatement)) {
479 // Statements always start with an identifier.
480 AsmToken ID = getTok();
481 SMLoc IDLoc = ID.getLoc();
483 if (ParseIdentifier(IDVal))
484 return TokError("unexpected token at start of statement");
486 // FIXME: Recurse on local labels?
488 // See what kind of statement we have.
489 switch (Lexer.getKind()) {
490 case AsmToken::Colon: {
491 // identifier ':' -> Label.
494 // Diagnose attempt to use a variable as a label.
496 // FIXME: Diagnostics. Note the location of the definition as a label.
497 // FIXME: This doesn't diagnose assignment to a symbol which has been
498 // implicitly marked as external.
499 MCSymbol *Sym = CreateSymbol(IDVal);
500 if (!Sym->isUndefined())
501 return Error(IDLoc, "invalid symbol redefinition");
506 return ParseStatement();
509 case AsmToken::Equal:
510 // identifier '=' ... -> assignment statement
513 return ParseAssignment(IDVal);
515 default: // Normal instruction or directive.
519 // Otherwise, we have a normal instruction or directive.
520 if (IDVal[0] == '.') {
521 // FIXME: This should be driven based on a hash lookup and callback.
522 if (IDVal == ".section")
523 return ParseDirectiveDarwinSection();
524 if (IDVal == ".text")
525 // FIXME: This changes behavior based on the -static flag to the
527 return ParseDirectiveSectionSwitch("__TEXT", "__text",
528 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS);
529 if (IDVal == ".const")
530 return ParseDirectiveSectionSwitch("__TEXT", "__const");
531 if (IDVal == ".static_const")
532 return ParseDirectiveSectionSwitch("__TEXT", "__static_const");
533 if (IDVal == ".cstring")
534 return ParseDirectiveSectionSwitch("__TEXT","__cstring",
535 MCSectionMachO::S_CSTRING_LITERALS);
536 if (IDVal == ".literal4")
537 return ParseDirectiveSectionSwitch("__TEXT", "__literal4",
538 MCSectionMachO::S_4BYTE_LITERALS,
540 if (IDVal == ".literal8")
541 return ParseDirectiveSectionSwitch("__TEXT", "__literal8",
542 MCSectionMachO::S_8BYTE_LITERALS,
544 if (IDVal == ".literal16")
545 return ParseDirectiveSectionSwitch("__TEXT","__literal16",
546 MCSectionMachO::S_16BYTE_LITERALS,
548 if (IDVal == ".constructor")
549 return ParseDirectiveSectionSwitch("__TEXT","__constructor");
550 if (IDVal == ".destructor")
551 return ParseDirectiveSectionSwitch("__TEXT","__destructor");
552 if (IDVal == ".fvmlib_init0")
553 return ParseDirectiveSectionSwitch("__TEXT","__fvmlib_init0");
554 if (IDVal == ".fvmlib_init1")
555 return ParseDirectiveSectionSwitch("__TEXT","__fvmlib_init1");
557 // FIXME: The assembler manual claims that this has the self modify code
558 // flag, at least on x86-32, but that does not appear to be correct.
559 if (IDVal == ".symbol_stub")
560 return ParseDirectiveSectionSwitch("__TEXT","__symbol_stub",
561 MCSectionMachO::S_SYMBOL_STUBS |
562 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
563 // FIXME: Different on PPC and ARM.
565 // FIXME: PowerPC only?
566 if (IDVal == ".picsymbol_stub")
567 return ParseDirectiveSectionSwitch("__TEXT","__picsymbol_stub",
568 MCSectionMachO::S_SYMBOL_STUBS |
569 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
571 if (IDVal == ".data")
572 return ParseDirectiveSectionSwitch("__DATA", "__data");
573 if (IDVal == ".static_data")
574 return ParseDirectiveSectionSwitch("__DATA", "__static_data");
576 // FIXME: The section names of these two are misspelled in the assembler
578 if (IDVal == ".non_lazy_symbol_pointer")
579 return ParseDirectiveSectionSwitch("__DATA", "__nl_symbol_ptr",
580 MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS,
582 if (IDVal == ".lazy_symbol_pointer")
583 return ParseDirectiveSectionSwitch("__DATA", "__la_symbol_ptr",
584 MCSectionMachO::S_LAZY_SYMBOL_POINTERS,
587 if (IDVal == ".dyld")
588 return ParseDirectiveSectionSwitch("__DATA", "__dyld");
589 if (IDVal == ".mod_init_func")
590 return ParseDirectiveSectionSwitch("__DATA", "__mod_init_func",
591 MCSectionMachO::S_MOD_INIT_FUNC_POINTERS,
593 if (IDVal == ".mod_term_func")
594 return ParseDirectiveSectionSwitch("__DATA", "__mod_term_func",
595 MCSectionMachO::S_MOD_TERM_FUNC_POINTERS,
597 if (IDVal == ".const_data")
598 return ParseDirectiveSectionSwitch("__DATA", "__const");
601 if (IDVal == ".objc_class")
602 return ParseDirectiveSectionSwitch("__OBJC", "__class",
603 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
604 if (IDVal == ".objc_meta_class")
605 return ParseDirectiveSectionSwitch("__OBJC", "__meta_class",
606 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
607 if (IDVal == ".objc_cat_cls_meth")
608 return ParseDirectiveSectionSwitch("__OBJC", "__cat_cls_meth",
609 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
610 if (IDVal == ".objc_cat_inst_meth")
611 return ParseDirectiveSectionSwitch("__OBJC", "__cat_inst_meth",
612 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
613 if (IDVal == ".objc_protocol")
614 return ParseDirectiveSectionSwitch("__OBJC", "__protocol",
615 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
616 if (IDVal == ".objc_string_object")
617 return ParseDirectiveSectionSwitch("__OBJC", "__string_object",
618 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
619 if (IDVal == ".objc_cls_meth")
620 return ParseDirectiveSectionSwitch("__OBJC", "__cls_meth",
621 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
622 if (IDVal == ".objc_inst_meth")
623 return ParseDirectiveSectionSwitch("__OBJC", "__inst_meth",
624 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
625 if (IDVal == ".objc_cls_refs")
626 return ParseDirectiveSectionSwitch("__OBJC", "__cls_refs",
627 MCSectionMachO::S_ATTR_NO_DEAD_STRIP |
628 MCSectionMachO::S_LITERAL_POINTERS,
630 if (IDVal == ".objc_message_refs")
631 return ParseDirectiveSectionSwitch("__OBJC", "__message_refs",
632 MCSectionMachO::S_ATTR_NO_DEAD_STRIP |
633 MCSectionMachO::S_LITERAL_POINTERS,
635 if (IDVal == ".objc_symbols")
636 return ParseDirectiveSectionSwitch("__OBJC", "__symbols",
637 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
638 if (IDVal == ".objc_category")
639 return ParseDirectiveSectionSwitch("__OBJC", "__category",
640 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
641 if (IDVal == ".objc_class_vars")
642 return ParseDirectiveSectionSwitch("__OBJC", "__class_vars",
643 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
644 if (IDVal == ".objc_instance_vars")
645 return ParseDirectiveSectionSwitch("__OBJC", "__instance_vars",
646 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
647 if (IDVal == ".objc_module_info")
648 return ParseDirectiveSectionSwitch("__OBJC", "__module_info",
649 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
650 if (IDVal == ".objc_class_names")
651 return ParseDirectiveSectionSwitch("__TEXT", "__cstring",
652 MCSectionMachO::S_CSTRING_LITERALS);
653 if (IDVal == ".objc_meth_var_types")
654 return ParseDirectiveSectionSwitch("__TEXT", "__cstring",
655 MCSectionMachO::S_CSTRING_LITERALS);
656 if (IDVal == ".objc_meth_var_names")
657 return ParseDirectiveSectionSwitch("__TEXT", "__cstring",
658 MCSectionMachO::S_CSTRING_LITERALS);
659 if (IDVal == ".objc_selector_strs")
660 return ParseDirectiveSectionSwitch("__OBJC", "__selector_strs",
661 MCSectionMachO::S_CSTRING_LITERALS);
663 // Assembler features
665 return ParseDirectiveSet();
669 if (IDVal == ".ascii")
670 return ParseDirectiveAscii(false);
671 if (IDVal == ".asciz")
672 return ParseDirectiveAscii(true);
674 if (IDVal == ".byte")
675 return ParseDirectiveValue(1);
676 if (IDVal == ".short")
677 return ParseDirectiveValue(2);
678 if (IDVal == ".long")
679 return ParseDirectiveValue(4);
680 if (IDVal == ".quad")
681 return ParseDirectiveValue(8);
683 // FIXME: Target hooks for IsPow2.
684 if (IDVal == ".align")
685 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
686 if (IDVal == ".align32")
687 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
688 if (IDVal == ".balign")
689 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
690 if (IDVal == ".balignw")
691 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
692 if (IDVal == ".balignl")
693 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
694 if (IDVal == ".p2align")
695 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
696 if (IDVal == ".p2alignw")
697 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
698 if (IDVal == ".p2alignl")
699 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
702 return ParseDirectiveOrg();
704 if (IDVal == ".fill")
705 return ParseDirectiveFill();
706 if (IDVal == ".space")
707 return ParseDirectiveSpace();
709 // Symbol attribute directives
711 if (IDVal == ".globl" || IDVal == ".global")
712 return ParseDirectiveSymbolAttribute(MCSA_Global);
713 if (IDVal == ".hidden")
714 return ParseDirectiveSymbolAttribute(MCSA_Hidden);
715 if (IDVal == ".indirect_symbol")
716 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
717 if (IDVal == ".internal")
718 return ParseDirectiveSymbolAttribute(MCSA_Internal);
719 if (IDVal == ".lazy_reference")
720 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
721 if (IDVal == ".no_dead_strip")
722 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
723 if (IDVal == ".private_extern")
724 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
725 if (IDVal == ".protected")
726 return ParseDirectiveSymbolAttribute(MCSA_Protected);
727 if (IDVal == ".reference")
728 return ParseDirectiveSymbolAttribute(MCSA_Reference);
729 if (IDVal == ".weak")
730 return ParseDirectiveSymbolAttribute(MCSA_Weak);
731 if (IDVal == ".weak_definition")
732 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
733 if (IDVal == ".weak_reference")
734 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
736 if (IDVal == ".comm")
737 return ParseDirectiveComm(/*IsLocal=*/false);
738 if (IDVal == ".lcomm")
739 return ParseDirectiveComm(/*IsLocal=*/true);
740 if (IDVal == ".zerofill")
741 return ParseDirectiveDarwinZerofill();
742 if (IDVal == ".desc")
743 return ParseDirectiveDarwinSymbolDesc();
744 if (IDVal == ".lsym")
745 return ParseDirectiveDarwinLsym();
747 if (IDVal == ".subsections_via_symbols")
748 return ParseDirectiveDarwinSubsectionsViaSymbols();
749 if (IDVal == ".abort")
750 return ParseDirectiveAbort();
751 if (IDVal == ".include")
752 return ParseDirectiveInclude();
753 if (IDVal == ".dump")
754 return ParseDirectiveDarwinDumpOrLoad(IDLoc, /*IsDump=*/true);
755 if (IDVal == ".load")
756 return ParseDirectiveDarwinDumpOrLoad(IDLoc, /*IsLoad=*/false);
758 // Look up the handler in the handler table,
759 bool(AsmParser::*Handler)(StringRef, SMLoc) = DirectiveMap[IDVal];
761 return (this->*Handler)(IDVal, IDLoc);
763 // Target hook for parsing target specific directives.
764 if (!getTargetParser().ParseDirective(ID))
767 Warning(IDLoc, "ignoring directive for now");
768 EatToEndOfStatement();
773 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
774 if (getTargetParser().ParseInstruction(IDVal, IDLoc, ParsedOperands))
775 // FIXME: Leaking ParsedOperands on failure.
778 if (Lexer.isNot(AsmToken::EndOfStatement))
779 // FIXME: Leaking ParsedOperands on failure.
780 return TokError("unexpected token in argument list");
782 // Eat the end of statement marker.
788 bool MatchFail = getTargetParser().MatchInstruction(ParsedOperands, Inst);
790 // Free any parsed operands.
791 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
792 delete ParsedOperands[i];
795 // FIXME: We should give nicer diagnostics about the exact failure.
796 Error(IDLoc, "unrecognized instruction");
800 // Instruction is good, process it.
801 Out.EmitInstruction(Inst);
803 // Skip to end of line for now.
807 bool AsmParser::ParseAssignment(const StringRef &Name) {
808 // FIXME: Use better location, we should use proper tokens.
809 SMLoc EqualLoc = Lexer.getLoc();
812 SMLoc StartLoc = Lexer.getLoc();
813 if (ParseExpression(Value))
816 if (Lexer.isNot(AsmToken::EndOfStatement))
817 return TokError("unexpected token in assignment");
819 // Eat the end of statement marker.
822 // Validate that the LHS is allowed to be a variable (either it has not been
823 // used as a symbol, or it is an absolute symbol).
824 MCSymbol *Sym = getContext().LookupSymbol(Name);
826 // Diagnose assignment to a label.
828 // FIXME: Diagnostics. Note the location of the definition as a label.
829 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
830 if (!Sym->isUndefined() && !Sym->isAbsolute())
831 return Error(EqualLoc, "redefinition of '" + Name + "'");
832 else if (!Sym->isVariable())
833 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
834 else if (!isa<MCConstantExpr>(Sym->getValue()))
835 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
838 Sym = CreateSymbol(Name);
840 // FIXME: Handle '.'.
842 // Do the assignment.
843 Out.EmitAssignment(Sym, Value);
851 bool AsmParser::ParseIdentifier(StringRef &Res) {
852 if (Lexer.isNot(AsmToken::Identifier) &&
853 Lexer.isNot(AsmToken::String))
856 Res = getTok().getIdentifier();
858 Lex(); // Consume the identifier token.
863 /// ParseDirectiveSet:
864 /// ::= .set identifier ',' expression
865 bool AsmParser::ParseDirectiveSet() {
868 if (ParseIdentifier(Name))
869 return TokError("expected identifier after '.set' directive");
871 if (Lexer.isNot(AsmToken::Comma))
872 return TokError("unexpected token in '.set'");
875 return ParseAssignment(Name);
878 /// ParseDirectiveSection:
879 /// ::= .section identifier (',' identifier)*
880 /// FIXME: This should actually parse out the segment, section, attributes and
881 /// sizeof_stub fields.
882 bool AsmParser::ParseDirectiveDarwinSection() {
883 SMLoc Loc = Lexer.getLoc();
885 StringRef SectionName;
886 if (ParseIdentifier(SectionName))
887 return Error(Loc, "expected identifier after '.section' directive");
889 // Verify there is a following comma.
890 if (!Lexer.is(AsmToken::Comma))
891 return TokError("unexpected token in '.section' directive");
893 std::string SectionSpec = SectionName;
896 // Add all the tokens until the end of the line, ParseSectionSpecifier will
898 StringRef EOL = Lexer.LexUntilEndOfStatement();
899 SectionSpec.append(EOL.begin(), EOL.end());
902 if (Lexer.isNot(AsmToken::EndOfStatement))
903 return TokError("unexpected token in '.section' directive");
907 StringRef Segment, Section;
908 unsigned TAA, StubSize;
909 std::string ErrorStr =
910 MCSectionMachO::ParseSectionSpecifier(SectionSpec, Segment, Section,
913 if (!ErrorStr.empty())
914 return Error(Loc, ErrorStr.c_str());
916 // FIXME: Arch specific.
917 bool isText = Segment == "__TEXT"; // FIXME: Hack.
918 Out.SwitchSection(getMachOSection(Segment, Section, TAA, StubSize,
919 isText ? SectionKind::getText()
920 : SectionKind::getDataRel()));
924 /// ParseDirectiveSectionSwitch -
925 bool AsmParser::ParseDirectiveSectionSwitch(const char *Segment,
927 unsigned TAA, unsigned Align,
929 if (Lexer.isNot(AsmToken::EndOfStatement))
930 return TokError("unexpected token in section switching directive");
933 // FIXME: Arch specific.
934 bool isText = StringRef(Segment) == "__TEXT"; // FIXME: Hack.
935 Out.SwitchSection(getMachOSection(Segment, Section, TAA, StubSize,
936 isText ? SectionKind::getText()
937 : SectionKind::getDataRel()));
939 // Set the implicit alignment, if any.
941 // FIXME: This isn't really what 'as' does; I think it just uses the implicit
942 // alignment on the section (e.g., if one manually inserts bytes into the
943 // section, then just issueing the section switch directive will not realign
944 // the section. However, this is arguably more reasonable behavior, and there
945 // is no good reason for someone to intentionally emit incorrectly sized
946 // values into the implicitly aligned sections.
948 Out.EmitValueToAlignment(Align, 0, 1, 0);
953 bool AsmParser::ParseEscapedString(std::string &Data) {
954 assert(Lexer.is(AsmToken::String) && "Unexpected current token!");
957 StringRef Str = getTok().getStringContents();
958 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
959 if (Str[i] != '\\') {
964 // Recognize escaped characters. Note that this escape semantics currently
965 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
968 return TokError("unexpected backslash at end of string");
970 // Recognize octal sequences.
971 if ((unsigned) (Str[i] - '0') <= 7) {
972 // Consume up to three octal characters.
973 unsigned Value = Str[i] - '0';
975 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
977 Value = Value * 8 + (Str[i] - '0');
979 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
981 Value = Value * 8 + (Str[i] - '0');
986 return TokError("invalid octal escape sequence (out of range)");
988 Data += (unsigned char) Value;
992 // Otherwise recognize individual escapes.
995 // Just reject invalid escape sequences for now.
996 return TokError("invalid escape sequence (unrecognized character)");
998 case 'b': Data += '\b'; break;
999 case 'f': Data += '\f'; break;
1000 case 'n': Data += '\n'; break;
1001 case 'r': Data += '\r'; break;
1002 case 't': Data += '\t'; break;
1003 case '"': Data += '"'; break;
1004 case '\\': Data += '\\'; break;
1011 /// ParseDirectiveAscii:
1012 /// ::= ( .ascii | .asciz ) [ "string" ( , "string" )* ]
1013 bool AsmParser::ParseDirectiveAscii(bool ZeroTerminated) {
1014 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1016 if (Lexer.isNot(AsmToken::String))
1017 return TokError("expected string in '.ascii' or '.asciz' directive");
1020 if (ParseEscapedString(Data))
1023 Out.EmitBytes(Data, DEFAULT_ADDRSPACE);
1025 Out.EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1029 if (Lexer.is(AsmToken::EndOfStatement))
1032 if (Lexer.isNot(AsmToken::Comma))
1033 return TokError("unexpected token in '.ascii' or '.asciz' directive");
1042 /// ParseDirectiveValue
1043 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1044 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1045 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1047 const MCExpr *Value;
1048 SMLoc ATTRIBUTE_UNUSED StartLoc = Lexer.getLoc();
1049 if (ParseExpression(Value))
1052 Out.EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1054 if (Lexer.is(AsmToken::EndOfStatement))
1057 // FIXME: Improve diagnostic.
1058 if (Lexer.isNot(AsmToken::Comma))
1059 return TokError("unexpected token in directive");
1068 /// ParseDirectiveSpace
1069 /// ::= .space expression [ , expression ]
1070 bool AsmParser::ParseDirectiveSpace() {
1072 if (ParseAbsoluteExpression(NumBytes))
1075 int64_t FillExpr = 0;
1076 bool HasFillExpr = false;
1077 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1078 if (Lexer.isNot(AsmToken::Comma))
1079 return TokError("unexpected token in '.space' directive");
1082 if (ParseAbsoluteExpression(FillExpr))
1087 if (Lexer.isNot(AsmToken::EndOfStatement))
1088 return TokError("unexpected token in '.space' directive");
1094 return TokError("invalid number of bytes in '.space' directive");
1096 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1097 Out.EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1102 /// ParseDirectiveFill
1103 /// ::= .fill expression , expression , expression
1104 bool AsmParser::ParseDirectiveFill() {
1106 if (ParseAbsoluteExpression(NumValues))
1109 if (Lexer.isNot(AsmToken::Comma))
1110 return TokError("unexpected token in '.fill' directive");
1114 if (ParseAbsoluteExpression(FillSize))
1117 if (Lexer.isNot(AsmToken::Comma))
1118 return TokError("unexpected token in '.fill' directive");
1122 if (ParseAbsoluteExpression(FillExpr))
1125 if (Lexer.isNot(AsmToken::EndOfStatement))
1126 return TokError("unexpected token in '.fill' directive");
1130 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1131 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1133 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1134 Out.EmitValue(MCConstantExpr::Create(FillExpr, getContext()), FillSize,
1140 /// ParseDirectiveOrg
1141 /// ::= .org expression [ , expression ]
1142 bool AsmParser::ParseDirectiveOrg() {
1143 const MCExpr *Offset;
1144 SMLoc StartLoc = Lexer.getLoc();
1145 if (ParseExpression(Offset))
1148 // Parse optional fill expression.
1149 int64_t FillExpr = 0;
1150 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1151 if (Lexer.isNot(AsmToken::Comma))
1152 return TokError("unexpected token in '.org' directive");
1155 if (ParseAbsoluteExpression(FillExpr))
1158 if (Lexer.isNot(AsmToken::EndOfStatement))
1159 return TokError("unexpected token in '.org' directive");
1164 // FIXME: Only limited forms of relocatable expressions are accepted here, it
1165 // has to be relative to the current section.
1166 Out.EmitValueToOffset(Offset, FillExpr);
1171 /// ParseDirectiveAlign
1172 /// ::= {.align, ...} expression [ , expression [ , expression ]]
1173 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1174 SMLoc AlignmentLoc = Lexer.getLoc();
1176 if (ParseAbsoluteExpression(Alignment))
1180 bool HasFillExpr = false;
1181 int64_t FillExpr = 0;
1182 int64_t MaxBytesToFill = 0;
1183 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1184 if (Lexer.isNot(AsmToken::Comma))
1185 return TokError("unexpected token in directive");
1188 // The fill expression can be omitted while specifying a maximum number of
1189 // alignment bytes, e.g:
1191 if (Lexer.isNot(AsmToken::Comma)) {
1193 if (ParseAbsoluteExpression(FillExpr))
1197 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1198 if (Lexer.isNot(AsmToken::Comma))
1199 return TokError("unexpected token in directive");
1202 MaxBytesLoc = Lexer.getLoc();
1203 if (ParseAbsoluteExpression(MaxBytesToFill))
1206 if (Lexer.isNot(AsmToken::EndOfStatement))
1207 return TokError("unexpected token in directive");
1214 // FIXME: Sometimes fill with nop.
1218 // Compute alignment in bytes.
1220 // FIXME: Diagnose overflow.
1221 if (Alignment >= 32) {
1222 Error(AlignmentLoc, "invalid alignment value");
1226 Alignment = 1ULL << Alignment;
1229 // Diagnose non-sensical max bytes to align.
1230 if (MaxBytesLoc.isValid()) {
1231 if (MaxBytesToFill < 1) {
1232 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
1233 "many bytes, ignoring maximum bytes expression");
1237 if (MaxBytesToFill >= Alignment) {
1238 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
1244 // FIXME: hard code the parser to use EmitCodeAlignment for text when using
1245 // the TextAlignFillValue.
1246 if(Out.getCurrentSection()->getKind().isText() &&
1247 Lexer.getMAI().getTextAlignFillValue() == FillExpr)
1248 Out.EmitCodeAlignment(Alignment, MaxBytesToFill);
1250 // FIXME: Target specific behavior about how the "extra" bytes are filled.
1251 Out.EmitValueToAlignment(Alignment, FillExpr, ValueSize, MaxBytesToFill);
1256 /// ParseDirectiveSymbolAttribute
1257 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
1258 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
1259 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1263 if (ParseIdentifier(Name))
1264 return TokError("expected identifier in directive");
1266 MCSymbol *Sym = CreateSymbol(Name);
1268 Out.EmitSymbolAttribute(Sym, Attr);
1270 if (Lexer.is(AsmToken::EndOfStatement))
1273 if (Lexer.isNot(AsmToken::Comma))
1274 return TokError("unexpected token in directive");
1283 /// ParseDirectiveDarwinSymbolDesc
1284 /// ::= .desc identifier , expression
1285 bool AsmParser::ParseDirectiveDarwinSymbolDesc() {
1287 if (ParseIdentifier(Name))
1288 return TokError("expected identifier in directive");
1290 // Handle the identifier as the key symbol.
1291 MCSymbol *Sym = CreateSymbol(Name);
1293 if (Lexer.isNot(AsmToken::Comma))
1294 return TokError("unexpected token in '.desc' directive");
1297 SMLoc DescLoc = Lexer.getLoc();
1299 if (ParseAbsoluteExpression(DescValue))
1302 if (Lexer.isNot(AsmToken::EndOfStatement))
1303 return TokError("unexpected token in '.desc' directive");
1307 // Set the n_desc field of this Symbol to this DescValue
1308 Out.EmitSymbolDesc(Sym, DescValue);
1313 /// ParseDirectiveComm
1314 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
1315 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
1316 SMLoc IDLoc = Lexer.getLoc();
1318 if (ParseIdentifier(Name))
1319 return TokError("expected identifier in directive");
1321 // Handle the identifier as the key symbol.
1322 MCSymbol *Sym = CreateSymbol(Name);
1324 if (Lexer.isNot(AsmToken::Comma))
1325 return TokError("unexpected token in directive");
1329 SMLoc SizeLoc = Lexer.getLoc();
1330 if (ParseAbsoluteExpression(Size))
1333 int64_t Pow2Alignment = 0;
1334 SMLoc Pow2AlignmentLoc;
1335 if (Lexer.is(AsmToken::Comma)) {
1337 Pow2AlignmentLoc = Lexer.getLoc();
1338 if (ParseAbsoluteExpression(Pow2Alignment))
1341 // If this target takes alignments in bytes (not log) validate and convert.
1342 if (Lexer.getMAI().getAlignmentIsInBytes()) {
1343 if (!isPowerOf2_64(Pow2Alignment))
1344 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
1345 Pow2Alignment = Log2_64(Pow2Alignment);
1349 if (Lexer.isNot(AsmToken::EndOfStatement))
1350 return TokError("unexpected token in '.comm' or '.lcomm' directive");
1354 // NOTE: a size of zero for a .comm should create a undefined symbol
1355 // but a size of .lcomm creates a bss symbol of size zero.
1357 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
1358 "be less than zero");
1360 // NOTE: The alignment in the directive is a power of 2 value, the assember
1361 // may internally end up wanting an alignment in bytes.
1362 // FIXME: Diagnose overflow.
1363 if (Pow2Alignment < 0)
1364 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
1365 "alignment, can't be less than zero");
1367 if (!Sym->isUndefined())
1368 return Error(IDLoc, "invalid symbol redefinition");
1370 // '.lcomm' is equivalent to '.zerofill'.
1371 // Create the Symbol as a common or local common with Size and Pow2Alignment
1373 Out.EmitZerofill(getMachOSection("__DATA", "__bss",
1374 MCSectionMachO::S_ZEROFILL, 0,
1375 SectionKind::getBSS()),
1376 Sym, Size, 1 << Pow2Alignment);
1380 Out.EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
1384 /// ParseDirectiveDarwinZerofill
1385 /// ::= .zerofill segname , sectname [, identifier , size_expression [
1386 /// , align_expression ]]
1387 bool AsmParser::ParseDirectiveDarwinZerofill() {
1388 // FIXME: Handle quoted names here.
1390 if (Lexer.isNot(AsmToken::Identifier))
1391 return TokError("expected segment name after '.zerofill' directive");
1392 StringRef Segment = getTok().getString();
1395 if (Lexer.isNot(AsmToken::Comma))
1396 return TokError("unexpected token in directive");
1399 if (Lexer.isNot(AsmToken::Identifier))
1400 return TokError("expected section name after comma in '.zerofill' "
1402 StringRef Section = getTok().getString();
1405 // If this is the end of the line all that was wanted was to create the
1406 // the section but with no symbol.
1407 if (Lexer.is(AsmToken::EndOfStatement)) {
1408 // Create the zerofill section but no symbol
1409 Out.EmitZerofill(getMachOSection(Segment, Section,
1410 MCSectionMachO::S_ZEROFILL, 0,
1411 SectionKind::getBSS()));
1415 if (Lexer.isNot(AsmToken::Comma))
1416 return TokError("unexpected token in directive");
1419 if (Lexer.isNot(AsmToken::Identifier))
1420 return TokError("expected identifier in directive");
1422 // handle the identifier as the key symbol.
1423 SMLoc IDLoc = Lexer.getLoc();
1424 MCSymbol *Sym = CreateSymbol(getTok().getString());
1427 if (Lexer.isNot(AsmToken::Comma))
1428 return TokError("unexpected token in directive");
1432 SMLoc SizeLoc = Lexer.getLoc();
1433 if (ParseAbsoluteExpression(Size))
1436 int64_t Pow2Alignment = 0;
1437 SMLoc Pow2AlignmentLoc;
1438 if (Lexer.is(AsmToken::Comma)) {
1440 Pow2AlignmentLoc = Lexer.getLoc();
1441 if (ParseAbsoluteExpression(Pow2Alignment))
1445 if (Lexer.isNot(AsmToken::EndOfStatement))
1446 return TokError("unexpected token in '.zerofill' directive");
1451 return Error(SizeLoc, "invalid '.zerofill' directive size, can't be less "
1454 // NOTE: The alignment in the directive is a power of 2 value, the assember
1455 // may internally end up wanting an alignment in bytes.
1456 // FIXME: Diagnose overflow.
1457 if (Pow2Alignment < 0)
1458 return Error(Pow2AlignmentLoc, "invalid '.zerofill' directive alignment, "
1459 "can't be less than zero");
1461 if (!Sym->isUndefined())
1462 return Error(IDLoc, "invalid symbol redefinition");
1464 // Create the zerofill Symbol with Size and Pow2Alignment
1466 // FIXME: Arch specific.
1467 Out.EmitZerofill(getMachOSection(Segment, Section,
1468 MCSectionMachO::S_ZEROFILL, 0,
1469 SectionKind::getBSS()),
1470 Sym, Size, 1 << Pow2Alignment);
1475 /// ParseDirectiveDarwinSubsectionsViaSymbols
1476 /// ::= .subsections_via_symbols
1477 bool AsmParser::ParseDirectiveDarwinSubsectionsViaSymbols() {
1478 if (Lexer.isNot(AsmToken::EndOfStatement))
1479 return TokError("unexpected token in '.subsections_via_symbols' directive");
1483 Out.EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
1488 /// ParseDirectiveAbort
1489 /// ::= .abort [ "abort_string" ]
1490 bool AsmParser::ParseDirectiveAbort() {
1491 // FIXME: Use loc from directive.
1492 SMLoc Loc = Lexer.getLoc();
1495 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1496 if (Lexer.isNot(AsmToken::String))
1497 return TokError("expected string in '.abort' directive");
1499 Str = getTok().getString();
1504 if (Lexer.isNot(AsmToken::EndOfStatement))
1505 return TokError("unexpected token in '.abort' directive");
1509 // FIXME: Handle here.
1511 Error(Loc, ".abort detected. Assembly stopping.");
1513 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
1518 /// ParseDirectiveLsym
1519 /// ::= .lsym identifier , expression
1520 bool AsmParser::ParseDirectiveDarwinLsym() {
1522 if (ParseIdentifier(Name))
1523 return TokError("expected identifier in directive");
1525 // Handle the identifier as the key symbol.
1526 MCSymbol *Sym = CreateSymbol(Name);
1528 if (Lexer.isNot(AsmToken::Comma))
1529 return TokError("unexpected token in '.lsym' directive");
1532 const MCExpr *Value;
1533 SMLoc StartLoc = Lexer.getLoc();
1534 if (ParseExpression(Value))
1537 if (Lexer.isNot(AsmToken::EndOfStatement))
1538 return TokError("unexpected token in '.lsym' directive");
1542 // We don't currently support this directive.
1544 // FIXME: Diagnostic location!
1546 return TokError("directive '.lsym' is unsupported");
1549 /// ParseDirectiveInclude
1550 /// ::= .include "filename"
1551 bool AsmParser::ParseDirectiveInclude() {
1552 if (Lexer.isNot(AsmToken::String))
1553 return TokError("expected string in '.include' directive");
1555 std::string Filename = getTok().getString();
1556 SMLoc IncludeLoc = Lexer.getLoc();
1559 if (Lexer.isNot(AsmToken::EndOfStatement))
1560 return TokError("unexpected token in '.include' directive");
1562 // Strip the quotes.
1563 Filename = Filename.substr(1, Filename.size()-2);
1565 // Attempt to switch the lexer to the included file before consuming the end
1566 // of statement to avoid losing it when we switch.
1567 if (EnterIncludeFile(Filename)) {
1568 PrintMessage(IncludeLoc,
1569 "Could not find include file '" + Filename + "'",
1577 /// ParseDirectiveDarwinDumpOrLoad
1578 /// ::= ( .dump | .load ) "filename"
1579 bool AsmParser::ParseDirectiveDarwinDumpOrLoad(SMLoc IDLoc, bool IsDump) {
1580 if (Lexer.isNot(AsmToken::String))
1581 return TokError("expected string in '.dump' or '.load' directive");
1585 if (Lexer.isNot(AsmToken::EndOfStatement))
1586 return TokError("unexpected token in '.dump' or '.load' directive");
1590 // FIXME: If/when .dump and .load are implemented they will be done in the
1591 // the assembly parser and not have any need for an MCStreamer API.
1593 Warning(IDLoc, "ignoring directive .dump for now");
1595 Warning(IDLoc, "ignoring directive .load for now");
1600 /// ParseDirectiveIf
1601 /// ::= .if expression
1602 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
1603 // Consume the identifier that was the .if directive
1606 TheCondStack.push_back(TheCondState);
1607 TheCondState.TheCond = AsmCond::IfCond;
1608 if(TheCondState.Ignore) {
1609 EatToEndOfStatement();
1613 if (ParseAbsoluteExpression(ExprValue))
1616 if (Lexer.isNot(AsmToken::EndOfStatement))
1617 return TokError("unexpected token in '.if' directive");
1621 TheCondState.CondMet = ExprValue;
1622 TheCondState.Ignore = !TheCondState.CondMet;
1628 /// ParseDirectiveElseIf
1629 /// ::= .elseif expression
1630 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
1631 if (TheCondState.TheCond != AsmCond::IfCond &&
1632 TheCondState.TheCond != AsmCond::ElseIfCond)
1633 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
1635 TheCondState.TheCond = AsmCond::ElseIfCond;
1637 // Consume the identifier that was the .elseif directive
1640 bool LastIgnoreState = false;
1641 if (!TheCondStack.empty())
1642 LastIgnoreState = TheCondStack.back().Ignore;
1643 if (LastIgnoreState || TheCondState.CondMet) {
1644 TheCondState.Ignore = true;
1645 EatToEndOfStatement();
1649 if (ParseAbsoluteExpression(ExprValue))
1652 if (Lexer.isNot(AsmToken::EndOfStatement))
1653 return TokError("unexpected token in '.elseif' directive");
1656 TheCondState.CondMet = ExprValue;
1657 TheCondState.Ignore = !TheCondState.CondMet;
1663 /// ParseDirectiveElse
1665 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
1666 // Consume the identifier that was the .else directive
1669 if (Lexer.isNot(AsmToken::EndOfStatement))
1670 return TokError("unexpected token in '.else' directive");
1674 if (TheCondState.TheCond != AsmCond::IfCond &&
1675 TheCondState.TheCond != AsmCond::ElseIfCond)
1676 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
1678 TheCondState.TheCond = AsmCond::ElseCond;
1679 bool LastIgnoreState = false;
1680 if (!TheCondStack.empty())
1681 LastIgnoreState = TheCondStack.back().Ignore;
1682 if (LastIgnoreState || TheCondState.CondMet)
1683 TheCondState.Ignore = true;
1685 TheCondState.Ignore = false;
1690 /// ParseDirectiveEndIf
1692 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
1693 // Consume the identifier that was the .endif directive
1696 if (Lexer.isNot(AsmToken::EndOfStatement))
1697 return TokError("unexpected token in '.endif' directive");
1701 if ((TheCondState.TheCond == AsmCond::NoCond) ||
1702 TheCondStack.empty())
1703 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
1705 if (!TheCondStack.empty()) {
1706 TheCondState = TheCondStack.back();
1707 TheCondStack.pop_back();
1713 /// ParseDirectiveFile
1714 /// ::= .file [number] string
1715 bool AsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
1716 // FIXME: I'm not sure what this is.
1717 int64_t FileNumber = -1;
1718 if (Lexer.is(AsmToken::Integer)) {
1719 FileNumber = getTok().getIntVal();
1723 return TokError("file number less than one");
1726 if (Lexer.isNot(AsmToken::String))
1727 return TokError("unexpected token in '.file' directive");
1729 StringRef Filename = getTok().getString();
1730 Filename = Filename.substr(1, Filename.size()-2);
1733 if (Lexer.isNot(AsmToken::EndOfStatement))
1734 return TokError("unexpected token in '.file' directive");
1736 if (FileNumber == -1)
1737 Out.EmitFileDirective(Filename);
1739 Out.EmitDwarfFileDirective(FileNumber, Filename);
1744 /// ParseDirectiveLine
1745 /// ::= .line [number]
1746 bool AsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
1747 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1748 if (Lexer.isNot(AsmToken::Integer))
1749 return TokError("unexpected token in '.line' directive");
1751 int64_t LineNumber = getTok().getIntVal();
1755 // FIXME: Do something with the .line.
1758 if (Lexer.isNot(AsmToken::EndOfStatement))
1759 return TokError("unexpected token in '.file' directive");
1765 /// ParseDirectiveLoc
1766 /// ::= .loc number [number [number]]
1767 bool AsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
1768 if (Lexer.isNot(AsmToken::Integer))
1769 return TokError("unexpected token in '.loc' directive");
1771 // FIXME: What are these fields?
1772 int64_t FileNumber = getTok().getIntVal();
1774 // FIXME: Validate file.
1777 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1778 if (Lexer.isNot(AsmToken::Integer))
1779 return TokError("unexpected token in '.loc' directive");
1781 int64_t Param2 = getTok().getIntVal();
1785 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1786 if (Lexer.isNot(AsmToken::Integer))
1787 return TokError("unexpected token in '.loc' directive");
1789 int64_t Param3 = getTok().getIntVal();
1793 // FIXME: Do something with the .loc.
1797 if (Lexer.isNot(AsmToken::EndOfStatement))
1798 return TokError("unexpected token in '.file' directive");