1 //===- AsmParser.cpp - Parser for Assembly Files --------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This class implements a parser for assembly files similar to gas syntax. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/ADT/APFloat.h" 14 #include "llvm/ADT/APInt.h" 15 #include "llvm/ADT/ArrayRef.h" 16 #include "llvm/ADT/None.h" 17 #include "llvm/ADT/STLExtras.h" 18 #include "llvm/ADT/SmallString.h" 19 #include "llvm/ADT/SmallVector.h" 20 #include "llvm/ADT/StringExtras.h" 21 #include "llvm/ADT/StringMap.h" 22 #include "llvm/ADT/StringRef.h" 23 #include "llvm/ADT/Twine.h" 24 #include "llvm/BinaryFormat/Dwarf.h" 25 #include "llvm/DebugInfo/CodeView/SymbolRecord.h" 26 #include "llvm/MC/MCAsmInfo.h" 27 #include "llvm/MC/MCCodeView.h" 28 #include "llvm/MC/MCContext.h" 29 #include "llvm/MC/MCDirectives.h" 30 #include "llvm/MC/MCDwarf.h" 31 #include "llvm/MC/MCExpr.h" 32 #include "llvm/MC/MCInstPrinter.h" 33 #include "llvm/MC/MCInstrDesc.h" 34 #include "llvm/MC/MCInstrInfo.h" 35 #include "llvm/MC/MCObjectFileInfo.h" 36 #include "llvm/MC/MCParser/AsmCond.h" 37 #include "llvm/MC/MCParser/AsmLexer.h" 38 #include "llvm/MC/MCParser/MCAsmLexer.h" 39 #include "llvm/MC/MCParser/MCAsmParser.h" 40 #include "llvm/MC/MCParser/MCAsmParserExtension.h" 41 #include "llvm/MC/MCParser/MCAsmParserUtils.h" 42 #include "llvm/MC/MCParser/MCParsedAsmOperand.h" 43 #include "llvm/MC/MCParser/MCTargetAsmParser.h" 44 #include "llvm/MC/MCRegisterInfo.h" 45 #include "llvm/MC/MCSection.h" 46 #include "llvm/MC/MCStreamer.h" 47 #include "llvm/MC/MCSymbol.h" 48 #include "llvm/MC/MCTargetOptions.h" 49 #include "llvm/MC/MCValue.h" 50 #include "llvm/Support/Casting.h" 51 #include "llvm/Support/CommandLine.h" 52 #include "llvm/Support/ErrorHandling.h" 53 #include "llvm/Support/MD5.h" 54 #include "llvm/Support/MathExtras.h" 55 #include "llvm/Support/MemoryBuffer.h" 56 #include "llvm/Support/SMLoc.h" 57 #include "llvm/Support/SourceMgr.h" 58 #include "llvm/Support/raw_ostream.h" 59 #include <algorithm> 60 #include <cassert> 61 #include <cctype> 62 #include <climits> 63 #include <cstddef> 64 #include <cstdint> 65 #include <deque> 66 #include <memory> 67 #include <sstream> 68 #include <string> 69 #include <tuple> 70 #include <utility> 71 #include <vector> 72 73 using namespace llvm; 74 75 MCAsmParserSemaCallback::~MCAsmParserSemaCallback() = default; 76 77 extern cl::opt<unsigned> AsmMacroMaxNestingDepth; 78 79 namespace { 80 81 /// Helper types for tracking macro definitions. 82 typedef std::vector<AsmToken> MCAsmMacroArgument; 83 typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments; 84 85 /// Helper class for storing information about an active macro 86 /// instantiation. 87 struct MacroInstantiation { 88 /// The location of the instantiation. 89 SMLoc InstantiationLoc; 90 91 /// The buffer where parsing should resume upon instantiation completion. 92 unsigned ExitBuffer; 93 94 /// The location where parsing should resume upon instantiation completion. 95 SMLoc ExitLoc; 96 97 /// The depth of TheCondStack at the start of the instantiation. 98 size_t CondStackDepth; 99 }; 100 101 struct ParseStatementInfo { 102 /// The parsed operands from the last parsed statement. 103 SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> ParsedOperands; 104 105 /// The opcode from the last parsed instruction. 106 unsigned Opcode = ~0U; 107 108 /// Was there an error parsing the inline assembly? 109 bool ParseError = false; 110 111 SmallVectorImpl<AsmRewrite> *AsmRewrites = nullptr; 112 113 ParseStatementInfo() = delete; 114 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites) 115 : AsmRewrites(rewrites) {} 116 }; 117 118 /// The concrete assembly parser instance. 119 class AsmParser : public MCAsmParser { 120 private: 121 AsmLexer Lexer; 122 MCContext &Ctx; 123 MCStreamer &Out; 124 const MCAsmInfo &MAI; 125 SourceMgr &SrcMgr; 126 SourceMgr::DiagHandlerTy SavedDiagHandler; 127 void *SavedDiagContext; 128 std::unique_ptr<MCAsmParserExtension> PlatformParser; 129 130 /// This is the current buffer index we're lexing from as managed by the 131 /// SourceMgr object. 132 unsigned CurBuffer; 133 134 AsmCond TheCondState; 135 std::vector<AsmCond> TheCondStack; 136 137 /// maps directive names to handler methods in parser 138 /// extensions. Extensions register themselves in this map by calling 139 /// addDirectiveHandler. 140 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap; 141 142 /// Stack of active macro instantiations. 143 std::vector<MacroInstantiation*> ActiveMacros; 144 145 /// List of bodies of anonymous macros. 146 std::deque<MCAsmMacro> MacroLikeBodies; 147 148 /// Boolean tracking whether macro substitution is enabled. 149 unsigned MacrosEnabledFlag : 1; 150 151 /// Keeps track of how many .macro's have been instantiated. 152 unsigned NumOfMacroInstantiations; 153 154 /// The values from the last parsed cpp hash file line comment if any. 155 struct CppHashInfoTy { 156 StringRef Filename; 157 int64_t LineNumber; 158 SMLoc Loc; 159 unsigned Buf; 160 CppHashInfoTy() : Filename(), LineNumber(0), Loc(), Buf(0) {} 161 }; 162 CppHashInfoTy CppHashInfo; 163 164 /// The filename from the first cpp hash file line comment, if any. 165 StringRef FirstCppHashFilename; 166 167 /// List of forward directional labels for diagnosis at the end. 168 SmallVector<std::tuple<SMLoc, CppHashInfoTy, MCSymbol *>, 4> DirLabels; 169 170 /// AssemblerDialect. ~OU means unset value and use value provided by MAI. 171 unsigned AssemblerDialect = ~0U; 172 173 /// is Darwin compatibility enabled? 174 bool IsDarwin = false; 175 176 /// Are we parsing ms-style inline assembly? 177 bool ParsingMSInlineAsm = false; 178 179 /// Did we already inform the user about inconsistent MD5 usage? 180 bool ReportedInconsistentMD5 = false; 181 182 // Is alt macro mode enabled. 183 bool AltMacroMode = false; 184 185 public: 186 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out, 187 const MCAsmInfo &MAI, unsigned CB); 188 AsmParser(const AsmParser &) = delete; 189 AsmParser &operator=(const AsmParser &) = delete; 190 ~AsmParser() override; 191 192 bool Run(bool NoInitialTextSection, bool NoFinalize = false) override; 193 194 void addDirectiveHandler(StringRef Directive, 195 ExtensionDirectiveHandler Handler) override { 196 ExtensionDirectiveMap[Directive] = Handler; 197 } 198 199 void addAliasForDirective(StringRef Directive, StringRef Alias) override { 200 DirectiveKindMap[Directive.lower()] = DirectiveKindMap[Alias.lower()]; 201 } 202 203 /// @name MCAsmParser Interface 204 /// { 205 206 SourceMgr &getSourceManager() override { return SrcMgr; } 207 MCAsmLexer &getLexer() override { return Lexer; } 208 MCContext &getContext() override { return Ctx; } 209 MCStreamer &getStreamer() override { return Out; } 210 211 CodeViewContext &getCVContext() { return Ctx.getCVContext(); } 212 213 unsigned getAssemblerDialect() override { 214 if (AssemblerDialect == ~0U) 215 return MAI.getAssemblerDialect(); 216 else 217 return AssemblerDialect; 218 } 219 void setAssemblerDialect(unsigned i) override { 220 AssemblerDialect = i; 221 } 222 223 void Note(SMLoc L, const Twine &Msg, SMRange Range = None) override; 224 bool Warning(SMLoc L, const Twine &Msg, SMRange Range = None) override; 225 bool printError(SMLoc L, const Twine &Msg, SMRange Range = None) override; 226 227 const AsmToken &Lex() override; 228 229 void setParsingMSInlineAsm(bool V) override { 230 ParsingMSInlineAsm = V; 231 // When parsing MS inline asm, we must lex 0b1101 and 0ABCH as binary and 232 // hex integer literals. 233 Lexer.setLexMasmIntegers(V); 234 } 235 bool isParsingMSInlineAsm() override { return ParsingMSInlineAsm; } 236 237 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString, 238 unsigned &NumOutputs, unsigned &NumInputs, 239 SmallVectorImpl<std::pair<void *,bool>> &OpDecls, 240 SmallVectorImpl<std::string> &Constraints, 241 SmallVectorImpl<std::string> &Clobbers, 242 const MCInstrInfo *MII, const MCInstPrinter *IP, 243 MCAsmParserSemaCallback &SI) override; 244 245 bool parseExpression(const MCExpr *&Res); 246 bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override; 247 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override; 248 bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override; 249 bool parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res, 250 SMLoc &EndLoc) override; 251 bool parseAbsoluteExpression(int64_t &Res) override; 252 253 /// Parse a floating point expression using the float \p Semantics 254 /// and set \p Res to the value. 255 bool parseRealValue(const fltSemantics &Semantics, APInt &Res); 256 257 /// Parse an identifier or string (as a quoted identifier) 258 /// and set \p Res to the identifier contents. 259 bool parseIdentifier(StringRef &Res) override; 260 void eatToEndOfStatement() override; 261 262 bool checkForValidSection() override; 263 264 /// } 265 266 private: 267 bool parseStatement(ParseStatementInfo &Info, 268 MCAsmParserSemaCallback *SI); 269 bool parseCurlyBlockScope(SmallVectorImpl<AsmRewrite>& AsmStrRewrites); 270 bool parseCppHashLineFilenameComment(SMLoc L, bool SaveLocInfo = true); 271 272 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body, 273 ArrayRef<MCAsmMacroParameter> Parameters); 274 bool expandMacro(raw_svector_ostream &OS, StringRef Body, 275 ArrayRef<MCAsmMacroParameter> Parameters, 276 ArrayRef<MCAsmMacroArgument> A, bool EnableAtPseudoVariable, 277 SMLoc L); 278 279 /// Are macros enabled in the parser? 280 bool areMacrosEnabled() {return MacrosEnabledFlag;} 281 282 /// Control a flag in the parser that enables or disables macros. 283 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;} 284 285 /// Are we inside a macro instantiation? 286 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();} 287 288 /// Handle entry to macro instantiation. 289 /// 290 /// \param M The macro. 291 /// \param NameLoc Instantiation location. 292 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc); 293 294 /// Handle exit from macro instantiation. 295 void handleMacroExit(); 296 297 /// Extract AsmTokens for a macro argument. 298 bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg); 299 300 /// Parse all macro arguments for a given macro. 301 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A); 302 303 void printMacroInstantiations(); 304 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg, 305 SMRange Range = None) const { 306 ArrayRef<SMRange> Ranges(Range); 307 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges); 308 } 309 static void DiagHandler(const SMDiagnostic &Diag, void *Context); 310 311 /// Should we emit DWARF describing this assembler source? (Returns false if 312 /// the source has .file directives, which means we don't want to generate 313 /// info describing the assembler source itself.) 314 bool enabledGenDwarfForAssembly(); 315 316 /// Enter the specified file. This returns true on failure. 317 bool enterIncludeFile(const std::string &Filename); 318 319 /// Process the specified file for the .incbin directive. 320 /// This returns true on failure. 321 bool processIncbinFile(const std::string &Filename, int64_t Skip = 0, 322 const MCExpr *Count = nullptr, SMLoc Loc = SMLoc()); 323 324 /// Reset the current lexer position to that given by \p Loc. The 325 /// current token is not set; clients should ensure Lex() is called 326 /// subsequently. 327 /// 328 /// \param InBuffer If not 0, should be the known buffer id that contains the 329 /// location. 330 void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0); 331 332 /// Parse up to the end of statement and a return the contents from the 333 /// current token until the end of the statement; the current token on exit 334 /// will be either the EndOfStatement or EOF. 335 StringRef parseStringToEndOfStatement() override; 336 337 /// Parse until the end of a statement or a comma is encountered, 338 /// return the contents from the current token up to the end or comma. 339 StringRef parseStringToComma(); 340 341 bool parseAssignment(StringRef Name, bool allow_redef, 342 bool NoDeadStrip = false); 343 344 unsigned getBinOpPrecedence(AsmToken::TokenKind K, 345 MCBinaryExpr::Opcode &Kind); 346 347 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc); 348 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc); 349 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc); 350 351 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc); 352 353 bool parseCVFunctionId(int64_t &FunctionId, StringRef DirectiveName); 354 bool parseCVFileId(int64_t &FileId, StringRef DirectiveName); 355 356 // Generic (target and platform independent) directive parsing. 357 enum DirectiveKind { 358 DK_NO_DIRECTIVE, // Placeholder 359 DK_SET, 360 DK_EQU, 361 DK_EQUIV, 362 DK_ASCII, 363 DK_ASCIZ, 364 DK_STRING, 365 DK_BYTE, 366 DK_SHORT, 367 DK_RELOC, 368 DK_VALUE, 369 DK_2BYTE, 370 DK_LONG, 371 DK_INT, 372 DK_4BYTE, 373 DK_QUAD, 374 DK_8BYTE, 375 DK_OCTA, 376 DK_DC, 377 DK_DC_A, 378 DK_DC_B, 379 DK_DC_D, 380 DK_DC_L, 381 DK_DC_S, 382 DK_DC_W, 383 DK_DC_X, 384 DK_DCB, 385 DK_DCB_B, 386 DK_DCB_D, 387 DK_DCB_L, 388 DK_DCB_S, 389 DK_DCB_W, 390 DK_DCB_X, 391 DK_DS, 392 DK_DS_B, 393 DK_DS_D, 394 DK_DS_L, 395 DK_DS_P, 396 DK_DS_S, 397 DK_DS_W, 398 DK_DS_X, 399 DK_SINGLE, 400 DK_FLOAT, 401 DK_DOUBLE, 402 DK_ALIGN, 403 DK_ALIGN32, 404 DK_BALIGN, 405 DK_BALIGNW, 406 DK_BALIGNL, 407 DK_P2ALIGN, 408 DK_P2ALIGNW, 409 DK_P2ALIGNL, 410 DK_ORG, 411 DK_FILL, 412 DK_ENDR, 413 DK_BUNDLE_ALIGN_MODE, 414 DK_BUNDLE_LOCK, 415 DK_BUNDLE_UNLOCK, 416 DK_ZERO, 417 DK_EXTERN, 418 DK_GLOBL, 419 DK_GLOBAL, 420 DK_LAZY_REFERENCE, 421 DK_NO_DEAD_STRIP, 422 DK_SYMBOL_RESOLVER, 423 DK_PRIVATE_EXTERN, 424 DK_REFERENCE, 425 DK_WEAK_DEFINITION, 426 DK_WEAK_REFERENCE, 427 DK_WEAK_DEF_CAN_BE_HIDDEN, 428 DK_COLD, 429 DK_COMM, 430 DK_COMMON, 431 DK_LCOMM, 432 DK_ABORT, 433 DK_INCLUDE, 434 DK_INCBIN, 435 DK_CODE16, 436 DK_CODE16GCC, 437 DK_REPT, 438 DK_IRP, 439 DK_IRPC, 440 DK_IF, 441 DK_IFEQ, 442 DK_IFGE, 443 DK_IFGT, 444 DK_IFLE, 445 DK_IFLT, 446 DK_IFNE, 447 DK_IFB, 448 DK_IFNB, 449 DK_IFC, 450 DK_IFEQS, 451 DK_IFNC, 452 DK_IFNES, 453 DK_IFDEF, 454 DK_IFNDEF, 455 DK_IFNOTDEF, 456 DK_ELSEIF, 457 DK_ELSE, 458 DK_ENDIF, 459 DK_SPACE, 460 DK_SKIP, 461 DK_FILE, 462 DK_LINE, 463 DK_LOC, 464 DK_STABS, 465 DK_CV_FILE, 466 DK_CV_FUNC_ID, 467 DK_CV_INLINE_SITE_ID, 468 DK_CV_LOC, 469 DK_CV_LINETABLE, 470 DK_CV_INLINE_LINETABLE, 471 DK_CV_DEF_RANGE, 472 DK_CV_STRINGTABLE, 473 DK_CV_STRING, 474 DK_CV_FILECHECKSUMS, 475 DK_CV_FILECHECKSUM_OFFSET, 476 DK_CV_FPO_DATA, 477 DK_CFI_SECTIONS, 478 DK_CFI_STARTPROC, 479 DK_CFI_ENDPROC, 480 DK_CFI_DEF_CFA, 481 DK_CFI_DEF_CFA_OFFSET, 482 DK_CFI_ADJUST_CFA_OFFSET, 483 DK_CFI_DEF_CFA_REGISTER, 484 DK_CFI_OFFSET, 485 DK_CFI_REL_OFFSET, 486 DK_CFI_PERSONALITY, 487 DK_CFI_LSDA, 488 DK_CFI_REMEMBER_STATE, 489 DK_CFI_RESTORE_STATE, 490 DK_CFI_SAME_VALUE, 491 DK_CFI_RESTORE, 492 DK_CFI_ESCAPE, 493 DK_CFI_RETURN_COLUMN, 494 DK_CFI_SIGNAL_FRAME, 495 DK_CFI_UNDEFINED, 496 DK_CFI_REGISTER, 497 DK_CFI_WINDOW_SAVE, 498 DK_CFI_B_KEY_FRAME, 499 DK_MACROS_ON, 500 DK_MACROS_OFF, 501 DK_ALTMACRO, 502 DK_NOALTMACRO, 503 DK_MACRO, 504 DK_EXITM, 505 DK_ENDM, 506 DK_ENDMACRO, 507 DK_PURGEM, 508 DK_SLEB128, 509 DK_ULEB128, 510 DK_ERR, 511 DK_ERROR, 512 DK_WARNING, 513 DK_PRINT, 514 DK_ADDRSIG, 515 DK_ADDRSIG_SYM, 516 DK_END 517 }; 518 519 /// Maps directive name --> DirectiveKind enum, for 520 /// directives parsed by this class. 521 StringMap<DirectiveKind> DirectiveKindMap; 522 523 // Codeview def_range type parsing. 524 enum CVDefRangeType { 525 CVDR_DEFRANGE = 0, // Placeholder 526 CVDR_DEFRANGE_REGISTER, 527 CVDR_DEFRANGE_FRAMEPOINTER_REL, 528 CVDR_DEFRANGE_SUBFIELD_REGISTER, 529 CVDR_DEFRANGE_REGISTER_REL 530 }; 531 532 /// Maps Codeview def_range types --> CVDefRangeType enum, for 533 /// Codeview def_range types parsed by this class. 534 StringMap<CVDefRangeType> CVDefRangeTypeMap; 535 536 // ".ascii", ".asciz", ".string" 537 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated); 538 bool parseDirectiveReloc(SMLoc DirectiveLoc); // ".reloc" 539 bool parseDirectiveValue(StringRef IDVal, 540 unsigned Size); // ".byte", ".long", ... 541 bool parseDirectiveOctaValue(StringRef IDVal); // ".octa", ... 542 bool parseDirectiveRealValue(StringRef IDVal, 543 const fltSemantics &); // ".single", ... 544 bool parseDirectiveFill(); // ".fill" 545 bool parseDirectiveZero(); // ".zero" 546 // ".set", ".equ", ".equiv" 547 bool parseDirectiveSet(StringRef IDVal, bool allow_redef); 548 bool parseDirectiveOrg(); // ".org" 549 // ".align{,32}", ".p2align{,w,l}" 550 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize); 551 552 // ".file", ".line", ".loc", ".stabs" 553 bool parseDirectiveFile(SMLoc DirectiveLoc); 554 bool parseDirectiveLine(); 555 bool parseDirectiveLoc(); 556 bool parseDirectiveStabs(); 557 558 // ".cv_file", ".cv_func_id", ".cv_inline_site_id", ".cv_loc", ".cv_linetable", 559 // ".cv_inline_linetable", ".cv_def_range", ".cv_string" 560 bool parseDirectiveCVFile(); 561 bool parseDirectiveCVFuncId(); 562 bool parseDirectiveCVInlineSiteId(); 563 bool parseDirectiveCVLoc(); 564 bool parseDirectiveCVLinetable(); 565 bool parseDirectiveCVInlineLinetable(); 566 bool parseDirectiveCVDefRange(); 567 bool parseDirectiveCVString(); 568 bool parseDirectiveCVStringTable(); 569 bool parseDirectiveCVFileChecksums(); 570 bool parseDirectiveCVFileChecksumOffset(); 571 bool parseDirectiveCVFPOData(); 572 573 // .cfi directives 574 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc); 575 bool parseDirectiveCFIWindowSave(); 576 bool parseDirectiveCFISections(); 577 bool parseDirectiveCFIStartProc(); 578 bool parseDirectiveCFIEndProc(); 579 bool parseDirectiveCFIDefCfaOffset(); 580 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc); 581 bool parseDirectiveCFIAdjustCfaOffset(); 582 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc); 583 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc); 584 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc); 585 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality); 586 bool parseDirectiveCFIRememberState(); 587 bool parseDirectiveCFIRestoreState(); 588 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc); 589 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc); 590 bool parseDirectiveCFIEscape(); 591 bool parseDirectiveCFIReturnColumn(SMLoc DirectiveLoc); 592 bool parseDirectiveCFISignalFrame(); 593 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc); 594 595 // macro directives 596 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc); 597 bool parseDirectiveExitMacro(StringRef Directive); 598 bool parseDirectiveEndMacro(StringRef Directive); 599 bool parseDirectiveMacro(SMLoc DirectiveLoc); 600 bool parseDirectiveMacrosOnOff(StringRef Directive); 601 // alternate macro mode directives 602 bool parseDirectiveAltmacro(StringRef Directive); 603 // ".bundle_align_mode" 604 bool parseDirectiveBundleAlignMode(); 605 // ".bundle_lock" 606 bool parseDirectiveBundleLock(); 607 // ".bundle_unlock" 608 bool parseDirectiveBundleUnlock(); 609 610 // ".space", ".skip" 611 bool parseDirectiveSpace(StringRef IDVal); 612 613 // ".dcb" 614 bool parseDirectiveDCB(StringRef IDVal, unsigned Size); 615 bool parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &); 616 // ".ds" 617 bool parseDirectiveDS(StringRef IDVal, unsigned Size); 618 619 // .sleb128 (Signed=true) and .uleb128 (Signed=false) 620 bool parseDirectiveLEB128(bool Signed); 621 622 /// Parse a directive like ".globl" which 623 /// accepts a single symbol (which should be a label or an external). 624 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr); 625 626 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm" 627 628 bool parseDirectiveAbort(); // ".abort" 629 bool parseDirectiveInclude(); // ".include" 630 bool parseDirectiveIncbin(); // ".incbin" 631 632 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne" 633 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind); 634 // ".ifb" or ".ifnb", depending on ExpectBlank. 635 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank); 636 // ".ifc" or ".ifnc", depending on ExpectEqual. 637 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual); 638 // ".ifeqs" or ".ifnes", depending on ExpectEqual. 639 bool parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual); 640 // ".ifdef" or ".ifndef", depending on expect_defined 641 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined); 642 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif" 643 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else" 644 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif 645 bool parseEscapedString(std::string &Data) override; 646 bool parseAngleBracketString(std::string &Data) override; 647 648 const MCExpr *applyModifierToExpr(const MCExpr *E, 649 MCSymbolRefExpr::VariantKind Variant); 650 651 // Macro-like directives 652 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc); 653 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc, 654 raw_svector_ostream &OS); 655 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive); 656 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp" 657 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc" 658 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr" 659 660 // "_emit" or "__emit" 661 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info, 662 size_t Len); 663 664 // "align" 665 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info); 666 667 // "end" 668 bool parseDirectiveEnd(SMLoc DirectiveLoc); 669 670 // ".err" or ".error" 671 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage); 672 673 // ".warning" 674 bool parseDirectiveWarning(SMLoc DirectiveLoc); 675 676 // .print <double-quotes-string> 677 bool parseDirectivePrint(SMLoc DirectiveLoc); 678 679 // Directives to support address-significance tables. 680 bool parseDirectiveAddrsig(); 681 bool parseDirectiveAddrsigSym(); 682 683 void initializeDirectiveKindMap(); 684 void initializeCVDefRangeTypeMap(); 685 }; 686 687 } // end anonymous namespace 688 689 namespace llvm { 690 691 extern MCAsmParserExtension *createDarwinAsmParser(); 692 extern MCAsmParserExtension *createELFAsmParser(); 693 extern MCAsmParserExtension *createCOFFAsmParser(); 694 extern MCAsmParserExtension *createWasmAsmParser(); 695 696 } // end namespace llvm 697 698 enum { DEFAULT_ADDRSPACE = 0 }; 699 700 AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out, 701 const MCAsmInfo &MAI, unsigned CB = 0) 702 : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM), 703 CurBuffer(CB ? CB : SM.getMainFileID()), MacrosEnabledFlag(true) { 704 HadError = false; 705 // Save the old handler. 706 SavedDiagHandler = SrcMgr.getDiagHandler(); 707 SavedDiagContext = SrcMgr.getDiagContext(); 708 // Set our own handler which calls the saved handler. 709 SrcMgr.setDiagHandler(DiagHandler, this); 710 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer()); 711 712 // Initialize the platform / file format parser. 713 switch (Ctx.getObjectFileInfo()->getObjectFileType()) { 714 case MCObjectFileInfo::IsCOFF: 715 PlatformParser.reset(createCOFFAsmParser()); 716 break; 717 case MCObjectFileInfo::IsMachO: 718 PlatformParser.reset(createDarwinAsmParser()); 719 IsDarwin = true; 720 break; 721 case MCObjectFileInfo::IsELF: 722 PlatformParser.reset(createELFAsmParser()); 723 break; 724 case MCObjectFileInfo::IsWasm: 725 PlatformParser.reset(createWasmAsmParser()); 726 break; 727 case MCObjectFileInfo::IsXCOFF: 728 report_fatal_error( 729 "Need to implement createXCOFFAsmParser for XCOFF format."); 730 break; 731 } 732 733 PlatformParser->Initialize(*this); 734 initializeDirectiveKindMap(); 735 initializeCVDefRangeTypeMap(); 736 737 NumOfMacroInstantiations = 0; 738 } 739 740 AsmParser::~AsmParser() { 741 assert((HadError || ActiveMacros.empty()) && 742 "Unexpected active macro instantiation!"); 743 744 // Restore the saved diagnostics handler and context for use during 745 // finalization. 746 SrcMgr.setDiagHandler(SavedDiagHandler, SavedDiagContext); 747 } 748 749 void AsmParser::printMacroInstantiations() { 750 // Print the active macro instantiation stack. 751 for (std::vector<MacroInstantiation *>::const_reverse_iterator 752 it = ActiveMacros.rbegin(), 753 ie = ActiveMacros.rend(); 754 it != ie; ++it) 755 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note, 756 "while in macro instantiation"); 757 } 758 759 void AsmParser::Note(SMLoc L, const Twine &Msg, SMRange Range) { 760 printPendingErrors(); 761 printMessage(L, SourceMgr::DK_Note, Msg, Range); 762 printMacroInstantiations(); 763 } 764 765 bool AsmParser::Warning(SMLoc L, const Twine &Msg, SMRange Range) { 766 if(getTargetParser().getTargetOptions().MCNoWarn) 767 return false; 768 if (getTargetParser().getTargetOptions().MCFatalWarnings) 769 return Error(L, Msg, Range); 770 printMessage(L, SourceMgr::DK_Warning, Msg, Range); 771 printMacroInstantiations(); 772 return false; 773 } 774 775 bool AsmParser::printError(SMLoc L, const Twine &Msg, SMRange Range) { 776 HadError = true; 777 printMessage(L, SourceMgr::DK_Error, Msg, Range); 778 printMacroInstantiations(); 779 return true; 780 } 781 782 bool AsmParser::enterIncludeFile(const std::string &Filename) { 783 std::string IncludedFile; 784 unsigned NewBuf = 785 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile); 786 if (!NewBuf) 787 return true; 788 789 CurBuffer = NewBuf; 790 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer()); 791 return false; 792 } 793 794 /// Process the specified .incbin file by searching for it in the include paths 795 /// then just emitting the byte contents of the file to the streamer. This 796 /// returns true on failure. 797 bool AsmParser::processIncbinFile(const std::string &Filename, int64_t Skip, 798 const MCExpr *Count, SMLoc Loc) { 799 std::string IncludedFile; 800 unsigned NewBuf = 801 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile); 802 if (!NewBuf) 803 return true; 804 805 // Pick up the bytes from the file and emit them. 806 StringRef Bytes = SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(); 807 Bytes = Bytes.drop_front(Skip); 808 if (Count) { 809 int64_t Res; 810 if (!Count->evaluateAsAbsolute(Res, getStreamer().getAssemblerPtr())) 811 return Error(Loc, "expected absolute expression"); 812 if (Res < 0) 813 return Warning(Loc, "negative count has no effect"); 814 Bytes = Bytes.take_front(Res); 815 } 816 getStreamer().emitBytes(Bytes); 817 return false; 818 } 819 820 void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) { 821 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc); 822 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(), 823 Loc.getPointer()); 824 } 825 826 const AsmToken &AsmParser::Lex() { 827 if (Lexer.getTok().is(AsmToken::Error)) 828 Error(Lexer.getErrLoc(), Lexer.getErr()); 829 830 // if it's a end of statement with a comment in it 831 if (getTok().is(AsmToken::EndOfStatement)) { 832 // if this is a line comment output it. 833 if (!getTok().getString().empty() && getTok().getString().front() != '\n' && 834 getTok().getString().front() != '\r' && MAI.preserveAsmComments()) 835 Out.addExplicitComment(Twine(getTok().getString())); 836 } 837 838 const AsmToken *tok = &Lexer.Lex(); 839 840 // Parse comments here to be deferred until end of next statement. 841 while (tok->is(AsmToken::Comment)) { 842 if (MAI.preserveAsmComments()) 843 Out.addExplicitComment(Twine(tok->getString())); 844 tok = &Lexer.Lex(); 845 } 846 847 if (tok->is(AsmToken::Eof)) { 848 // If this is the end of an included file, pop the parent file off the 849 // include stack. 850 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer); 851 if (ParentIncludeLoc != SMLoc()) { 852 jumpToLoc(ParentIncludeLoc); 853 return Lex(); 854 } 855 } 856 857 return *tok; 858 } 859 860 bool AsmParser::enabledGenDwarfForAssembly() { 861 // Check whether the user specified -g. 862 if (!getContext().getGenDwarfForAssembly()) 863 return false; 864 // If we haven't encountered any .file directives (which would imply that 865 // the assembler source was produced with debug info already) then emit one 866 // describing the assembler source file itself. 867 if (getContext().getGenDwarfFileNumber() == 0) { 868 // Use the first #line directive for this, if any. It's preprocessed, so 869 // there is no checksum, and of course no source directive. 870 if (!FirstCppHashFilename.empty()) 871 getContext().setMCLineTableRootFile(/*CUID=*/0, 872 getContext().getCompilationDir(), 873 FirstCppHashFilename, 874 /*Cksum=*/None, /*Source=*/None); 875 const MCDwarfFile &RootFile = 876 getContext().getMCDwarfLineTable(/*CUID=*/0).getRootFile(); 877 getContext().setGenDwarfFileNumber(getStreamer().emitDwarfFileDirective( 878 /*CUID=*/0, getContext().getCompilationDir(), RootFile.Name, 879 RootFile.Checksum, RootFile.Source)); 880 } 881 return true; 882 } 883 884 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) { 885 // Create the initial section, if requested. 886 if (!NoInitialTextSection) 887 Out.InitSections(false); 888 889 // Prime the lexer. 890 Lex(); 891 892 HadError = false; 893 AsmCond StartingCondState = TheCondState; 894 SmallVector<AsmRewrite, 4> AsmStrRewrites; 895 896 // If we are generating dwarf for assembly source files save the initial text 897 // section. (Don't use enabledGenDwarfForAssembly() here, as we aren't 898 // emitting any actual debug info yet and haven't had a chance to parse any 899 // embedded .file directives.) 900 if (getContext().getGenDwarfForAssembly()) { 901 MCSection *Sec = getStreamer().getCurrentSectionOnly(); 902 if (!Sec->getBeginSymbol()) { 903 MCSymbol *SectionStartSym = getContext().createTempSymbol(); 904 getStreamer().emitLabel(SectionStartSym); 905 Sec->setBeginSymbol(SectionStartSym); 906 } 907 bool InsertResult = getContext().addGenDwarfSection(Sec); 908 assert(InsertResult && ".text section should not have debug info yet"); 909 (void)InsertResult; 910 } 911 912 StringRef Filename = getContext().getMainFileName(); 913 if (!Filename.empty() && (Filename.compare(StringRef("-")) != 0)) 914 Out.emitFileDirective(Filename); 915 916 // While we have input, parse each statement. 917 while (Lexer.isNot(AsmToken::Eof)) { 918 ParseStatementInfo Info(&AsmStrRewrites); 919 bool Parsed = parseStatement(Info, nullptr); 920 921 // If we have a Lexer Error we are on an Error Token. Load in Lexer Error 922 // for printing ErrMsg via Lex() only if no (presumably better) parser error 923 // exists. 924 if (Parsed && !hasPendingError() && Lexer.getTok().is(AsmToken::Error)) { 925 Lex(); 926 } 927 928 // parseStatement returned true so may need to emit an error. 929 printPendingErrors(); 930 931 // Skipping to the next line if needed. 932 if (Parsed && !getLexer().isAtStartOfStatement()) 933 eatToEndOfStatement(); 934 } 935 936 getTargetParser().onEndOfFile(); 937 printPendingErrors(); 938 939 // All errors should have been emitted. 940 assert(!hasPendingError() && "unexpected error from parseStatement"); 941 942 getTargetParser().flushPendingInstructions(getStreamer()); 943 944 if (TheCondState.TheCond != StartingCondState.TheCond || 945 TheCondState.Ignore != StartingCondState.Ignore) 946 printError(getTok().getLoc(), "unmatched .ifs or .elses"); 947 // Check to see there are no empty DwarfFile slots. 948 const auto &LineTables = getContext().getMCDwarfLineTables(); 949 if (!LineTables.empty()) { 950 unsigned Index = 0; 951 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) { 952 if (File.Name.empty() && Index != 0) 953 printError(getTok().getLoc(), "unassigned file number: " + 954 Twine(Index) + 955 " for .file directives"); 956 ++Index; 957 } 958 } 959 960 // Check to see that all assembler local symbols were actually defined. 961 // Targets that don't do subsections via symbols may not want this, though, 962 // so conservatively exclude them. Only do this if we're finalizing, though, 963 // as otherwise we won't necessarilly have seen everything yet. 964 if (!NoFinalize) { 965 if (MAI.hasSubsectionsViaSymbols()) { 966 for (const auto &TableEntry : getContext().getSymbols()) { 967 MCSymbol *Sym = TableEntry.getValue(); 968 // Variable symbols may not be marked as defined, so check those 969 // explicitly. If we know it's a variable, we have a definition for 970 // the purposes of this check. 971 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined()) 972 // FIXME: We would really like to refer back to where the symbol was 973 // first referenced for a source location. We need to add something 974 // to track that. Currently, we just point to the end of the file. 975 printError(getTok().getLoc(), "assembler local symbol '" + 976 Sym->getName() + "' not defined"); 977 } 978 } 979 980 // Temporary symbols like the ones for directional jumps don't go in the 981 // symbol table. They also need to be diagnosed in all (final) cases. 982 for (std::tuple<SMLoc, CppHashInfoTy, MCSymbol *> &LocSym : DirLabels) { 983 if (std::get<2>(LocSym)->isUndefined()) { 984 // Reset the state of any "# line file" directives we've seen to the 985 // context as it was at the diagnostic site. 986 CppHashInfo = std::get<1>(LocSym); 987 printError(std::get<0>(LocSym), "directional label undefined"); 988 } 989 } 990 } 991 992 // Finalize the output stream if there are no errors and if the client wants 993 // us to. 994 if (!HadError && !NoFinalize) 995 Out.Finish(); 996 997 return HadError || getContext().hadError(); 998 } 999 1000 bool AsmParser::checkForValidSection() { 1001 if (!ParsingMSInlineAsm && !getStreamer().getCurrentSectionOnly()) { 1002 Out.InitSections(false); 1003 return Error(getTok().getLoc(), 1004 "expected section directive before assembly directive"); 1005 } 1006 return false; 1007 } 1008 1009 /// Throw away the rest of the line for testing purposes. 1010 void AsmParser::eatToEndOfStatement() { 1011 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof)) 1012 Lexer.Lex(); 1013 1014 // Eat EOL. 1015 if (Lexer.is(AsmToken::EndOfStatement)) 1016 Lexer.Lex(); 1017 } 1018 1019 StringRef AsmParser::parseStringToEndOfStatement() { 1020 const char *Start = getTok().getLoc().getPointer(); 1021 1022 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof)) 1023 Lexer.Lex(); 1024 1025 const char *End = getTok().getLoc().getPointer(); 1026 return StringRef(Start, End - Start); 1027 } 1028 1029 StringRef AsmParser::parseStringToComma() { 1030 const char *Start = getTok().getLoc().getPointer(); 1031 1032 while (Lexer.isNot(AsmToken::EndOfStatement) && 1033 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof)) 1034 Lexer.Lex(); 1035 1036 const char *End = getTok().getLoc().getPointer(); 1037 return StringRef(Start, End - Start); 1038 } 1039 1040 /// Parse a paren expression and return it. 1041 /// NOTE: This assumes the leading '(' has already been consumed. 1042 /// 1043 /// parenexpr ::= expr) 1044 /// 1045 bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) { 1046 if (parseExpression(Res)) 1047 return true; 1048 if (Lexer.isNot(AsmToken::RParen)) 1049 return TokError("expected ')' in parentheses expression"); 1050 EndLoc = Lexer.getTok().getEndLoc(); 1051 Lex(); 1052 return false; 1053 } 1054 1055 /// Parse a bracket expression and return it. 1056 /// NOTE: This assumes the leading '[' has already been consumed. 1057 /// 1058 /// bracketexpr ::= expr] 1059 /// 1060 bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) { 1061 if (parseExpression(Res)) 1062 return true; 1063 EndLoc = getTok().getEndLoc(); 1064 if (parseToken(AsmToken::RBrac, "expected ']' in brackets expression")) 1065 return true; 1066 return false; 1067 } 1068 1069 /// Parse a primary expression and return it. 1070 /// primaryexpr ::= (parenexpr 1071 /// primaryexpr ::= symbol 1072 /// primaryexpr ::= number 1073 /// primaryexpr ::= '.' 1074 /// primaryexpr ::= ~,+,- primaryexpr 1075 bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) { 1076 SMLoc FirstTokenLoc = getLexer().getLoc(); 1077 AsmToken::TokenKind FirstTokenKind = Lexer.getKind(); 1078 switch (FirstTokenKind) { 1079 default: 1080 return TokError("unknown token in expression"); 1081 // If we have an error assume that we've already handled it. 1082 case AsmToken::Error: 1083 return true; 1084 case AsmToken::Exclaim: 1085 Lex(); // Eat the operator. 1086 if (parsePrimaryExpr(Res, EndLoc)) 1087 return true; 1088 Res = MCUnaryExpr::createLNot(Res, getContext(), FirstTokenLoc); 1089 return false; 1090 case AsmToken::Dollar: 1091 case AsmToken::At: 1092 case AsmToken::String: 1093 case AsmToken::Identifier: { 1094 StringRef Identifier; 1095 if (parseIdentifier(Identifier)) { 1096 // We may have failed but $ may be a valid token. 1097 if (getTok().is(AsmToken::Dollar)) { 1098 if (Lexer.getMAI().getDollarIsPC()) { 1099 Lex(); 1100 // This is a '$' reference, which references the current PC. Emit a 1101 // temporary label to the streamer and refer to it. 1102 MCSymbol *Sym = Ctx.createTempSymbol(); 1103 Out.emitLabel(Sym); 1104 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, 1105 getContext()); 1106 EndLoc = FirstTokenLoc; 1107 return false; 1108 } 1109 return Error(FirstTokenLoc, "invalid token in expression"); 1110 } 1111 } 1112 // Parse symbol variant 1113 std::pair<StringRef, StringRef> Split; 1114 if (!MAI.useParensForSymbolVariant()) { 1115 if (FirstTokenKind == AsmToken::String) { 1116 if (Lexer.is(AsmToken::At)) { 1117 Lex(); // eat @ 1118 SMLoc AtLoc = getLexer().getLoc(); 1119 StringRef VName; 1120 if (parseIdentifier(VName)) 1121 return Error(AtLoc, "expected symbol variant after '@'"); 1122 1123 Split = std::make_pair(Identifier, VName); 1124 } 1125 } else { 1126 Split = Identifier.split('@'); 1127 } 1128 } else if (Lexer.is(AsmToken::LParen)) { 1129 Lex(); // eat '('. 1130 StringRef VName; 1131 parseIdentifier(VName); 1132 // eat ')'. 1133 if (parseToken(AsmToken::RParen, 1134 "unexpected token in variant, expected ')'")) 1135 return true; 1136 Split = std::make_pair(Identifier, VName); 1137 } 1138 1139 EndLoc = SMLoc::getFromPointer(Identifier.end()); 1140 1141 // This is a symbol reference. 1142 StringRef SymbolName = Identifier; 1143 if (SymbolName.empty()) 1144 return Error(getLexer().getLoc(), "expected a symbol reference"); 1145 1146 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None; 1147 1148 // Lookup the symbol variant if used. 1149 if (!Split.second.empty()) { 1150 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second); 1151 if (Variant != MCSymbolRefExpr::VK_Invalid) { 1152 SymbolName = Split.first; 1153 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) { 1154 Variant = MCSymbolRefExpr::VK_None; 1155 } else { 1156 return Error(SMLoc::getFromPointer(Split.second.begin()), 1157 "invalid variant '" + Split.second + "'"); 1158 } 1159 } 1160 1161 MCSymbol *Sym = getContext().getInlineAsmLabel(SymbolName); 1162 if (!Sym) 1163 Sym = getContext().getOrCreateSymbol(SymbolName); 1164 1165 // If this is an absolute variable reference, substitute it now to preserve 1166 // semantics in the face of reassignment. 1167 if (Sym->isVariable()) { 1168 auto V = Sym->getVariableValue(/*SetUsed*/ false); 1169 bool DoInline = isa<MCConstantExpr>(V) && !Variant; 1170 if (auto TV = dyn_cast<MCTargetExpr>(V)) 1171 DoInline = TV->inlineAssignedExpr(); 1172 if (DoInline) { 1173 if (Variant) 1174 return Error(EndLoc, "unexpected modifier on variable reference"); 1175 Res = Sym->getVariableValue(/*SetUsed*/ false); 1176 return false; 1177 } 1178 } 1179 1180 // Otherwise create a symbol ref. 1181 Res = MCSymbolRefExpr::create(Sym, Variant, getContext(), FirstTokenLoc); 1182 return false; 1183 } 1184 case AsmToken::BigNum: 1185 return TokError("literal value out of range for directive"); 1186 case AsmToken::Integer: { 1187 SMLoc Loc = getTok().getLoc(); 1188 int64_t IntVal = getTok().getIntVal(); 1189 Res = MCConstantExpr::create(IntVal, getContext()); 1190 EndLoc = Lexer.getTok().getEndLoc(); 1191 Lex(); // Eat token. 1192 // Look for 'b' or 'f' following an Integer as a directional label 1193 if (Lexer.getKind() == AsmToken::Identifier) { 1194 StringRef IDVal = getTok().getString(); 1195 // Lookup the symbol variant if used. 1196 std::pair<StringRef, StringRef> Split = IDVal.split('@'); 1197 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None; 1198 if (Split.first.size() != IDVal.size()) { 1199 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second); 1200 if (Variant == MCSymbolRefExpr::VK_Invalid) 1201 return TokError("invalid variant '" + Split.second + "'"); 1202 IDVal = Split.first; 1203 } 1204 if (IDVal == "f" || IDVal == "b") { 1205 MCSymbol *Sym = 1206 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b"); 1207 Res = MCSymbolRefExpr::create(Sym, Variant, getContext()); 1208 if (IDVal == "b" && Sym->isUndefined()) 1209 return Error(Loc, "directional label undefined"); 1210 DirLabels.push_back(std::make_tuple(Loc, CppHashInfo, Sym)); 1211 EndLoc = Lexer.getTok().getEndLoc(); 1212 Lex(); // Eat identifier. 1213 } 1214 } 1215 return false; 1216 } 1217 case AsmToken::Real: { 1218 APFloat RealVal(APFloat::IEEEdouble(), getTok().getString()); 1219 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue(); 1220 Res = MCConstantExpr::create(IntVal, getContext()); 1221 EndLoc = Lexer.getTok().getEndLoc(); 1222 Lex(); // Eat token. 1223 return false; 1224 } 1225 case AsmToken::Dot: { 1226 // This is a '.' reference, which references the current PC. Emit a 1227 // temporary label to the streamer and refer to it. 1228 MCSymbol *Sym = Ctx.createTempSymbol(); 1229 Out.emitLabel(Sym); 1230 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext()); 1231 EndLoc = Lexer.getTok().getEndLoc(); 1232 Lex(); // Eat identifier. 1233 return false; 1234 } 1235 case AsmToken::LParen: 1236 Lex(); // Eat the '('. 1237 return parseParenExpr(Res, EndLoc); 1238 case AsmToken::LBrac: 1239 if (!PlatformParser->HasBracketExpressions()) 1240 return TokError("brackets expression not supported on this target"); 1241 Lex(); // Eat the '['. 1242 return parseBracketExpr(Res, EndLoc); 1243 case AsmToken::Minus: 1244 Lex(); // Eat the operator. 1245 if (parsePrimaryExpr(Res, EndLoc)) 1246 return true; 1247 Res = MCUnaryExpr::createMinus(Res, getContext(), FirstTokenLoc); 1248 return false; 1249 case AsmToken::Plus: 1250 Lex(); // Eat the operator. 1251 if (parsePrimaryExpr(Res, EndLoc)) 1252 return true; 1253 Res = MCUnaryExpr::createPlus(Res, getContext(), FirstTokenLoc); 1254 return false; 1255 case AsmToken::Tilde: 1256 Lex(); // Eat the operator. 1257 if (parsePrimaryExpr(Res, EndLoc)) 1258 return true; 1259 Res = MCUnaryExpr::createNot(Res, getContext(), FirstTokenLoc); 1260 return false; 1261 // MIPS unary expression operators. The lexer won't generate these tokens if 1262 // MCAsmInfo::HasMipsExpressions is false for the target. 1263 case AsmToken::PercentCall16: 1264 case AsmToken::PercentCall_Hi: 1265 case AsmToken::PercentCall_Lo: 1266 case AsmToken::PercentDtprel_Hi: 1267 case AsmToken::PercentDtprel_Lo: 1268 case AsmToken::PercentGot: 1269 case AsmToken::PercentGot_Disp: 1270 case AsmToken::PercentGot_Hi: 1271 case AsmToken::PercentGot_Lo: 1272 case AsmToken::PercentGot_Ofst: 1273 case AsmToken::PercentGot_Page: 1274 case AsmToken::PercentGottprel: 1275 case AsmToken::PercentGp_Rel: 1276 case AsmToken::PercentHi: 1277 case AsmToken::PercentHigher: 1278 case AsmToken::PercentHighest: 1279 case AsmToken::PercentLo: 1280 case AsmToken::PercentNeg: 1281 case AsmToken::PercentPcrel_Hi: 1282 case AsmToken::PercentPcrel_Lo: 1283 case AsmToken::PercentTlsgd: 1284 case AsmToken::PercentTlsldm: 1285 case AsmToken::PercentTprel_Hi: 1286 case AsmToken::PercentTprel_Lo: 1287 Lex(); // Eat the operator. 1288 if (Lexer.isNot(AsmToken::LParen)) 1289 return TokError("expected '(' after operator"); 1290 Lex(); // Eat the operator. 1291 if (parseExpression(Res, EndLoc)) 1292 return true; 1293 if (Lexer.isNot(AsmToken::RParen)) 1294 return TokError("expected ')'"); 1295 Lex(); // Eat the operator. 1296 Res = getTargetParser().createTargetUnaryExpr(Res, FirstTokenKind, Ctx); 1297 return !Res; 1298 } 1299 } 1300 1301 bool AsmParser::parseExpression(const MCExpr *&Res) { 1302 SMLoc EndLoc; 1303 return parseExpression(Res, EndLoc); 1304 } 1305 1306 const MCExpr * 1307 AsmParser::applyModifierToExpr(const MCExpr *E, 1308 MCSymbolRefExpr::VariantKind Variant) { 1309 // Ask the target implementation about this expression first. 1310 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx); 1311 if (NewE) 1312 return NewE; 1313 // Recurse over the given expression, rebuilding it to apply the given variant 1314 // if there is exactly one symbol. 1315 switch (E->getKind()) { 1316 case MCExpr::Target: 1317 case MCExpr::Constant: 1318 return nullptr; 1319 1320 case MCExpr::SymbolRef: { 1321 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E); 1322 1323 if (SRE->getKind() != MCSymbolRefExpr::VK_None) { 1324 TokError("invalid variant on expression '" + getTok().getIdentifier() + 1325 "' (already modified)"); 1326 return E; 1327 } 1328 1329 return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext()); 1330 } 1331 1332 case MCExpr::Unary: { 1333 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E); 1334 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant); 1335 if (!Sub) 1336 return nullptr; 1337 return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext()); 1338 } 1339 1340 case MCExpr::Binary: { 1341 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E); 1342 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant); 1343 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant); 1344 1345 if (!LHS && !RHS) 1346 return nullptr; 1347 1348 if (!LHS) 1349 LHS = BE->getLHS(); 1350 if (!RHS) 1351 RHS = BE->getRHS(); 1352 1353 return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext()); 1354 } 1355 } 1356 1357 llvm_unreachable("Invalid expression kind!"); 1358 } 1359 1360 /// This function checks if the next token is <string> type or arithmetic. 1361 /// string that begin with character '<' must end with character '>'. 1362 /// otherwise it is arithmetics. 1363 /// If the function returns a 'true' value, 1364 /// the End argument will be filled with the last location pointed to the '>' 1365 /// character. 1366 1367 /// There is a gap between the AltMacro's documentation and the single quote 1368 /// implementation. GCC does not fully support this feature and so we will not 1369 /// support it. 1370 /// TODO: Adding single quote as a string. 1371 static bool isAngleBracketString(SMLoc &StrLoc, SMLoc &EndLoc) { 1372 assert((StrLoc.getPointer() != nullptr) && 1373 "Argument to the function cannot be a NULL value"); 1374 const char *CharPtr = StrLoc.getPointer(); 1375 while ((*CharPtr != '>') && (*CharPtr != '\n') && (*CharPtr != '\r') && 1376 (*CharPtr != '\0')) { 1377 if (*CharPtr == '!') 1378 CharPtr++; 1379 CharPtr++; 1380 } 1381 if (*CharPtr == '>') { 1382 EndLoc = StrLoc.getFromPointer(CharPtr + 1); 1383 return true; 1384 } 1385 return false; 1386 } 1387 1388 /// creating a string without the escape characters '!'. 1389 static std::string angleBracketString(StringRef AltMacroStr) { 1390 std::string Res; 1391 for (size_t Pos = 0; Pos < AltMacroStr.size(); Pos++) { 1392 if (AltMacroStr[Pos] == '!') 1393 Pos++; 1394 Res += AltMacroStr[Pos]; 1395 } 1396 return Res; 1397 } 1398 1399 /// Parse an expression and return it. 1400 /// 1401 /// expr ::= expr &&,|| expr -> lowest. 1402 /// expr ::= expr |,^,&,! expr 1403 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr 1404 /// expr ::= expr <<,>> expr 1405 /// expr ::= expr +,- expr 1406 /// expr ::= expr *,/,% expr -> highest. 1407 /// expr ::= primaryexpr 1408 /// 1409 bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) { 1410 // Parse the expression. 1411 Res = nullptr; 1412 if (getTargetParser().parsePrimaryExpr(Res, EndLoc) || 1413 parseBinOpRHS(1, Res, EndLoc)) 1414 return true; 1415 1416 // As a special case, we support 'a op b @ modifier' by rewriting the 1417 // expression to include the modifier. This is inefficient, but in general we 1418 // expect users to use 'a@modifier op b'. 1419 if (Lexer.getKind() == AsmToken::At) { 1420 Lex(); 1421 1422 if (Lexer.isNot(AsmToken::Identifier)) 1423 return TokError("unexpected symbol modifier following '@'"); 1424 1425 MCSymbolRefExpr::VariantKind Variant = 1426 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier()); 1427 if (Variant == MCSymbolRefExpr::VK_Invalid) 1428 return TokError("invalid variant '" + getTok().getIdentifier() + "'"); 1429 1430 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant); 1431 if (!ModifiedRes) { 1432 return TokError("invalid modifier '" + getTok().getIdentifier() + 1433 "' (no symbols present)"); 1434 } 1435 1436 Res = ModifiedRes; 1437 Lex(); 1438 } 1439 1440 // Try to constant fold it up front, if possible. Do not exploit 1441 // assembler here. 1442 int64_t Value; 1443 if (Res->evaluateAsAbsolute(Value)) 1444 Res = MCConstantExpr::create(Value, getContext()); 1445 1446 return false; 1447 } 1448 1449 bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) { 1450 Res = nullptr; 1451 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc); 1452 } 1453 1454 bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res, 1455 SMLoc &EndLoc) { 1456 if (parseParenExpr(Res, EndLoc)) 1457 return true; 1458 1459 for (; ParenDepth > 0; --ParenDepth) { 1460 if (parseBinOpRHS(1, Res, EndLoc)) 1461 return true; 1462 1463 // We don't Lex() the last RParen. 1464 // This is the same behavior as parseParenExpression(). 1465 if (ParenDepth - 1 > 0) { 1466 EndLoc = getTok().getEndLoc(); 1467 if (parseToken(AsmToken::RParen, 1468 "expected ')' in parentheses expression")) 1469 return true; 1470 } 1471 } 1472 return false; 1473 } 1474 1475 bool AsmParser::parseAbsoluteExpression(int64_t &Res) { 1476 const MCExpr *Expr; 1477 1478 SMLoc StartLoc = Lexer.getLoc(); 1479 if (parseExpression(Expr)) 1480 return true; 1481 1482 if (!Expr->evaluateAsAbsolute(Res, getStreamer().getAssemblerPtr())) 1483 return Error(StartLoc, "expected absolute expression"); 1484 1485 return false; 1486 } 1487 1488 static unsigned getDarwinBinOpPrecedence(AsmToken::TokenKind K, 1489 MCBinaryExpr::Opcode &Kind, 1490 bool ShouldUseLogicalShr) { 1491 switch (K) { 1492 default: 1493 return 0; // not a binop. 1494 1495 // Lowest Precedence: &&, || 1496 case AsmToken::AmpAmp: 1497 Kind = MCBinaryExpr::LAnd; 1498 return 1; 1499 case AsmToken::PipePipe: 1500 Kind = MCBinaryExpr::LOr; 1501 return 1; 1502 1503 // Low Precedence: |, &, ^ 1504 // 1505 // FIXME: gas seems to support '!' as an infix operator? 1506 case AsmToken::Pipe: 1507 Kind = MCBinaryExpr::Or; 1508 return 2; 1509 case AsmToken::Caret: 1510 Kind = MCBinaryExpr::Xor; 1511 return 2; 1512 case AsmToken::Amp: 1513 Kind = MCBinaryExpr::And; 1514 return 2; 1515 1516 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >= 1517 case AsmToken::EqualEqual: 1518 Kind = MCBinaryExpr::EQ; 1519 return 3; 1520 case AsmToken::ExclaimEqual: 1521 case AsmToken::LessGreater: 1522 Kind = MCBinaryExpr::NE; 1523 return 3; 1524 case AsmToken::Less: 1525 Kind = MCBinaryExpr::LT; 1526 return 3; 1527 case AsmToken::LessEqual: 1528 Kind = MCBinaryExpr::LTE; 1529 return 3; 1530 case AsmToken::Greater: 1531 Kind = MCBinaryExpr::GT; 1532 return 3; 1533 case AsmToken::GreaterEqual: 1534 Kind = MCBinaryExpr::GTE; 1535 return 3; 1536 1537 // Intermediate Precedence: <<, >> 1538 case AsmToken::LessLess: 1539 Kind = MCBinaryExpr::Shl; 1540 return 4; 1541 case AsmToken::GreaterGreater: 1542 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr; 1543 return 4; 1544 1545 // High Intermediate Precedence: +, - 1546 case AsmToken::Plus: 1547 Kind = MCBinaryExpr::Add; 1548 return 5; 1549 case AsmToken::Minus: 1550 Kind = MCBinaryExpr::Sub; 1551 return 5; 1552 1553 // Highest Precedence: *, /, % 1554 case AsmToken::Star: 1555 Kind = MCBinaryExpr::Mul; 1556 return 6; 1557 case AsmToken::Slash: 1558 Kind = MCBinaryExpr::Div; 1559 return 6; 1560 case AsmToken::Percent: 1561 Kind = MCBinaryExpr::Mod; 1562 return 6; 1563 } 1564 } 1565 1566 static unsigned getGNUBinOpPrecedence(AsmToken::TokenKind K, 1567 MCBinaryExpr::Opcode &Kind, 1568 bool ShouldUseLogicalShr) { 1569 switch (K) { 1570 default: 1571 return 0; // not a binop. 1572 1573 // Lowest Precedence: &&, || 1574 case AsmToken::AmpAmp: 1575 Kind = MCBinaryExpr::LAnd; 1576 return 2; 1577 case AsmToken::PipePipe: 1578 Kind = MCBinaryExpr::LOr; 1579 return 1; 1580 1581 // Low Precedence: ==, !=, <>, <, <=, >, >= 1582 case AsmToken::EqualEqual: 1583 Kind = MCBinaryExpr::EQ; 1584 return 3; 1585 case AsmToken::ExclaimEqual: 1586 case AsmToken::LessGreater: 1587 Kind = MCBinaryExpr::NE; 1588 return 3; 1589 case AsmToken::Less: 1590 Kind = MCBinaryExpr::LT; 1591 return 3; 1592 case AsmToken::LessEqual: 1593 Kind = MCBinaryExpr::LTE; 1594 return 3; 1595 case AsmToken::Greater: 1596 Kind = MCBinaryExpr::GT; 1597 return 3; 1598 case AsmToken::GreaterEqual: 1599 Kind = MCBinaryExpr::GTE; 1600 return 3; 1601 1602 // Low Intermediate Precedence: +, - 1603 case AsmToken::Plus: 1604 Kind = MCBinaryExpr::Add; 1605 return 4; 1606 case AsmToken::Minus: 1607 Kind = MCBinaryExpr::Sub; 1608 return 4; 1609 1610 // High Intermediate Precedence: |, &, ^ 1611 // 1612 // FIXME: gas seems to support '!' as an infix operator? 1613 case AsmToken::Pipe: 1614 Kind = MCBinaryExpr::Or; 1615 return 5; 1616 case AsmToken::Caret: 1617 Kind = MCBinaryExpr::Xor; 1618 return 5; 1619 case AsmToken::Amp: 1620 Kind = MCBinaryExpr::And; 1621 return 5; 1622 1623 // Highest Precedence: *, /, %, <<, >> 1624 case AsmToken::Star: 1625 Kind = MCBinaryExpr::Mul; 1626 return 6; 1627 case AsmToken::Slash: 1628 Kind = MCBinaryExpr::Div; 1629 return 6; 1630 case AsmToken::Percent: 1631 Kind = MCBinaryExpr::Mod; 1632 return 6; 1633 case AsmToken::LessLess: 1634 Kind = MCBinaryExpr::Shl; 1635 return 6; 1636 case AsmToken::GreaterGreater: 1637 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr; 1638 return 6; 1639 } 1640 } 1641 1642 unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K, 1643 MCBinaryExpr::Opcode &Kind) { 1644 bool ShouldUseLogicalShr = MAI.shouldUseLogicalShr(); 1645 return IsDarwin ? getDarwinBinOpPrecedence(K, Kind, ShouldUseLogicalShr) 1646 : getGNUBinOpPrecedence(K, Kind, ShouldUseLogicalShr); 1647 } 1648 1649 /// Parse all binary operators with precedence >= 'Precedence'. 1650 /// Res contains the LHS of the expression on input. 1651 bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, 1652 SMLoc &EndLoc) { 1653 SMLoc StartLoc = Lexer.getLoc(); 1654 while (true) { 1655 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add; 1656 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind); 1657 1658 // If the next token is lower precedence than we are allowed to eat, return 1659 // successfully with what we ate already. 1660 if (TokPrec < Precedence) 1661 return false; 1662 1663 Lex(); 1664 1665 // Eat the next primary expression. 1666 const MCExpr *RHS; 1667 if (getTargetParser().parsePrimaryExpr(RHS, EndLoc)) 1668 return true; 1669 1670 // If BinOp binds less tightly with RHS than the operator after RHS, let 1671 // the pending operator take RHS as its LHS. 1672 MCBinaryExpr::Opcode Dummy; 1673 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy); 1674 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc)) 1675 return true; 1676 1677 // Merge LHS and RHS according to operator. 1678 Res = MCBinaryExpr::create(Kind, Res, RHS, getContext(), StartLoc); 1679 } 1680 } 1681 1682 /// ParseStatement: 1683 /// ::= EndOfStatement 1684 /// ::= Label* Directive ...Operands... EndOfStatement 1685 /// ::= Label* Identifier OperandList* EndOfStatement 1686 bool AsmParser::parseStatement(ParseStatementInfo &Info, 1687 MCAsmParserSemaCallback *SI) { 1688 assert(!hasPendingError() && "parseStatement started with pending error"); 1689 // Eat initial spaces and comments 1690 while (Lexer.is(AsmToken::Space)) 1691 Lex(); 1692 if (Lexer.is(AsmToken::EndOfStatement)) { 1693 // if this is a line comment we can drop it safely 1694 if (getTok().getString().empty() || getTok().getString().front() == '\r' || 1695 getTok().getString().front() == '\n') 1696 Out.AddBlankLine(); 1697 Lex(); 1698 return false; 1699 } 1700 // Statements always start with an identifier. 1701 AsmToken ID = getTok(); 1702 SMLoc IDLoc = ID.getLoc(); 1703 StringRef IDVal; 1704 int64_t LocalLabelVal = -1; 1705 if (Lexer.is(AsmToken::HashDirective)) 1706 return parseCppHashLineFilenameComment(IDLoc, 1707 !isInsideMacroInstantiation()); 1708 1709 // Allow an integer followed by a ':' as a directional local label. 1710 if (Lexer.is(AsmToken::Integer)) { 1711 LocalLabelVal = getTok().getIntVal(); 1712 if (LocalLabelVal < 0) { 1713 if (!TheCondState.Ignore) { 1714 Lex(); // always eat a token 1715 return Error(IDLoc, "unexpected token at start of statement"); 1716 } 1717 IDVal = ""; 1718 } else { 1719 IDVal = getTok().getString(); 1720 Lex(); // Consume the integer token to be used as an identifier token. 1721 if (Lexer.getKind() != AsmToken::Colon) { 1722 if (!TheCondState.Ignore) { 1723 Lex(); // always eat a token 1724 return Error(IDLoc, "unexpected token at start of statement"); 1725 } 1726 } 1727 } 1728 } else if (Lexer.is(AsmToken::Dot)) { 1729 // Treat '.' as a valid identifier in this context. 1730 Lex(); 1731 IDVal = "."; 1732 } else if (Lexer.is(AsmToken::LCurly)) { 1733 // Treat '{' as a valid identifier in this context. 1734 Lex(); 1735 IDVal = "{"; 1736 1737 } else if (Lexer.is(AsmToken::RCurly)) { 1738 // Treat '}' as a valid identifier in this context. 1739 Lex(); 1740 IDVal = "}"; 1741 } else if (Lexer.is(AsmToken::Star) && 1742 getTargetParser().starIsStartOfStatement()) { 1743 // Accept '*' as a valid start of statement. 1744 Lex(); 1745 IDVal = "*"; 1746 } else if (parseIdentifier(IDVal)) { 1747 if (!TheCondState.Ignore) { 1748 Lex(); // always eat a token 1749 return Error(IDLoc, "unexpected token at start of statement"); 1750 } 1751 IDVal = ""; 1752 } 1753 1754 // Handle conditional assembly here before checking for skipping. We 1755 // have to do this so that .endif isn't skipped in a ".if 0" block for 1756 // example. 1757 StringMap<DirectiveKind>::const_iterator DirKindIt = 1758 DirectiveKindMap.find(IDVal.lower()); 1759 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end()) 1760 1761 ? DK_NO_DIRECTIVE 1762 : DirKindIt->getValue(); 1763 switch (DirKind) { 1764 default: 1765 break; 1766 case DK_IF: 1767 case DK_IFEQ: 1768 case DK_IFGE: 1769 case DK_IFGT: 1770 case DK_IFLE: 1771 case DK_IFLT: 1772 case DK_IFNE: 1773 return parseDirectiveIf(IDLoc, DirKind); 1774 case DK_IFB: 1775 return parseDirectiveIfb(IDLoc, true); 1776 case DK_IFNB: 1777 return parseDirectiveIfb(IDLoc, false); 1778 case DK_IFC: 1779 return parseDirectiveIfc(IDLoc, true); 1780 case DK_IFEQS: 1781 return parseDirectiveIfeqs(IDLoc, true); 1782 case DK_IFNC: 1783 return parseDirectiveIfc(IDLoc, false); 1784 case DK_IFNES: 1785 return parseDirectiveIfeqs(IDLoc, false); 1786 case DK_IFDEF: 1787 return parseDirectiveIfdef(IDLoc, true); 1788 case DK_IFNDEF: 1789 case DK_IFNOTDEF: 1790 return parseDirectiveIfdef(IDLoc, false); 1791 case DK_ELSEIF: 1792 return parseDirectiveElseIf(IDLoc); 1793 case DK_ELSE: 1794 return parseDirectiveElse(IDLoc); 1795 case DK_ENDIF: 1796 return parseDirectiveEndIf(IDLoc); 1797 } 1798 1799 // Ignore the statement if in the middle of inactive conditional 1800 // (e.g. ".if 0"). 1801 if (TheCondState.Ignore) { 1802 eatToEndOfStatement(); 1803 return false; 1804 } 1805 1806 // FIXME: Recurse on local labels? 1807 1808 // See what kind of statement we have. 1809 switch (Lexer.getKind()) { 1810 case AsmToken::Colon: { 1811 if (!getTargetParser().isLabel(ID)) 1812 break; 1813 if (checkForValidSection()) 1814 return true; 1815 1816 // identifier ':' -> Label. 1817 Lex(); 1818 1819 // Diagnose attempt to use '.' as a label. 1820 if (IDVal == ".") 1821 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label"); 1822 1823 // Diagnose attempt to use a variable as a label. 1824 // 1825 // FIXME: Diagnostics. Note the location of the definition as a label. 1826 // FIXME: This doesn't diagnose assignment to a symbol which has been 1827 // implicitly marked as external. 1828 MCSymbol *Sym; 1829 if (LocalLabelVal == -1) { 1830 if (ParsingMSInlineAsm && SI) { 1831 StringRef RewrittenLabel = 1832 SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true); 1833 assert(!RewrittenLabel.empty() && 1834 "We should have an internal name here."); 1835 Info.AsmRewrites->emplace_back(AOK_Label, IDLoc, IDVal.size(), 1836 RewrittenLabel); 1837 IDVal = RewrittenLabel; 1838 } 1839 Sym = getContext().getOrCreateSymbol(IDVal); 1840 } else 1841 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal); 1842 // End of Labels should be treated as end of line for lexing 1843 // purposes but that information is not available to the Lexer who 1844 // does not understand Labels. This may cause us to see a Hash 1845 // here instead of a preprocessor line comment. 1846 if (getTok().is(AsmToken::Hash)) { 1847 StringRef CommentStr = parseStringToEndOfStatement(); 1848 Lexer.Lex(); 1849 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr)); 1850 } 1851 1852 // Consume any end of statement token, if present, to avoid spurious 1853 // AddBlankLine calls(). 1854 if (getTok().is(AsmToken::EndOfStatement)) { 1855 Lex(); 1856 } 1857 1858 getTargetParser().doBeforeLabelEmit(Sym); 1859 1860 // Emit the label. 1861 if (!getTargetParser().isParsingMSInlineAsm()) 1862 Out.emitLabel(Sym, IDLoc); 1863 1864 // If we are generating dwarf for assembly source files then gather the 1865 // info to make a dwarf label entry for this label if needed. 1866 if (enabledGenDwarfForAssembly()) 1867 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(), 1868 IDLoc); 1869 1870 getTargetParser().onLabelParsed(Sym); 1871 1872 return false; 1873 } 1874 1875 case AsmToken::Equal: 1876 if (!getTargetParser().equalIsAsmAssignment()) 1877 break; 1878 // identifier '=' ... -> assignment statement 1879 Lex(); 1880 1881 return parseAssignment(IDVal, true); 1882 1883 default: // Normal instruction or directive. 1884 break; 1885 } 1886 1887 // If macros are enabled, check to see if this is a macro instantiation. 1888 if (areMacrosEnabled()) 1889 if (const MCAsmMacro *M = getContext().lookupMacro(IDVal)) { 1890 return handleMacroEntry(M, IDLoc); 1891 } 1892 1893 // Otherwise, we have a normal instruction or directive. 1894 1895 // Directives start with "." 1896 if (IDVal.startswith(".") && IDVal != ".") { 1897 // There are several entities interested in parsing directives: 1898 // 1899 // 1. The target-specific assembly parser. Some directives are target 1900 // specific or may potentially behave differently on certain targets. 1901 // 2. Asm parser extensions. For example, platform-specific parsers 1902 // (like the ELF parser) register themselves as extensions. 1903 // 3. The generic directive parser implemented by this class. These are 1904 // all the directives that behave in a target and platform independent 1905 // manner, or at least have a default behavior that's shared between 1906 // all targets and platforms. 1907 1908 getTargetParser().flushPendingInstructions(getStreamer()); 1909 1910 SMLoc StartTokLoc = getTok().getLoc(); 1911 bool TPDirectiveReturn = getTargetParser().ParseDirective(ID); 1912 1913 if (hasPendingError()) 1914 return true; 1915 // Currently the return value should be true if we are 1916 // uninterested but as this is at odds with the standard parsing 1917 // convention (return true = error) we have instances of a parsed 1918 // directive that fails returning true as an error. Catch these 1919 // cases as best as possible errors here. 1920 if (TPDirectiveReturn && StartTokLoc != getTok().getLoc()) 1921 return true; 1922 // Return if we did some parsing or believe we succeeded. 1923 if (!TPDirectiveReturn || StartTokLoc != getTok().getLoc()) 1924 return false; 1925 1926 // Next, check the extension directive map to see if any extension has 1927 // registered itself to parse this directive. 1928 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler = 1929 ExtensionDirectiveMap.lookup(IDVal); 1930 if (Handler.first) 1931 return (*Handler.second)(Handler.first, IDVal, IDLoc); 1932 1933 // Finally, if no one else is interested in this directive, it must be 1934 // generic and familiar to this class. 1935 switch (DirKind) { 1936 default: 1937 break; 1938 case DK_SET: 1939 case DK_EQU: 1940 return parseDirectiveSet(IDVal, true); 1941 case DK_EQUIV: 1942 return parseDirectiveSet(IDVal, false); 1943 case DK_ASCII: 1944 return parseDirectiveAscii(IDVal, false); 1945 case DK_ASCIZ: 1946 case DK_STRING: 1947 return parseDirectiveAscii(IDVal, true); 1948 case DK_BYTE: 1949 case DK_DC_B: 1950 return parseDirectiveValue(IDVal, 1); 1951 case DK_DC: 1952 case DK_DC_W: 1953 case DK_SHORT: 1954 case DK_VALUE: 1955 case DK_2BYTE: 1956 return parseDirectiveValue(IDVal, 2); 1957 case DK_LONG: 1958 case DK_INT: 1959 case DK_4BYTE: 1960 case DK_DC_L: 1961 return parseDirectiveValue(IDVal, 4); 1962 case DK_QUAD: 1963 case DK_8BYTE: 1964 return parseDirectiveValue(IDVal, 8); 1965 case DK_DC_A: 1966 return parseDirectiveValue( 1967 IDVal, getContext().getAsmInfo()->getCodePointerSize()); 1968 case DK_OCTA: 1969 return parseDirectiveOctaValue(IDVal); 1970 case DK_SINGLE: 1971 case DK_FLOAT: 1972 case DK_DC_S: 1973 return parseDirectiveRealValue(IDVal, APFloat::IEEEsingle()); 1974 case DK_DOUBLE: 1975 case DK_DC_D: 1976 return parseDirectiveRealValue(IDVal, APFloat::IEEEdouble()); 1977 case DK_ALIGN: { 1978 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes(); 1979 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1); 1980 } 1981 case DK_ALIGN32: { 1982 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes(); 1983 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4); 1984 } 1985 case DK_BALIGN: 1986 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1); 1987 case DK_BALIGNW: 1988 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2); 1989 case DK_BALIGNL: 1990 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4); 1991 case DK_P2ALIGN: 1992 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1); 1993 case DK_P2ALIGNW: 1994 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2); 1995 case DK_P2ALIGNL: 1996 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4); 1997 case DK_ORG: 1998 return parseDirectiveOrg(); 1999 case DK_FILL: 2000 return parseDirectiveFill(); 2001 case DK_ZERO: 2002 return parseDirectiveZero(); 2003 case DK_EXTERN: 2004 eatToEndOfStatement(); // .extern is the default, ignore it. 2005 return false; 2006 case DK_GLOBL: 2007 case DK_GLOBAL: 2008 return parseDirectiveSymbolAttribute(MCSA_Global); 2009 case DK_LAZY_REFERENCE: 2010 return parseDirectiveSymbolAttribute(MCSA_LazyReference); 2011 case DK_NO_DEAD_STRIP: 2012 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip); 2013 case DK_SYMBOL_RESOLVER: 2014 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver); 2015 case DK_PRIVATE_EXTERN: 2016 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern); 2017 case DK_REFERENCE: 2018 return parseDirectiveSymbolAttribute(MCSA_Reference); 2019 case DK_WEAK_DEFINITION: 2020 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition); 2021 case DK_WEAK_REFERENCE: 2022 return parseDirectiveSymbolAttribute(MCSA_WeakReference); 2023 case DK_WEAK_DEF_CAN_BE_HIDDEN: 2024 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate); 2025 case DK_COLD: 2026 return parseDirectiveSymbolAttribute(MCSA_Cold); 2027 case DK_COMM: 2028 case DK_COMMON: 2029 return parseDirectiveComm(/*IsLocal=*/false); 2030 case DK_LCOMM: 2031 return parseDirectiveComm(/*IsLocal=*/true); 2032 case DK_ABORT: 2033 return parseDirectiveAbort(); 2034 case DK_INCLUDE: 2035 return parseDirectiveInclude(); 2036 case DK_INCBIN: 2037 return parseDirectiveIncbin(); 2038 case DK_CODE16: 2039 case DK_CODE16GCC: 2040 return TokError(Twine(IDVal) + 2041 " not currently supported for this target"); 2042 case DK_REPT: 2043 return parseDirectiveRept(IDLoc, IDVal); 2044 case DK_IRP: 2045 return parseDirectiveIrp(IDLoc); 2046 case DK_IRPC: 2047 return parseDirectiveIrpc(IDLoc); 2048 case DK_ENDR: 2049 return parseDirectiveEndr(IDLoc); 2050 case DK_BUNDLE_ALIGN_MODE: 2051 return parseDirectiveBundleAlignMode(); 2052 case DK_BUNDLE_LOCK: 2053 return parseDirectiveBundleLock(); 2054 case DK_BUNDLE_UNLOCK: 2055 return parseDirectiveBundleUnlock(); 2056 case DK_SLEB128: 2057 return parseDirectiveLEB128(true); 2058 case DK_ULEB128: 2059 return parseDirectiveLEB128(false); 2060 case DK_SPACE: 2061 case DK_SKIP: 2062 return parseDirectiveSpace(IDVal); 2063 case DK_FILE: 2064 return parseDirectiveFile(IDLoc); 2065 case DK_LINE: 2066 return parseDirectiveLine(); 2067 case DK_LOC: 2068 return parseDirectiveLoc(); 2069 case DK_STABS: 2070 return parseDirectiveStabs(); 2071 case DK_CV_FILE: 2072 return parseDirectiveCVFile(); 2073 case DK_CV_FUNC_ID: 2074 return parseDirectiveCVFuncId(); 2075 case DK_CV_INLINE_SITE_ID: 2076 return parseDirectiveCVInlineSiteId(); 2077 case DK_CV_LOC: 2078 return parseDirectiveCVLoc(); 2079 case DK_CV_LINETABLE: 2080 return parseDirectiveCVLinetable(); 2081 case DK_CV_INLINE_LINETABLE: 2082 return parseDirectiveCVInlineLinetable(); 2083 case DK_CV_DEF_RANGE: 2084 return parseDirectiveCVDefRange(); 2085 case DK_CV_STRING: 2086 return parseDirectiveCVString(); 2087 case DK_CV_STRINGTABLE: 2088 return parseDirectiveCVStringTable(); 2089 case DK_CV_FILECHECKSUMS: 2090 return parseDirectiveCVFileChecksums(); 2091 case DK_CV_FILECHECKSUM_OFFSET: 2092 return parseDirectiveCVFileChecksumOffset(); 2093 case DK_CV_FPO_DATA: 2094 return parseDirectiveCVFPOData(); 2095 case DK_CFI_SECTIONS: 2096 return parseDirectiveCFISections(); 2097 case DK_CFI_STARTPROC: 2098 return parseDirectiveCFIStartProc(); 2099 case DK_CFI_ENDPROC: 2100 return parseDirectiveCFIEndProc(); 2101 case DK_CFI_DEF_CFA: 2102 return parseDirectiveCFIDefCfa(IDLoc); 2103 case DK_CFI_DEF_CFA_OFFSET: 2104 return parseDirectiveCFIDefCfaOffset(); 2105 case DK_CFI_ADJUST_CFA_OFFSET: 2106 return parseDirectiveCFIAdjustCfaOffset(); 2107 case DK_CFI_DEF_CFA_REGISTER: 2108 return parseDirectiveCFIDefCfaRegister(IDLoc); 2109 case DK_CFI_OFFSET: 2110 return parseDirectiveCFIOffset(IDLoc); 2111 case DK_CFI_REL_OFFSET: 2112 return parseDirectiveCFIRelOffset(IDLoc); 2113 case DK_CFI_PERSONALITY: 2114 return parseDirectiveCFIPersonalityOrLsda(true); 2115 case DK_CFI_LSDA: 2116 return parseDirectiveCFIPersonalityOrLsda(false); 2117 case DK_CFI_REMEMBER_STATE: 2118 return parseDirectiveCFIRememberState(); 2119 case DK_CFI_RESTORE_STATE: 2120 return parseDirectiveCFIRestoreState(); 2121 case DK_CFI_SAME_VALUE: 2122 return parseDirectiveCFISameValue(IDLoc); 2123 case DK_CFI_RESTORE: 2124 return parseDirectiveCFIRestore(IDLoc); 2125 case DK_CFI_ESCAPE: 2126 return parseDirectiveCFIEscape(); 2127 case DK_CFI_RETURN_COLUMN: 2128 return parseDirectiveCFIReturnColumn(IDLoc); 2129 case DK_CFI_SIGNAL_FRAME: 2130 return parseDirectiveCFISignalFrame(); 2131 case DK_CFI_UNDEFINED: 2132 return parseDirectiveCFIUndefined(IDLoc); 2133 case DK_CFI_REGISTER: 2134 return parseDirectiveCFIRegister(IDLoc); 2135 case DK_CFI_WINDOW_SAVE: 2136 return parseDirectiveCFIWindowSave(); 2137 case DK_MACROS_ON: 2138 case DK_MACROS_OFF: 2139 return parseDirectiveMacrosOnOff(IDVal); 2140 case DK_MACRO: 2141 return parseDirectiveMacro(IDLoc); 2142 case DK_ALTMACRO: 2143 case DK_NOALTMACRO: 2144 return parseDirectiveAltmacro(IDVal); 2145 case DK_EXITM: 2146 return parseDirectiveExitMacro(IDVal); 2147 case DK_ENDM: 2148 case DK_ENDMACRO: 2149 return parseDirectiveEndMacro(IDVal); 2150 case DK_PURGEM: 2151 return parseDirectivePurgeMacro(IDLoc); 2152 case DK_END: 2153 return parseDirectiveEnd(IDLoc); 2154 case DK_ERR: 2155 return parseDirectiveError(IDLoc, false); 2156 case DK_ERROR: 2157 return parseDirectiveError(IDLoc, true); 2158 case DK_WARNING: 2159 return parseDirectiveWarning(IDLoc); 2160 case DK_RELOC: 2161 return parseDirectiveReloc(IDLoc); 2162 case DK_DCB: 2163 case DK_DCB_W: 2164 return parseDirectiveDCB(IDVal, 2); 2165 case DK_DCB_B: 2166 return parseDirectiveDCB(IDVal, 1); 2167 case DK_DCB_D: 2168 return parseDirectiveRealDCB(IDVal, APFloat::IEEEdouble()); 2169 case DK_DCB_L: 2170 return parseDirectiveDCB(IDVal, 4); 2171 case DK_DCB_S: 2172 return parseDirectiveRealDCB(IDVal, APFloat::IEEEsingle()); 2173 case DK_DC_X: 2174 case DK_DCB_X: 2175 return TokError(Twine(IDVal) + 2176 " not currently supported for this target"); 2177 case DK_DS: 2178 case DK_DS_W: 2179 return parseDirectiveDS(IDVal, 2); 2180 case DK_DS_B: 2181 return parseDirectiveDS(IDVal, 1); 2182 case DK_DS_D: 2183 return parseDirectiveDS(IDVal, 8); 2184 case DK_DS_L: 2185 case DK_DS_S: 2186 return parseDirectiveDS(IDVal, 4); 2187 case DK_DS_P: 2188 case DK_DS_X: 2189 return parseDirectiveDS(IDVal, 12); 2190 case DK_PRINT: 2191 return parseDirectivePrint(IDLoc); 2192 case DK_ADDRSIG: 2193 return parseDirectiveAddrsig(); 2194 case DK_ADDRSIG_SYM: 2195 return parseDirectiveAddrsigSym(); 2196 } 2197 2198 return Error(IDLoc, "unknown directive"); 2199 } 2200 2201 // __asm _emit or __asm __emit 2202 if (ParsingMSInlineAsm && (IDVal == "_emit" || IDVal == "__emit" || 2203 IDVal == "_EMIT" || IDVal == "__EMIT")) 2204 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size()); 2205 2206 // __asm align 2207 if (ParsingMSInlineAsm && (IDVal == "align" || IDVal == "ALIGN")) 2208 return parseDirectiveMSAlign(IDLoc, Info); 2209 2210 if (ParsingMSInlineAsm && (IDVal == "even" || IDVal == "EVEN")) 2211 Info.AsmRewrites->emplace_back(AOK_EVEN, IDLoc, 4); 2212 if (checkForValidSection()) 2213 return true; 2214 2215 // Canonicalize the opcode to lower case. 2216 std::string OpcodeStr = IDVal.lower(); 2217 ParseInstructionInfo IInfo(Info.AsmRewrites); 2218 bool ParseHadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, ID, 2219 Info.ParsedOperands); 2220 Info.ParseError = ParseHadError; 2221 2222 // Dump the parsed representation, if requested. 2223 if (getShowParsedOperands()) { 2224 SmallString<256> Str; 2225 raw_svector_ostream OS(Str); 2226 OS << "parsed instruction: ["; 2227 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) { 2228 if (i != 0) 2229 OS << ", "; 2230 Info.ParsedOperands[i]->print(OS); 2231 } 2232 OS << "]"; 2233 2234 printMessage(IDLoc, SourceMgr::DK_Note, OS.str()); 2235 } 2236 2237 // Fail even if ParseInstruction erroneously returns false. 2238 if (hasPendingError() || ParseHadError) 2239 return true; 2240 2241 // If we are generating dwarf for the current section then generate a .loc 2242 // directive for the instruction. 2243 if (!ParseHadError && enabledGenDwarfForAssembly() && 2244 getContext().getGenDwarfSectionSyms().count( 2245 getStreamer().getCurrentSectionOnly())) { 2246 unsigned Line; 2247 if (ActiveMacros.empty()) 2248 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer); 2249 else 2250 Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc, 2251 ActiveMacros.front()->ExitBuffer); 2252 2253 // If we previously parsed a cpp hash file line comment then make sure the 2254 // current Dwarf File is for the CppHashFilename if not then emit the 2255 // Dwarf File table for it and adjust the line number for the .loc. 2256 if (!CppHashInfo.Filename.empty()) { 2257 unsigned FileNumber = getStreamer().emitDwarfFileDirective( 2258 0, StringRef(), CppHashInfo.Filename); 2259 getContext().setGenDwarfFileNumber(FileNumber); 2260 2261 unsigned CppHashLocLineNo = 2262 SrcMgr.FindLineNumber(CppHashInfo.Loc, CppHashInfo.Buf); 2263 Line = CppHashInfo.LineNumber - 1 + (Line - CppHashLocLineNo); 2264 } 2265 2266 getStreamer().emitDwarfLocDirective( 2267 getContext().getGenDwarfFileNumber(), Line, 0, 2268 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0, 2269 StringRef()); 2270 } 2271 2272 // If parsing succeeded, match the instruction. 2273 if (!ParseHadError) { 2274 uint64_t ErrorInfo; 2275 if (getTargetParser().MatchAndEmitInstruction( 2276 IDLoc, Info.Opcode, Info.ParsedOperands, Out, ErrorInfo, 2277 getTargetParser().isParsingMSInlineAsm())) 2278 return true; 2279 } 2280 return false; 2281 } 2282 2283 // Parse and erase curly braces marking block start/end 2284 bool 2285 AsmParser::parseCurlyBlockScope(SmallVectorImpl<AsmRewrite> &AsmStrRewrites) { 2286 // Identify curly brace marking block start/end 2287 if (Lexer.isNot(AsmToken::LCurly) && Lexer.isNot(AsmToken::RCurly)) 2288 return false; 2289 2290 SMLoc StartLoc = Lexer.getLoc(); 2291 Lex(); // Eat the brace 2292 if (Lexer.is(AsmToken::EndOfStatement)) 2293 Lex(); // Eat EndOfStatement following the brace 2294 2295 // Erase the block start/end brace from the output asm string 2296 AsmStrRewrites.emplace_back(AOK_Skip, StartLoc, Lexer.getLoc().getPointer() - 2297 StartLoc.getPointer()); 2298 return true; 2299 } 2300 2301 /// parseCppHashLineFilenameComment as this: 2302 /// ::= # number "filename" 2303 bool AsmParser::parseCppHashLineFilenameComment(SMLoc L, bool SaveLocInfo) { 2304 Lex(); // Eat the hash token. 2305 // Lexer only ever emits HashDirective if it fully formed if it's 2306 // done the checking already so this is an internal error. 2307 assert(getTok().is(AsmToken::Integer) && 2308 "Lexing Cpp line comment: Expected Integer"); 2309 int64_t LineNumber = getTok().getIntVal(); 2310 Lex(); 2311 assert(getTok().is(AsmToken::String) && 2312 "Lexing Cpp line comment: Expected String"); 2313 StringRef Filename = getTok().getString(); 2314 Lex(); 2315 2316 if (!SaveLocInfo) 2317 return false; 2318 2319 // Get rid of the enclosing quotes. 2320 Filename = Filename.substr(1, Filename.size() - 2); 2321 2322 // Save the SMLoc, Filename and LineNumber for later use by diagnostics 2323 // and possibly DWARF file info. 2324 CppHashInfo.Loc = L; 2325 CppHashInfo.Filename = Filename; 2326 CppHashInfo.LineNumber = LineNumber; 2327 CppHashInfo.Buf = CurBuffer; 2328 if (FirstCppHashFilename.empty()) 2329 FirstCppHashFilename = Filename; 2330 return false; 2331 } 2332 2333 /// will use the last parsed cpp hash line filename comment 2334 /// for the Filename and LineNo if any in the diagnostic. 2335 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) { 2336 const AsmParser *Parser = static_cast<const AsmParser *>(Context); 2337 raw_ostream &OS = errs(); 2338 2339 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr(); 2340 SMLoc DiagLoc = Diag.getLoc(); 2341 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc); 2342 unsigned CppHashBuf = 2343 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashInfo.Loc); 2344 2345 // Like SourceMgr::printMessage() we need to print the include stack if any 2346 // before printing the message. 2347 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc); 2348 if (!Parser->SavedDiagHandler && DiagCurBuffer && 2349 DiagCurBuffer != DiagSrcMgr.getMainFileID()) { 2350 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer); 2351 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS); 2352 } 2353 2354 // If we have not parsed a cpp hash line filename comment or the source 2355 // manager changed or buffer changed (like in a nested include) then just 2356 // print the normal diagnostic using its Filename and LineNo. 2357 if (!Parser->CppHashInfo.LineNumber || &DiagSrcMgr != &Parser->SrcMgr || 2358 DiagBuf != CppHashBuf) { 2359 if (Parser->SavedDiagHandler) 2360 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext); 2361 else 2362 Diag.print(nullptr, OS); 2363 return; 2364 } 2365 2366 // Use the CppHashFilename and calculate a line number based on the 2367 // CppHashInfo.Loc and CppHashInfo.LineNumber relative to this Diag's SMLoc 2368 // for the diagnostic. 2369 const std::string &Filename = std::string(Parser->CppHashInfo.Filename); 2370 2371 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf); 2372 int CppHashLocLineNo = 2373 Parser->SrcMgr.FindLineNumber(Parser->CppHashInfo.Loc, CppHashBuf); 2374 int LineNo = 2375 Parser->CppHashInfo.LineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo); 2376 2377 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo, 2378 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(), 2379 Diag.getLineContents(), Diag.getRanges()); 2380 2381 if (Parser->SavedDiagHandler) 2382 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext); 2383 else 2384 NewDiag.print(nullptr, OS); 2385 } 2386 2387 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The 2388 // difference being that that function accepts '@' as part of identifiers and 2389 // we can't do that. AsmLexer.cpp should probably be changed to handle 2390 // '@' as a special case when needed. 2391 static bool isIdentifierChar(char c) { 2392 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' || 2393 c == '.'; 2394 } 2395 2396 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body, 2397 ArrayRef<MCAsmMacroParameter> Parameters, 2398 ArrayRef<MCAsmMacroArgument> A, 2399 bool EnableAtPseudoVariable, SMLoc L) { 2400 unsigned NParameters = Parameters.size(); 2401 bool HasVararg = NParameters ? Parameters.back().Vararg : false; 2402 if ((!IsDarwin || NParameters != 0) && NParameters != A.size()) 2403 return Error(L, "Wrong number of arguments"); 2404 2405 // A macro without parameters is handled differently on Darwin: 2406 // gas accepts no arguments and does no substitutions 2407 while (!Body.empty()) { 2408 // Scan for the next substitution. 2409 std::size_t End = Body.size(), Pos = 0; 2410 for (; Pos != End; ++Pos) { 2411 // Check for a substitution or escape. 2412 if (IsDarwin && !NParameters) { 2413 // This macro has no parameters, look for $0, $1, etc. 2414 if (Body[Pos] != '$' || Pos + 1 == End) 2415 continue; 2416 2417 char Next = Body[Pos + 1]; 2418 if (Next == '$' || Next == 'n' || 2419 isdigit(static_cast<unsigned char>(Next))) 2420 break; 2421 } else { 2422 // This macro has parameters, look for \foo, \bar, etc. 2423 if (Body[Pos] == '\\' && Pos + 1 != End) 2424 break; 2425 } 2426 } 2427 2428 // Add the prefix. 2429 OS << Body.slice(0, Pos); 2430 2431 // Check if we reached the end. 2432 if (Pos == End) 2433 break; 2434 2435 if (IsDarwin && !NParameters) { 2436 switch (Body[Pos + 1]) { 2437 // $$ => $ 2438 case '$': 2439 OS << '$'; 2440 break; 2441 2442 // $n => number of arguments 2443 case 'n': 2444 OS << A.size(); 2445 break; 2446 2447 // $[0-9] => argument 2448 default: { 2449 // Missing arguments are ignored. 2450 unsigned Index = Body[Pos + 1] - '0'; 2451 if (Index >= A.size()) 2452 break; 2453 2454 // Otherwise substitute with the token values, with spaces eliminated. 2455 for (const AsmToken &Token : A[Index]) 2456 OS << Token.getString(); 2457 break; 2458 } 2459 } 2460 Pos += 2; 2461 } else { 2462 unsigned I = Pos + 1; 2463 2464 // Check for the \@ pseudo-variable. 2465 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End) 2466 ++I; 2467 else 2468 while (isIdentifierChar(Body[I]) && I + 1 != End) 2469 ++I; 2470 2471 const char *Begin = Body.data() + Pos + 1; 2472 StringRef Argument(Begin, I - (Pos + 1)); 2473 unsigned Index = 0; 2474 2475 if (Argument == "@") { 2476 OS << NumOfMacroInstantiations; 2477 Pos += 2; 2478 } else { 2479 for (; Index < NParameters; ++Index) 2480 if (Parameters[Index].Name == Argument) 2481 break; 2482 2483 if (Index == NParameters) { 2484 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')') 2485 Pos += 3; 2486 else { 2487 OS << '\\' << Argument; 2488 Pos = I; 2489 } 2490 } else { 2491 bool VarargParameter = HasVararg && Index == (NParameters - 1); 2492 for (const AsmToken &Token : A[Index]) 2493 // For altmacro mode, you can write '%expr'. 2494 // The prefix '%' evaluates the expression 'expr' 2495 // and uses the result as a string (e.g. replace %(1+2) with the 2496 // string "3"). 2497 // Here, we identify the integer token which is the result of the 2498 // absolute expression evaluation and replace it with its string 2499 // representation. 2500 if (AltMacroMode && Token.getString().front() == '%' && 2501 Token.is(AsmToken::Integer)) 2502 // Emit an integer value to the buffer. 2503 OS << Token.getIntVal(); 2504 // Only Token that was validated as a string and begins with '<' 2505 // is considered altMacroString!!! 2506 else if (AltMacroMode && Token.getString().front() == '<' && 2507 Token.is(AsmToken::String)) { 2508 OS << angleBracketString(Token.getStringContents()); 2509 } 2510 // We expect no quotes around the string's contents when 2511 // parsing for varargs. 2512 else if (Token.isNot(AsmToken::String) || VarargParameter) 2513 OS << Token.getString(); 2514 else 2515 OS << Token.getStringContents(); 2516 2517 Pos += 1 + Argument.size(); 2518 } 2519 } 2520 } 2521 // Update the scan point. 2522 Body = Body.substr(Pos); 2523 } 2524 2525 return false; 2526 } 2527 2528 static bool isOperator(AsmToken::TokenKind kind) { 2529 switch (kind) { 2530 default: 2531 return false; 2532 case AsmToken::Plus: 2533 case AsmToken::Minus: 2534 case AsmToken::Tilde: 2535 case AsmToken::Slash: 2536 case AsmToken::Star: 2537 case AsmToken::Dot: 2538 case AsmToken::Equal: 2539 case AsmToken::EqualEqual: 2540 case AsmToken::Pipe: 2541 case AsmToken::PipePipe: 2542 case AsmToken::Caret: 2543 case AsmToken::Amp: 2544 case AsmToken::AmpAmp: 2545 case AsmToken::Exclaim: 2546 case AsmToken::ExclaimEqual: 2547 case AsmToken::Less: 2548 case AsmToken::LessEqual: 2549 case AsmToken::LessLess: 2550 case AsmToken::LessGreater: 2551 case AsmToken::Greater: 2552 case AsmToken::GreaterEqual: 2553 case AsmToken::GreaterGreater: 2554 return true; 2555 } 2556 } 2557 2558 namespace { 2559 2560 class AsmLexerSkipSpaceRAII { 2561 public: 2562 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) { 2563 Lexer.setSkipSpace(SkipSpace); 2564 } 2565 2566 ~AsmLexerSkipSpaceRAII() { 2567 Lexer.setSkipSpace(true); 2568 } 2569 2570 private: 2571 AsmLexer &Lexer; 2572 }; 2573 2574 } // end anonymous namespace 2575 2576 bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) { 2577 2578 if (Vararg) { 2579 if (Lexer.isNot(AsmToken::EndOfStatement)) { 2580 StringRef Str = parseStringToEndOfStatement(); 2581 MA.emplace_back(AsmToken::String, Str); 2582 } 2583 return false; 2584 } 2585 2586 unsigned ParenLevel = 0; 2587 2588 // Darwin doesn't use spaces to delmit arguments. 2589 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin); 2590 2591 bool SpaceEaten; 2592 2593 while (true) { 2594 SpaceEaten = false; 2595 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) 2596 return TokError("unexpected token in macro instantiation"); 2597 2598 if (ParenLevel == 0) { 2599 2600 if (Lexer.is(AsmToken::Comma)) 2601 break; 2602 2603 if (Lexer.is(AsmToken::Space)) { 2604 SpaceEaten = true; 2605 Lexer.Lex(); // Eat spaces 2606 } 2607 2608 // Spaces can delimit parameters, but could also be part an expression. 2609 // If the token after a space is an operator, add the token and the next 2610 // one into this argument 2611 if (!IsDarwin) { 2612 if (isOperator(Lexer.getKind())) { 2613 MA.push_back(getTok()); 2614 Lexer.Lex(); 2615 2616 // Whitespace after an operator can be ignored. 2617 if (Lexer.is(AsmToken::Space)) 2618 Lexer.Lex(); 2619 2620 continue; 2621 } 2622 } 2623 if (SpaceEaten) 2624 break; 2625 } 2626 2627 // handleMacroEntry relies on not advancing the lexer here 2628 // to be able to fill in the remaining default parameter values 2629 if (Lexer.is(AsmToken::EndOfStatement)) 2630 break; 2631 2632 // Adjust the current parentheses level. 2633 if (Lexer.is(AsmToken::LParen)) 2634 ++ParenLevel; 2635 else if (Lexer.is(AsmToken::RParen) && ParenLevel) 2636 --ParenLevel; 2637 2638 // Append the token to the current argument list. 2639 MA.push_back(getTok()); 2640 Lexer.Lex(); 2641 } 2642 2643 if (ParenLevel != 0) 2644 return TokError("unbalanced parentheses in macro argument"); 2645 return false; 2646 } 2647 2648 // Parse the macro instantiation arguments. 2649 bool AsmParser::parseMacroArguments(const MCAsmMacro *M, 2650 MCAsmMacroArguments &A) { 2651 const unsigned NParameters = M ? M->Parameters.size() : 0; 2652 bool NamedParametersFound = false; 2653 SmallVector<SMLoc, 4> FALocs; 2654 2655 A.resize(NParameters); 2656 FALocs.resize(NParameters); 2657 2658 // Parse two kinds of macro invocations: 2659 // - macros defined without any parameters accept an arbitrary number of them 2660 // - macros defined with parameters accept at most that many of them 2661 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false; 2662 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters; 2663 ++Parameter) { 2664 SMLoc IDLoc = Lexer.getLoc(); 2665 MCAsmMacroParameter FA; 2666 2667 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) { 2668 if (parseIdentifier(FA.Name)) 2669 return Error(IDLoc, "invalid argument identifier for formal argument"); 2670 2671 if (Lexer.isNot(AsmToken::Equal)) 2672 return TokError("expected '=' after formal parameter identifier"); 2673 2674 Lex(); 2675 2676 NamedParametersFound = true; 2677 } 2678 bool Vararg = HasVararg && Parameter == (NParameters - 1); 2679 2680 if (NamedParametersFound && FA.Name.empty()) 2681 return Error(IDLoc, "cannot mix positional and keyword arguments"); 2682 2683 SMLoc StrLoc = Lexer.getLoc(); 2684 SMLoc EndLoc; 2685 if (AltMacroMode && Lexer.is(AsmToken::Percent)) { 2686 const MCExpr *AbsoluteExp; 2687 int64_t Value; 2688 /// Eat '%' 2689 Lex(); 2690 if (parseExpression(AbsoluteExp, EndLoc)) 2691 return false; 2692 if (!AbsoluteExp->evaluateAsAbsolute(Value, 2693 getStreamer().getAssemblerPtr())) 2694 return Error(StrLoc, "expected absolute expression"); 2695 const char *StrChar = StrLoc.getPointer(); 2696 const char *EndChar = EndLoc.getPointer(); 2697 AsmToken newToken(AsmToken::Integer, 2698 StringRef(StrChar, EndChar - StrChar), Value); 2699 FA.Value.push_back(newToken); 2700 } else if (AltMacroMode && Lexer.is(AsmToken::Less) && 2701 isAngleBracketString(StrLoc, EndLoc)) { 2702 const char *StrChar = StrLoc.getPointer(); 2703 const char *EndChar = EndLoc.getPointer(); 2704 jumpToLoc(EndLoc, CurBuffer); 2705 /// Eat from '<' to '>' 2706 Lex(); 2707 AsmToken newToken(AsmToken::String, 2708 StringRef(StrChar, EndChar - StrChar)); 2709 FA.Value.push_back(newToken); 2710 } else if(parseMacroArgument(FA.Value, Vararg)) 2711 return true; 2712 2713 unsigned PI = Parameter; 2714 if (!FA.Name.empty()) { 2715 unsigned FAI = 0; 2716 for (FAI = 0; FAI < NParameters; ++FAI) 2717 if (M->Parameters[FAI].Name == FA.Name) 2718 break; 2719 2720 if (FAI >= NParameters) { 2721 assert(M && "expected macro to be defined"); 2722 return Error(IDLoc, "parameter named '" + FA.Name + 2723 "' does not exist for macro '" + M->Name + "'"); 2724 } 2725 PI = FAI; 2726 } 2727 2728 if (!FA.Value.empty()) { 2729 if (A.size() <= PI) 2730 A.resize(PI + 1); 2731 A[PI] = FA.Value; 2732 2733 if (FALocs.size() <= PI) 2734 FALocs.resize(PI + 1); 2735 2736 FALocs[PI] = Lexer.getLoc(); 2737 } 2738 2739 // At the end of the statement, fill in remaining arguments that have 2740 // default values. If there aren't any, then the next argument is 2741 // required but missing 2742 if (Lexer.is(AsmToken::EndOfStatement)) { 2743 bool Failure = false; 2744 for (unsigned FAI = 0; FAI < NParameters; ++FAI) { 2745 if (A[FAI].empty()) { 2746 if (M->Parameters[FAI].Required) { 2747 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(), 2748 "missing value for required parameter " 2749 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'"); 2750 Failure = true; 2751 } 2752 2753 if (!M->Parameters[FAI].Value.empty()) 2754 A[FAI] = M->Parameters[FAI].Value; 2755 } 2756 } 2757 return Failure; 2758 } 2759 2760 if (Lexer.is(AsmToken::Comma)) 2761 Lex(); 2762 } 2763 2764 return TokError("too many positional arguments"); 2765 } 2766 2767 bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) { 2768 // Arbitrarily limit macro nesting depth (default matches 'as'). We can 2769 // eliminate this, although we should protect against infinite loops. 2770 unsigned MaxNestingDepth = AsmMacroMaxNestingDepth; 2771 if (ActiveMacros.size() == MaxNestingDepth) { 2772 std::ostringstream MaxNestingDepthError; 2773 MaxNestingDepthError << "macros cannot be nested more than " 2774 << MaxNestingDepth << " levels deep." 2775 << " Use -asm-macro-max-nesting-depth to increase " 2776 "this limit."; 2777 return TokError(MaxNestingDepthError.str()); 2778 } 2779 2780 MCAsmMacroArguments A; 2781 if (parseMacroArguments(M, A)) 2782 return true; 2783 2784 // Macro instantiation is lexical, unfortunately. We construct a new buffer 2785 // to hold the macro body with substitutions. 2786 SmallString<256> Buf; 2787 StringRef Body = M->Body; 2788 raw_svector_ostream OS(Buf); 2789 2790 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc())) 2791 return true; 2792 2793 // We include the .endmacro in the buffer as our cue to exit the macro 2794 // instantiation. 2795 OS << ".endmacro\n"; 2796 2797 std::unique_ptr<MemoryBuffer> Instantiation = 2798 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>"); 2799 2800 // Create the macro instantiation object and add to the current macro 2801 // instantiation stack. 2802 MacroInstantiation *MI = new MacroInstantiation{ 2803 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size()}; 2804 ActiveMacros.push_back(MI); 2805 2806 ++NumOfMacroInstantiations; 2807 2808 // Jump to the macro instantiation and prime the lexer. 2809 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc()); 2810 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer()); 2811 Lex(); 2812 2813 return false; 2814 } 2815 2816 void AsmParser::handleMacroExit() { 2817 // Jump to the EndOfStatement we should return to, and consume it. 2818 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer); 2819 Lex(); 2820 2821 // Pop the instantiation entry. 2822 delete ActiveMacros.back(); 2823 ActiveMacros.pop_back(); 2824 } 2825 2826 bool AsmParser::parseAssignment(StringRef Name, bool allow_redef, 2827 bool NoDeadStrip) { 2828 MCSymbol *Sym; 2829 const MCExpr *Value; 2830 if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym, 2831 Value)) 2832 return true; 2833 2834 if (!Sym) { 2835 // In the case where we parse an expression starting with a '.', we will 2836 // not generate an error, nor will we create a symbol. In this case we 2837 // should just return out. 2838 return false; 2839 } 2840 2841 // Do the assignment. 2842 Out.emitAssignment(Sym, Value); 2843 if (NoDeadStrip) 2844 Out.emitSymbolAttribute(Sym, MCSA_NoDeadStrip); 2845 2846 return false; 2847 } 2848 2849 /// parseIdentifier: 2850 /// ::= identifier 2851 /// ::= string 2852 bool AsmParser::parseIdentifier(StringRef &Res) { 2853 // The assembler has relaxed rules for accepting identifiers, in particular we 2854 // allow things like '.globl $foo' and '.def @feat.00', which would normally be 2855 // separate tokens. At this level, we have already lexed so we cannot (currently) 2856 // handle this as a context dependent token, instead we detect adjacent tokens 2857 // and return the combined identifier. 2858 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) { 2859 SMLoc PrefixLoc = getLexer().getLoc(); 2860 2861 // Consume the prefix character, and check for a following identifier. 2862 2863 AsmToken Buf[1]; 2864 Lexer.peekTokens(Buf, false); 2865 2866 if (Buf[0].isNot(AsmToken::Identifier) && Buf[0].isNot(AsmToken::Integer)) 2867 return true; 2868 2869 // We have a '$' or '@' followed by an identifier or integer token, make 2870 // sure they are adjacent. 2871 if (PrefixLoc.getPointer() + 1 != Buf[0].getLoc().getPointer()) 2872 return true; 2873 2874 // eat $ or @ 2875 Lexer.Lex(); // Lexer's Lex guarantees consecutive token. 2876 // Construct the joined identifier and consume the token. 2877 Res = StringRef(PrefixLoc.getPointer(), getTok().getString().size() + 1); 2878 Lex(); // Parser Lex to maintain invariants. 2879 return false; 2880 } 2881 2882 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String)) 2883 return true; 2884 2885 Res = getTok().getIdentifier(); 2886 2887 Lex(); // Consume the identifier token. 2888 2889 return false; 2890 } 2891 2892 /// parseDirectiveSet: 2893 /// ::= .equ identifier ',' expression 2894 /// ::= .equiv identifier ',' expression 2895 /// ::= .set identifier ',' expression 2896 bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) { 2897 StringRef Name; 2898 if (check(parseIdentifier(Name), "expected identifier") || 2899 parseToken(AsmToken::Comma) || parseAssignment(Name, allow_redef, true)) 2900 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive"); 2901 return false; 2902 } 2903 2904 bool AsmParser::parseEscapedString(std::string &Data) { 2905 if (check(getTok().isNot(AsmToken::String), "expected string")) 2906 return true; 2907 2908 Data = ""; 2909 StringRef Str = getTok().getStringContents(); 2910 for (unsigned i = 0, e = Str.size(); i != e; ++i) { 2911 if (Str[i] != '\\') { 2912 Data += Str[i]; 2913 continue; 2914 } 2915 2916 // Recognize escaped characters. Note that this escape semantics currently 2917 // loosely follows Darwin 'as'. 2918 ++i; 2919 if (i == e) 2920 return TokError("unexpected backslash at end of string"); 2921 2922 // Recognize hex sequences similarly to GNU 'as'. 2923 if (Str[i] == 'x' || Str[i] == 'X') { 2924 size_t length = Str.size(); 2925 if (i + 1 >= length || !isHexDigit(Str[i + 1])) 2926 return TokError("invalid hexadecimal escape sequence"); 2927 2928 // Consume hex characters. GNU 'as' reads all hexadecimal characters and 2929 // then truncates to the lower 16 bits. Seems reasonable. 2930 unsigned Value = 0; 2931 while (i + 1 < length && isHexDigit(Str[i + 1])) 2932 Value = Value * 16 + hexDigitValue(Str[++i]); 2933 2934 Data += (unsigned char)(Value & 0xFF); 2935 continue; 2936 } 2937 2938 // Recognize octal sequences. 2939 if ((unsigned)(Str[i] - '0') <= 7) { 2940 // Consume up to three octal characters. 2941 unsigned Value = Str[i] - '0'; 2942 2943 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) { 2944 ++i; 2945 Value = Value * 8 + (Str[i] - '0'); 2946 2947 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) { 2948 ++i; 2949 Value = Value * 8 + (Str[i] - '0'); 2950 } 2951 } 2952 2953 if (Value > 255) 2954 return TokError("invalid octal escape sequence (out of range)"); 2955 2956 Data += (unsigned char)Value; 2957 continue; 2958 } 2959 2960 // Otherwise recognize individual escapes. 2961 switch (Str[i]) { 2962 default: 2963 // Just reject invalid escape sequences for now. 2964 return TokError("invalid escape sequence (unrecognized character)"); 2965 2966 case 'b': Data += '\b'; break; 2967 case 'f': Data += '\f'; break; 2968 case 'n': Data += '\n'; break; 2969 case 'r': Data += '\r'; break; 2970 case 't': Data += '\t'; break; 2971 case '"': Data += '"'; break; 2972 case '\\': Data += '\\'; break; 2973 } 2974 } 2975 2976 Lex(); 2977 return false; 2978 } 2979 2980 bool AsmParser::parseAngleBracketString(std::string &Data) { 2981 SMLoc EndLoc, StartLoc = getTok().getLoc(); 2982 if (isAngleBracketString(StartLoc, EndLoc)) { 2983 const char *StartChar = StartLoc.getPointer() + 1; 2984 const char *EndChar = EndLoc.getPointer() - 1; 2985 jumpToLoc(EndLoc, CurBuffer); 2986 /// Eat from '<' to '>' 2987 Lex(); 2988 2989 Data = angleBracketString(StringRef(StartChar, EndChar - StartChar)); 2990 return false; 2991 } 2992 return true; 2993 } 2994 2995 /// parseDirectiveAscii: 2996 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ] 2997 bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) { 2998 auto parseOp = [&]() -> bool { 2999 std::string Data; 3000 if (checkForValidSection() || parseEscapedString(Data)) 3001 return true; 3002 getStreamer().emitBytes(Data); 3003 if (ZeroTerminated) 3004 getStreamer().emitBytes(StringRef("\0", 1)); 3005 return false; 3006 }; 3007 3008 if (parseMany(parseOp)) 3009 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive"); 3010 return false; 3011 } 3012 3013 /// parseDirectiveReloc 3014 /// ::= .reloc expression , identifier [ , expression ] 3015 bool AsmParser::parseDirectiveReloc(SMLoc DirectiveLoc) { 3016 const MCExpr *Offset; 3017 const MCExpr *Expr = nullptr; 3018 SMLoc OffsetLoc = Lexer.getTok().getLoc(); 3019 3020 if (parseExpression(Offset)) 3021 return true; 3022 if (parseToken(AsmToken::Comma, "expected comma") || 3023 check(getTok().isNot(AsmToken::Identifier), "expected relocation name")) 3024 return true; 3025 3026 SMLoc NameLoc = Lexer.getTok().getLoc(); 3027 StringRef Name = Lexer.getTok().getIdentifier(); 3028 Lex(); 3029 3030 if (Lexer.is(AsmToken::Comma)) { 3031 Lex(); 3032 SMLoc ExprLoc = Lexer.getLoc(); 3033 if (parseExpression(Expr)) 3034 return true; 3035 3036 MCValue Value; 3037 if (!Expr->evaluateAsRelocatable(Value, nullptr, nullptr)) 3038 return Error(ExprLoc, "expression must be relocatable"); 3039 } 3040 3041 if (parseToken(AsmToken::EndOfStatement, 3042 "unexpected token in .reloc directive")) 3043 return true; 3044 3045 const MCTargetAsmParser &MCT = getTargetParser(); 3046 const MCSubtargetInfo &STI = MCT.getSTI(); 3047 if (Optional<std::pair<bool, std::string>> Err = 3048 getStreamer().emitRelocDirective(*Offset, Name, Expr, DirectiveLoc, 3049 STI)) 3050 return Error(Err->first ? NameLoc : OffsetLoc, Err->second); 3051 3052 return false; 3053 } 3054 3055 /// parseDirectiveValue 3056 /// ::= (.byte | .short | ... ) [ expression (, expression)* ] 3057 bool AsmParser::parseDirectiveValue(StringRef IDVal, unsigned Size) { 3058 auto parseOp = [&]() -> bool { 3059 const MCExpr *Value; 3060 SMLoc ExprLoc = getLexer().getLoc(); 3061 if (checkForValidSection() || parseExpression(Value)) 3062 return true; 3063 // Special case constant expressions to match code generator. 3064 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) { 3065 assert(Size <= 8 && "Invalid size"); 3066 uint64_t IntValue = MCE->getValue(); 3067 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue)) 3068 return Error(ExprLoc, "out of range literal value"); 3069 getStreamer().emitIntValue(IntValue, Size); 3070 } else 3071 getStreamer().emitValue(Value, Size, ExprLoc); 3072 return false; 3073 }; 3074 3075 if (parseMany(parseOp)) 3076 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive"); 3077 return false; 3078 } 3079 3080 static bool parseHexOcta(AsmParser &Asm, uint64_t &hi, uint64_t &lo) { 3081 if (Asm.getTok().isNot(AsmToken::Integer) && 3082 Asm.getTok().isNot(AsmToken::BigNum)) 3083 return Asm.TokError("unknown token in expression"); 3084 SMLoc ExprLoc = Asm.getTok().getLoc(); 3085 APInt IntValue = Asm.getTok().getAPIntVal(); 3086 Asm.Lex(); 3087 if (!IntValue.isIntN(128)) 3088 return Asm.Error(ExprLoc, "out of range literal value"); 3089 if (!IntValue.isIntN(64)) { 3090 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue(); 3091 lo = IntValue.getLoBits(64).getZExtValue(); 3092 } else { 3093 hi = 0; 3094 lo = IntValue.getZExtValue(); 3095 } 3096 return false; 3097 } 3098 3099 /// ParseDirectiveOctaValue 3100 /// ::= .octa [ hexconstant (, hexconstant)* ] 3101 3102 bool AsmParser::parseDirectiveOctaValue(StringRef IDVal) { 3103 auto parseOp = [&]() -> bool { 3104 if (checkForValidSection()) 3105 return true; 3106 uint64_t hi, lo; 3107 if (parseHexOcta(*this, hi, lo)) 3108 return true; 3109 if (MAI.isLittleEndian()) { 3110 getStreamer().emitInt64(lo); 3111 getStreamer().emitInt64(hi); 3112 } else { 3113 getStreamer().emitInt64(hi); 3114 getStreamer().emitInt64(lo); 3115 } 3116 return false; 3117 }; 3118 3119 if (parseMany(parseOp)) 3120 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive"); 3121 return false; 3122 } 3123 3124 bool AsmParser::parseRealValue(const fltSemantics &Semantics, APInt &Res) { 3125 // We don't truly support arithmetic on floating point expressions, so we 3126 // have to manually parse unary prefixes. 3127 bool IsNeg = false; 3128 if (getLexer().is(AsmToken::Minus)) { 3129 Lexer.Lex(); 3130 IsNeg = true; 3131 } else if (getLexer().is(AsmToken::Plus)) 3132 Lexer.Lex(); 3133 3134 if (Lexer.is(AsmToken::Error)) 3135 return TokError(Lexer.getErr()); 3136 if (Lexer.isNot(AsmToken::Integer) && Lexer.isNot(AsmToken::Real) && 3137 Lexer.isNot(AsmToken::Identifier)) 3138 return TokError("unexpected token in directive"); 3139 3140 // Convert to an APFloat. 3141 APFloat Value(Semantics); 3142 StringRef IDVal = getTok().getString(); 3143 if (getLexer().is(AsmToken::Identifier)) { 3144 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf")) 3145 Value = APFloat::getInf(Semantics); 3146 else if (!IDVal.compare_lower("nan")) 3147 Value = APFloat::getNaN(Semantics, false, ~0); 3148 else 3149 return TokError("invalid floating point literal"); 3150 } else if (errorToBool( 3151 Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) 3152 .takeError())) 3153 return TokError("invalid floating point literal"); 3154 if (IsNeg) 3155 Value.changeSign(); 3156 3157 // Consume the numeric token. 3158 Lex(); 3159 3160 Res = Value.bitcastToAPInt(); 3161 3162 return false; 3163 } 3164 3165 /// parseDirectiveRealValue 3166 /// ::= (.single | .double) [ expression (, expression)* ] 3167 bool AsmParser::parseDirectiveRealValue(StringRef IDVal, 3168 const fltSemantics &Semantics) { 3169 auto parseOp = [&]() -> bool { 3170 APInt AsInt; 3171 if (checkForValidSection() || parseRealValue(Semantics, AsInt)) 3172 return true; 3173 getStreamer().emitIntValue(AsInt.getLimitedValue(), 3174 AsInt.getBitWidth() / 8); 3175 return false; 3176 }; 3177 3178 if (parseMany(parseOp)) 3179 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive"); 3180 return false; 3181 } 3182 3183 /// parseDirectiveZero 3184 /// ::= .zero expression 3185 bool AsmParser::parseDirectiveZero() { 3186 SMLoc NumBytesLoc = Lexer.getLoc(); 3187 const MCExpr *NumBytes; 3188 if (checkForValidSection() || parseExpression(NumBytes)) 3189 return true; 3190 3191 int64_t Val = 0; 3192 if (getLexer().is(AsmToken::Comma)) { 3193 Lex(); 3194 if (parseAbsoluteExpression(Val)) 3195 return true; 3196 } 3197 3198 if (parseToken(AsmToken::EndOfStatement, 3199 "unexpected token in '.zero' directive")) 3200 return true; 3201 getStreamer().emitFill(*NumBytes, Val, NumBytesLoc); 3202 3203 return false; 3204 } 3205 3206 /// parseDirectiveFill 3207 /// ::= .fill expression [ , expression [ , expression ] ] 3208 bool AsmParser::parseDirectiveFill() { 3209 SMLoc NumValuesLoc = Lexer.getLoc(); 3210 const MCExpr *NumValues; 3211 if (checkForValidSection() || parseExpression(NumValues)) 3212 return true; 3213 3214 int64_t FillSize = 1; 3215 int64_t FillExpr = 0; 3216 3217 SMLoc SizeLoc, ExprLoc; 3218 3219 if (parseOptionalToken(AsmToken::Comma)) { 3220 SizeLoc = getTok().getLoc(); 3221 if (parseAbsoluteExpression(FillSize)) 3222 return true; 3223 if (parseOptionalToken(AsmToken::Comma)) { 3224 ExprLoc = getTok().getLoc(); 3225 if (parseAbsoluteExpression(FillExpr)) 3226 return true; 3227 } 3228 } 3229 if (parseToken(AsmToken::EndOfStatement, 3230 "unexpected token in '.fill' directive")) 3231 return true; 3232 3233 if (FillSize < 0) { 3234 Warning(SizeLoc, "'.fill' directive with negative size has no effect"); 3235 return false; 3236 } 3237 if (FillSize > 8) { 3238 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8"); 3239 FillSize = 8; 3240 } 3241 3242 if (!isUInt<32>(FillExpr) && FillSize > 4) 3243 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits"); 3244 3245 getStreamer().emitFill(*NumValues, FillSize, FillExpr, NumValuesLoc); 3246 3247 return false; 3248 } 3249 3250 /// parseDirectiveOrg 3251 /// ::= .org expression [ , expression ] 3252 bool AsmParser::parseDirectiveOrg() { 3253 const MCExpr *Offset; 3254 SMLoc OffsetLoc = Lexer.getLoc(); 3255 if (checkForValidSection() || parseExpression(Offset)) 3256 return true; 3257 3258 // Parse optional fill expression. 3259 int64_t FillExpr = 0; 3260 if (parseOptionalToken(AsmToken::Comma)) 3261 if (parseAbsoluteExpression(FillExpr)) 3262 return addErrorSuffix(" in '.org' directive"); 3263 if (parseToken(AsmToken::EndOfStatement)) 3264 return addErrorSuffix(" in '.org' directive"); 3265 3266 getStreamer().emitValueToOffset(Offset, FillExpr, OffsetLoc); 3267 return false; 3268 } 3269 3270 /// parseDirectiveAlign 3271 /// ::= {.align, ...} expression [ , expression [ , expression ]] 3272 bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) { 3273 SMLoc AlignmentLoc = getLexer().getLoc(); 3274 int64_t Alignment; 3275 SMLoc MaxBytesLoc; 3276 bool HasFillExpr = false; 3277 int64_t FillExpr = 0; 3278 int64_t MaxBytesToFill = 0; 3279 3280 auto parseAlign = [&]() -> bool { 3281 if (parseAbsoluteExpression(Alignment)) 3282 return true; 3283 if (parseOptionalToken(AsmToken::Comma)) { 3284 // The fill expression can be omitted while specifying a maximum number of 3285 // alignment bytes, e.g: 3286 // .align 3,,4 3287 if (getTok().isNot(AsmToken::Comma)) { 3288 HasFillExpr = true; 3289 if (parseAbsoluteExpression(FillExpr)) 3290 return true; 3291 } 3292 if (parseOptionalToken(AsmToken::Comma)) 3293 if (parseTokenLoc(MaxBytesLoc) || 3294 parseAbsoluteExpression(MaxBytesToFill)) 3295 return true; 3296 } 3297 return parseToken(AsmToken::EndOfStatement); 3298 }; 3299 3300 if (checkForValidSection()) 3301 return addErrorSuffix(" in directive"); 3302 // Ignore empty '.p2align' directives for GNU-as compatibility 3303 if (IsPow2 && (ValueSize == 1) && getTok().is(AsmToken::EndOfStatement)) { 3304 Warning(AlignmentLoc, "p2align directive with no operand(s) is ignored"); 3305 return parseToken(AsmToken::EndOfStatement); 3306 } 3307 if (parseAlign()) 3308 return addErrorSuffix(" in directive"); 3309 3310 // Always emit an alignment here even if we thrown an error. 3311 bool ReturnVal = false; 3312 3313 // Compute alignment in bytes. 3314 if (IsPow2) { 3315 // FIXME: Diagnose overflow. 3316 if (Alignment >= 32) { 3317 ReturnVal |= Error(AlignmentLoc, "invalid alignment value"); 3318 Alignment = 31; 3319 } 3320 3321 Alignment = 1ULL << Alignment; 3322 } else { 3323 // Reject alignments that aren't either a power of two or zero, 3324 // for gas compatibility. Alignment of zero is silently rounded 3325 // up to one. 3326 if (Alignment == 0) 3327 Alignment = 1; 3328 if (!isPowerOf2_64(Alignment)) 3329 ReturnVal |= Error(AlignmentLoc, "alignment must be a power of 2"); 3330 } 3331 3332 // Diagnose non-sensical max bytes to align. 3333 if (MaxBytesLoc.isValid()) { 3334 if (MaxBytesToFill < 1) { 3335 ReturnVal |= Error(MaxBytesLoc, 3336 "alignment directive can never be satisfied in this " 3337 "many bytes, ignoring maximum bytes expression"); 3338 MaxBytesToFill = 0; 3339 } 3340 3341 if (MaxBytesToFill >= Alignment) { 3342 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and " 3343 "has no effect"); 3344 MaxBytesToFill = 0; 3345 } 3346 } 3347 3348 // Check whether we should use optimal code alignment for this .align 3349 // directive. 3350 const MCSection *Section = getStreamer().getCurrentSectionOnly(); 3351 assert(Section && "must have section to emit alignment"); 3352 bool UseCodeAlign = Section->UseCodeAlign(); 3353 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) && 3354 ValueSize == 1 && UseCodeAlign) { 3355 getStreamer().emitCodeAlignment(Alignment, MaxBytesToFill); 3356 } else { 3357 // FIXME: Target specific behavior about how the "extra" bytes are filled. 3358 getStreamer().emitValueToAlignment(Alignment, FillExpr, ValueSize, 3359 MaxBytesToFill); 3360 } 3361 3362 return ReturnVal; 3363 } 3364 3365 /// parseDirectiveFile 3366 /// ::= .file filename 3367 /// ::= .file number [directory] filename [md5 checksum] [source source-text] 3368 bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) { 3369 // FIXME: I'm not sure what this is. 3370 int64_t FileNumber = -1; 3371 if (getLexer().is(AsmToken::Integer)) { 3372 FileNumber = getTok().getIntVal(); 3373 Lex(); 3374 3375 if (FileNumber < 0) 3376 return TokError("negative file number"); 3377 } 3378 3379 std::string Path; 3380 3381 // Usually the directory and filename together, otherwise just the directory. 3382 // Allow the strings to have escaped octal character sequence. 3383 if (check(getTok().isNot(AsmToken::String), 3384 "unexpected token in '.file' directive") || 3385 parseEscapedString(Path)) 3386 return true; 3387 3388 StringRef Directory; 3389 StringRef Filename; 3390 std::string FilenameData; 3391 if (getLexer().is(AsmToken::String)) { 3392 if (check(FileNumber == -1, 3393 "explicit path specified, but no file number") || 3394 parseEscapedString(FilenameData)) 3395 return true; 3396 Filename = FilenameData; 3397 Directory = Path; 3398 } else { 3399 Filename = Path; 3400 } 3401 3402 uint64_t MD5Hi, MD5Lo; 3403 bool HasMD5 = false; 3404 3405 Optional<StringRef> Source; 3406 bool HasSource = false; 3407 std::string SourceString; 3408 3409 while (!parseOptionalToken(AsmToken::EndOfStatement)) { 3410 StringRef Keyword; 3411 if (check(getTok().isNot(AsmToken::Identifier), 3412 "unexpected token in '.file' directive") || 3413 parseIdentifier(Keyword)) 3414 return true; 3415 if (Keyword == "md5") { 3416 HasMD5 = true; 3417 if (check(FileNumber == -1, 3418 "MD5 checksum specified, but no file number") || 3419 parseHexOcta(*this, MD5Hi, MD5Lo)) 3420 return true; 3421 } else if (Keyword == "source") { 3422 HasSource = true; 3423 if (check(FileNumber == -1, 3424 "source specified, but no file number") || 3425 check(getTok().isNot(AsmToken::String), 3426 "unexpected token in '.file' directive") || 3427 parseEscapedString(SourceString)) 3428 return true; 3429 } else { 3430 return TokError("unexpected token in '.file' directive"); 3431 } 3432 } 3433 3434 if (FileNumber == -1) { 3435 // Ignore the directive if there is no number and the target doesn't support 3436 // numberless .file directives. This allows some portability of assembler 3437 // between different object file formats. 3438 if (getContext().getAsmInfo()->hasSingleParameterDotFile()) 3439 getStreamer().emitFileDirective(Filename); 3440 } else { 3441 // In case there is a -g option as well as debug info from directive .file, 3442 // we turn off the -g option, directly use the existing debug info instead. 3443 // Throw away any implicit file table for the assembler source. 3444 if (Ctx.getGenDwarfForAssembly()) { 3445 Ctx.getMCDwarfLineTable(0).resetFileTable(); 3446 Ctx.setGenDwarfForAssembly(false); 3447 } 3448 3449 Optional<MD5::MD5Result> CKMem; 3450 if (HasMD5) { 3451 MD5::MD5Result Sum; 3452 for (unsigned i = 0; i != 8; ++i) { 3453 Sum.Bytes[i] = uint8_t(MD5Hi >> ((7 - i) * 8)); 3454 Sum.Bytes[i + 8] = uint8_t(MD5Lo >> ((7 - i) * 8)); 3455 } 3456 CKMem = Sum; 3457 } 3458 if (HasSource) { 3459 char *SourceBuf = static_cast<char *>(Ctx.allocate(SourceString.size())); 3460 memcpy(SourceBuf, SourceString.data(), SourceString.size()); 3461 Source = StringRef(SourceBuf, SourceString.size()); 3462 } 3463 if (FileNumber == 0) { 3464 if (Ctx.getDwarfVersion() < 5) 3465 return Warning(DirectiveLoc, "file 0 not supported prior to DWARF-5"); 3466 getStreamer().emitDwarfFile0Directive(Directory, Filename, CKMem, Source); 3467 } else { 3468 Expected<unsigned> FileNumOrErr = getStreamer().tryEmitDwarfFileDirective( 3469 FileNumber, Directory, Filename, CKMem, Source); 3470 if (!FileNumOrErr) 3471 return Error(DirectiveLoc, toString(FileNumOrErr.takeError())); 3472 } 3473 // Alert the user if there are some .file directives with MD5 and some not. 3474 // But only do that once. 3475 if (!ReportedInconsistentMD5 && !Ctx.isDwarfMD5UsageConsistent(0)) { 3476 ReportedInconsistentMD5 = true; 3477 return Warning(DirectiveLoc, "inconsistent use of MD5 checksums"); 3478 } 3479 } 3480 3481 return false; 3482 } 3483 3484 /// parseDirectiveLine 3485 /// ::= .line [number] 3486 bool AsmParser::parseDirectiveLine() { 3487 int64_t LineNumber; 3488 if (getLexer().is(AsmToken::Integer)) { 3489 if (parseIntToken(LineNumber, "unexpected token in '.line' directive")) 3490 return true; 3491 (void)LineNumber; 3492 // FIXME: Do something with the .line. 3493 } 3494 if (parseToken(AsmToken::EndOfStatement, 3495 "unexpected token in '.line' directive")) 3496 return true; 3497 3498 return false; 3499 } 3500 3501 /// parseDirectiveLoc 3502 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end] 3503 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE] 3504 /// The first number is a file number, must have been previously assigned with 3505 /// a .file directive, the second number is the line number and optionally the 3506 /// third number is a column position (zero if not specified). The remaining 3507 /// optional items are .loc sub-directives. 3508 bool AsmParser::parseDirectiveLoc() { 3509 int64_t FileNumber = 0, LineNumber = 0; 3510 SMLoc Loc = getTok().getLoc(); 3511 if (parseIntToken(FileNumber, "unexpected token in '.loc' directive") || 3512 check(FileNumber < 1 && Ctx.getDwarfVersion() < 5, Loc, 3513 "file number less than one in '.loc' directive") || 3514 check(!getContext().isValidDwarfFileNumber(FileNumber), Loc, 3515 "unassigned file number in '.loc' directive")) 3516 return true; 3517 3518 // optional 3519 if (getLexer().is(AsmToken::Integer)) { 3520 LineNumber = getTok().getIntVal(); 3521 if (LineNumber < 0) 3522 return TokError("line number less than zero in '.loc' directive"); 3523 Lex(); 3524 } 3525 3526 int64_t ColumnPos = 0; 3527 if (getLexer().is(AsmToken::Integer)) { 3528 ColumnPos = getTok().getIntVal(); 3529 if (ColumnPos < 0) 3530 return TokError("column position less than zero in '.loc' directive"); 3531 Lex(); 3532 } 3533 3534 auto PrevFlags = getContext().getCurrentDwarfLoc().getFlags(); 3535 unsigned Flags = PrevFlags & DWARF2_FLAG_IS_STMT; 3536 unsigned Isa = 0; 3537 int64_t Discriminator = 0; 3538 3539 auto parseLocOp = [&]() -> bool { 3540 StringRef Name; 3541 SMLoc Loc = getTok().getLoc(); 3542 if (parseIdentifier(Name)) 3543 return TokError("unexpected token in '.loc' directive"); 3544 3545 if (Name == "basic_block") 3546 Flags |= DWARF2_FLAG_BASIC_BLOCK; 3547 else if (Name == "prologue_end") 3548 Flags |= DWARF2_FLAG_PROLOGUE_END; 3549 else if (Name == "epilogue_begin") 3550 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN; 3551 else if (Name == "is_stmt") { 3552 Loc = getTok().getLoc(); 3553 const MCExpr *Value; 3554 if (parseExpression(Value)) 3555 return true; 3556 // The expression must be the constant 0 or 1. 3557 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) { 3558 int Value = MCE->getValue(); 3559 if (Value == 0) 3560 Flags &= ~DWARF2_FLAG_IS_STMT; 3561 else if (Value == 1) 3562 Flags |= DWARF2_FLAG_IS_STMT; 3563 else 3564 return Error(Loc, "is_stmt value not 0 or 1"); 3565 } else { 3566 return Error(Loc, "is_stmt value not the constant value of 0 or 1"); 3567 } 3568 } else if (Name == "isa") { 3569 Loc = getTok().getLoc(); 3570 const MCExpr *Value; 3571 if (parseExpression(Value)) 3572 return true; 3573 // The expression must be a constant greater or equal to 0. 3574 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) { 3575 int Value = MCE->getValue(); 3576 if (Value < 0) 3577 return Error(Loc, "isa number less than zero"); 3578 Isa = Value; 3579 } else { 3580 return Error(Loc, "isa number not a constant value"); 3581 } 3582 } else if (Name == "discriminator") { 3583 if (parseAbsoluteExpression(Discriminator)) 3584 return true; 3585 } else { 3586 return Error(Loc, "unknown sub-directive in '.loc' directive"); 3587 } 3588 return false; 3589 }; 3590 3591 if (parseMany(parseLocOp, false /*hasComma*/)) 3592 return true; 3593 3594 getStreamer().emitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags, 3595 Isa, Discriminator, StringRef()); 3596 3597 return false; 3598 } 3599 3600 /// parseDirectiveStabs 3601 /// ::= .stabs string, number, number, number 3602 bool AsmParser::parseDirectiveStabs() { 3603 return TokError("unsupported directive '.stabs'"); 3604 } 3605 3606 /// parseDirectiveCVFile 3607 /// ::= .cv_file number filename [checksum] [checksumkind] 3608 bool AsmParser::parseDirectiveCVFile() { 3609 SMLoc FileNumberLoc = getTok().getLoc(); 3610 int64_t FileNumber; 3611 std::string Filename; 3612 std::string Checksum; 3613 int64_t ChecksumKind = 0; 3614 3615 if (parseIntToken(FileNumber, 3616 "expected file number in '.cv_file' directive") || 3617 check(FileNumber < 1, FileNumberLoc, "file number less than one") || 3618 check(getTok().isNot(AsmToken::String), 3619 "unexpected token in '.cv_file' directive") || 3620 parseEscapedString(Filename)) 3621 return true; 3622 if (!parseOptionalToken(AsmToken::EndOfStatement)) { 3623 if (check(getTok().isNot(AsmToken::String), 3624 "unexpected token in '.cv_file' directive") || 3625 parseEscapedString(Checksum) || 3626 parseIntToken(ChecksumKind, 3627 "expected checksum kind in '.cv_file' directive") || 3628 parseToken(AsmToken::EndOfStatement, 3629 "unexpected token in '.cv_file' directive")) 3630 return true; 3631 } 3632 3633 Checksum = fromHex(Checksum); 3634 void *CKMem = Ctx.allocate(Checksum.size(), 1); 3635 memcpy(CKMem, Checksum.data(), Checksum.size()); 3636 ArrayRef<uint8_t> ChecksumAsBytes(reinterpret_cast<const uint8_t *>(CKMem), 3637 Checksum.size()); 3638 3639 if (!getStreamer().EmitCVFileDirective(FileNumber, Filename, ChecksumAsBytes, 3640 static_cast<uint8_t>(ChecksumKind))) 3641 return Error(FileNumberLoc, "file number already allocated"); 3642 3643 return false; 3644 } 3645 3646 bool AsmParser::parseCVFunctionId(int64_t &FunctionId, 3647 StringRef DirectiveName) { 3648 SMLoc Loc; 3649 return parseTokenLoc(Loc) || 3650 parseIntToken(FunctionId, "expected function id in '" + DirectiveName + 3651 "' directive") || 3652 check(FunctionId < 0 || FunctionId >= UINT_MAX, Loc, 3653 "expected function id within range [0, UINT_MAX)"); 3654 } 3655 3656 bool AsmParser::parseCVFileId(int64_t &FileNumber, StringRef DirectiveName) { 3657 SMLoc Loc; 3658 return parseTokenLoc(Loc) || 3659 parseIntToken(FileNumber, "expected integer in '" + DirectiveName + 3660 "' directive") || 3661 check(FileNumber < 1, Loc, "file number less than one in '" + 3662 DirectiveName + "' directive") || 3663 check(!getCVContext().isValidFileNumber(FileNumber), Loc, 3664 "unassigned file number in '" + DirectiveName + "' directive"); 3665 } 3666 3667 /// parseDirectiveCVFuncId 3668 /// ::= .cv_func_id FunctionId 3669 /// 3670 /// Introduces a function ID that can be used with .cv_loc. 3671 bool AsmParser::parseDirectiveCVFuncId() { 3672 SMLoc FunctionIdLoc = getTok().getLoc(); 3673 int64_t FunctionId; 3674 3675 if (parseCVFunctionId(FunctionId, ".cv_func_id") || 3676 parseToken(AsmToken::EndOfStatement, 3677 "unexpected token in '.cv_func_id' directive")) 3678 return true; 3679 3680 if (!getStreamer().EmitCVFuncIdDirective(FunctionId)) 3681 return Error(FunctionIdLoc, "function id already allocated"); 3682 3683 return false; 3684 } 3685 3686 /// parseDirectiveCVInlineSiteId 3687 /// ::= .cv_inline_site_id FunctionId 3688 /// "within" IAFunc 3689 /// "inlined_at" IAFile IALine [IACol] 3690 /// 3691 /// Introduces a function ID that can be used with .cv_loc. Includes "inlined 3692 /// at" source location information for use in the line table of the caller, 3693 /// whether the caller is a real function or another inlined call site. 3694 bool AsmParser::parseDirectiveCVInlineSiteId() { 3695 SMLoc FunctionIdLoc = getTok().getLoc(); 3696 int64_t FunctionId; 3697 int64_t IAFunc; 3698 int64_t IAFile; 3699 int64_t IALine; 3700 int64_t IACol = 0; 3701 3702 // FunctionId 3703 if (parseCVFunctionId(FunctionId, ".cv_inline_site_id")) 3704 return true; 3705 3706 // "within" 3707 if (check((getLexer().isNot(AsmToken::Identifier) || 3708 getTok().getIdentifier() != "within"), 3709 "expected 'within' identifier in '.cv_inline_site_id' directive")) 3710 return true; 3711 Lex(); 3712 3713 // IAFunc 3714 if (parseCVFunctionId(IAFunc, ".cv_inline_site_id")) 3715 return true; 3716 3717 // "inlined_at" 3718 if (check((getLexer().isNot(AsmToken::Identifier) || 3719 getTok().getIdentifier() != "inlined_at"), 3720 "expected 'inlined_at' identifier in '.cv_inline_site_id' " 3721 "directive") ) 3722 return true; 3723 Lex(); 3724 3725 // IAFile IALine 3726 if (parseCVFileId(IAFile, ".cv_inline_site_id") || 3727 parseIntToken(IALine, "expected line number after 'inlined_at'")) 3728 return true; 3729 3730 // [IACol] 3731 if (getLexer().is(AsmToken::Integer)) { 3732 IACol = getTok().getIntVal(); 3733 Lex(); 3734 } 3735 3736 if (parseToken(AsmToken::EndOfStatement, 3737 "unexpected token in '.cv_inline_site_id' directive")) 3738 return true; 3739 3740 if (!getStreamer().EmitCVInlineSiteIdDirective(FunctionId, IAFunc, IAFile, 3741 IALine, IACol, FunctionIdLoc)) 3742 return Error(FunctionIdLoc, "function id already allocated"); 3743 3744 return false; 3745 } 3746 3747 /// parseDirectiveCVLoc 3748 /// ::= .cv_loc FunctionId FileNumber [LineNumber] [ColumnPos] [prologue_end] 3749 /// [is_stmt VALUE] 3750 /// The first number is a file number, must have been previously assigned with 3751 /// a .file directive, the second number is the line number and optionally the 3752 /// third number is a column position (zero if not specified). The remaining 3753 /// optional items are .loc sub-directives. 3754 bool AsmParser::parseDirectiveCVLoc() { 3755 SMLoc DirectiveLoc = getTok().getLoc(); 3756 int64_t FunctionId, FileNumber; 3757 if (parseCVFunctionId(FunctionId, ".cv_loc") || 3758 parseCVFileId(FileNumber, ".cv_loc")) 3759 return true; 3760 3761 int64_t LineNumber = 0; 3762 if (getLexer().is(AsmToken::Integer)) { 3763 LineNumber = getTok().getIntVal(); 3764 if (LineNumber < 0) 3765 return TokError("line number less than zero in '.cv_loc' directive"); 3766 Lex(); 3767 } 3768 3769 int64_t ColumnPos = 0; 3770 if (getLexer().is(AsmToken::Integer)) { 3771 ColumnPos = getTok().getIntVal(); 3772 if (ColumnPos < 0) 3773 return TokError("column position less than zero in '.cv_loc' directive"); 3774 Lex(); 3775 } 3776 3777 bool PrologueEnd = false; 3778 uint64_t IsStmt = 0; 3779 3780 auto parseOp = [&]() -> bool { 3781 StringRef Name; 3782 SMLoc Loc = getTok().getLoc(); 3783 if (parseIdentifier(Name)) 3784 return TokError("unexpected token in '.cv_loc' directive"); 3785 if (Name == "prologue_end") 3786 PrologueEnd = true; 3787 else if (Name == "is_stmt") { 3788 Loc = getTok().getLoc(); 3789 const MCExpr *Value; 3790 if (parseExpression(Value)) 3791 return true; 3792 // The expression must be the constant 0 or 1. 3793 IsStmt = ~0ULL; 3794 if (const auto *MCE = dyn_cast<MCConstantExpr>(Value)) 3795 IsStmt = MCE->getValue(); 3796 3797 if (IsStmt > 1) 3798 return Error(Loc, "is_stmt value not 0 or 1"); 3799 } else { 3800 return Error(Loc, "unknown sub-directive in '.cv_loc' directive"); 3801 } 3802 return false; 3803 }; 3804 3805 if (parseMany(parseOp, false /*hasComma*/)) 3806 return true; 3807 3808 getStreamer().emitCVLocDirective(FunctionId, FileNumber, LineNumber, 3809 ColumnPos, PrologueEnd, IsStmt, StringRef(), 3810 DirectiveLoc); 3811 return false; 3812 } 3813 3814 /// parseDirectiveCVLinetable 3815 /// ::= .cv_linetable FunctionId, FnStart, FnEnd 3816 bool AsmParser::parseDirectiveCVLinetable() { 3817 int64_t FunctionId; 3818 StringRef FnStartName, FnEndName; 3819 SMLoc Loc = getTok().getLoc(); 3820 if (parseCVFunctionId(FunctionId, ".cv_linetable") || 3821 parseToken(AsmToken::Comma, 3822 "unexpected token in '.cv_linetable' directive") || 3823 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc, 3824 "expected identifier in directive") || 3825 parseToken(AsmToken::Comma, 3826 "unexpected token in '.cv_linetable' directive") || 3827 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc, 3828 "expected identifier in directive")) 3829 return true; 3830 3831 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName); 3832 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName); 3833 3834 getStreamer().emitCVLinetableDirective(FunctionId, FnStartSym, FnEndSym); 3835 return false; 3836 } 3837 3838 /// parseDirectiveCVInlineLinetable 3839 /// ::= .cv_inline_linetable PrimaryFunctionId FileId LineNum FnStart FnEnd 3840 bool AsmParser::parseDirectiveCVInlineLinetable() { 3841 int64_t PrimaryFunctionId, SourceFileId, SourceLineNum; 3842 StringRef FnStartName, FnEndName; 3843 SMLoc Loc = getTok().getLoc(); 3844 if (parseCVFunctionId(PrimaryFunctionId, ".cv_inline_linetable") || 3845 parseTokenLoc(Loc) || 3846 parseIntToken( 3847 SourceFileId, 3848 "expected SourceField in '.cv_inline_linetable' directive") || 3849 check(SourceFileId <= 0, Loc, 3850 "File id less than zero in '.cv_inline_linetable' directive") || 3851 parseTokenLoc(Loc) || 3852 parseIntToken( 3853 SourceLineNum, 3854 "expected SourceLineNum in '.cv_inline_linetable' directive") || 3855 check(SourceLineNum < 0, Loc, 3856 "Line number less than zero in '.cv_inline_linetable' directive") || 3857 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc, 3858 "expected identifier in directive") || 3859 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc, 3860 "expected identifier in directive")) 3861 return true; 3862 3863 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement")) 3864 return true; 3865 3866 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName); 3867 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName); 3868 getStreamer().emitCVInlineLinetableDirective(PrimaryFunctionId, SourceFileId, 3869 SourceLineNum, FnStartSym, 3870 FnEndSym); 3871 return false; 3872 } 3873 3874 void AsmParser::initializeCVDefRangeTypeMap() { 3875 CVDefRangeTypeMap["reg"] = CVDR_DEFRANGE_REGISTER; 3876 CVDefRangeTypeMap["frame_ptr_rel"] = CVDR_DEFRANGE_FRAMEPOINTER_REL; 3877 CVDefRangeTypeMap["subfield_reg"] = CVDR_DEFRANGE_SUBFIELD_REGISTER; 3878 CVDefRangeTypeMap["reg_rel"] = CVDR_DEFRANGE_REGISTER_REL; 3879 } 3880 3881 /// parseDirectiveCVDefRange 3882 /// ::= .cv_def_range RangeStart RangeEnd (GapStart GapEnd)*, bytes* 3883 bool AsmParser::parseDirectiveCVDefRange() { 3884 SMLoc Loc; 3885 std::vector<std::pair<const MCSymbol *, const MCSymbol *>> Ranges; 3886 while (getLexer().is(AsmToken::Identifier)) { 3887 Loc = getLexer().getLoc(); 3888 StringRef GapStartName; 3889 if (parseIdentifier(GapStartName)) 3890 return Error(Loc, "expected identifier in directive"); 3891 MCSymbol *GapStartSym = getContext().getOrCreateSymbol(GapStartName); 3892 3893 Loc = getLexer().getLoc(); 3894 StringRef GapEndName; 3895 if (parseIdentifier(GapEndName)) 3896 return Error(Loc, "expected identifier in directive"); 3897 MCSymbol *GapEndSym = getContext().getOrCreateSymbol(GapEndName); 3898 3899 Ranges.push_back({GapStartSym, GapEndSym}); 3900 } 3901 3902 StringRef CVDefRangeTypeStr; 3903 if (parseToken( 3904 AsmToken::Comma, 3905 "expected comma before def_range type in .cv_def_range directive") || 3906 parseIdentifier(CVDefRangeTypeStr)) 3907 return Error(Loc, "expected def_range type in directive"); 3908 3909 StringMap<CVDefRangeType>::const_iterator CVTypeIt = 3910 CVDefRangeTypeMap.find(CVDefRangeTypeStr); 3911 CVDefRangeType CVDRType = (CVTypeIt == CVDefRangeTypeMap.end()) 3912 ? CVDR_DEFRANGE 3913 : CVTypeIt->getValue(); 3914 switch (CVDRType) { 3915 case CVDR_DEFRANGE_REGISTER: { 3916 int64_t DRRegister; 3917 if (parseToken(AsmToken::Comma, "expected comma before register number in " 3918 ".cv_def_range directive") || 3919 parseAbsoluteExpression(DRRegister)) 3920 return Error(Loc, "expected register number"); 3921 3922 codeview::DefRangeRegisterHeader DRHdr; 3923 DRHdr.Register = DRRegister; 3924 DRHdr.MayHaveNoName = 0; 3925 getStreamer().emitCVDefRangeDirective(Ranges, DRHdr); 3926 break; 3927 } 3928 case CVDR_DEFRANGE_FRAMEPOINTER_REL: { 3929 int64_t DROffset; 3930 if (parseToken(AsmToken::Comma, 3931 "expected comma before offset in .cv_def_range directive") || 3932 parseAbsoluteExpression(DROffset)) 3933 return Error(Loc, "expected offset value"); 3934 3935 codeview::DefRangeFramePointerRelHeader DRHdr; 3936 DRHdr.Offset = DROffset; 3937 getStreamer().emitCVDefRangeDirective(Ranges, DRHdr); 3938 break; 3939 } 3940 case CVDR_DEFRANGE_SUBFIELD_REGISTER: { 3941 int64_t DRRegister; 3942 int64_t DROffsetInParent; 3943 if (parseToken(AsmToken::Comma, "expected comma before register number in " 3944 ".cv_def_range directive") || 3945 parseAbsoluteExpression(DRRegister)) 3946 return Error(Loc, "expected register number"); 3947 if (parseToken(AsmToken::Comma, 3948 "expected comma before offset in .cv_def_range directive") || 3949 parseAbsoluteExpression(DROffsetInParent)) 3950 return Error(Loc, "expected offset value"); 3951 3952 codeview::DefRangeSubfieldRegisterHeader DRHdr; 3953 DRHdr.Register = DRRegister; 3954 DRHdr.MayHaveNoName = 0; 3955 DRHdr.OffsetInParent = DROffsetInParent; 3956 getStreamer().emitCVDefRangeDirective(Ranges, DRHdr); 3957 break; 3958 } 3959 case CVDR_DEFRANGE_REGISTER_REL: { 3960 int64_t DRRegister; 3961 int64_t DRFlags; 3962 int64_t DRBasePointerOffset; 3963 if (parseToken(AsmToken::Comma, "expected comma before register number in " 3964 ".cv_def_range directive") || 3965 parseAbsoluteExpression(DRRegister)) 3966 return Error(Loc, "expected register value"); 3967 if (parseToken( 3968 AsmToken::Comma, 3969 "expected comma before flag value in .cv_def_range directive") || 3970 parseAbsoluteExpression(DRFlags)) 3971 return Error(Loc, "expected flag value"); 3972 if (parseToken(AsmToken::Comma, "expected comma before base pointer offset " 3973 "in .cv_def_range directive") || 3974 parseAbsoluteExpression(DRBasePointerOffset)) 3975 return Error(Loc, "expected base pointer offset value"); 3976 3977 codeview::DefRangeRegisterRelHeader DRHdr; 3978 DRHdr.Register = DRRegister; 3979 DRHdr.Flags = DRFlags; 3980 DRHdr.BasePointerOffset = DRBasePointerOffset; 3981 getStreamer().emitCVDefRangeDirective(Ranges, DRHdr); 3982 break; 3983 } 3984 default: 3985 return Error(Loc, "unexpected def_range type in .cv_def_range directive"); 3986 } 3987 return true; 3988 } 3989 3990 /// parseDirectiveCVString 3991 /// ::= .cv_stringtable "string" 3992 bool AsmParser::parseDirectiveCVString() { 3993 std::string Data; 3994 if (checkForValidSection() || parseEscapedString(Data)) 3995 return addErrorSuffix(" in '.cv_string' directive"); 3996 3997 // Put the string in the table and emit the offset. 3998 std::pair<StringRef, unsigned> Insertion = 3999 getCVContext().addToStringTable(Data); 4000 getStreamer().emitInt32(Insertion.second); 4001 return false; 4002 } 4003 4004 /// parseDirectiveCVStringTable 4005 /// ::= .cv_stringtable 4006 bool AsmParser::parseDirectiveCVStringTable() { 4007 getStreamer().emitCVStringTableDirective(); 4008 return false; 4009 } 4010 4011 /// parseDirectiveCVFileChecksums 4012 /// ::= .cv_filechecksums 4013 bool AsmParser::parseDirectiveCVFileChecksums() { 4014 getStreamer().emitCVFileChecksumsDirective(); 4015 return false; 4016 } 4017 4018 /// parseDirectiveCVFileChecksumOffset 4019 /// ::= .cv_filechecksumoffset fileno 4020 bool AsmParser::parseDirectiveCVFileChecksumOffset() { 4021 int64_t FileNo; 4022 if (parseIntToken(FileNo, "expected identifier in directive")) 4023 return true; 4024 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement")) 4025 return true; 4026 getStreamer().emitCVFileChecksumOffsetDirective(FileNo); 4027 return false; 4028 } 4029 4030 /// parseDirectiveCVFPOData 4031 /// ::= .cv_fpo_data procsym 4032 bool AsmParser::parseDirectiveCVFPOData() { 4033 SMLoc DirLoc = getLexer().getLoc(); 4034 StringRef ProcName; 4035 if (parseIdentifier(ProcName)) 4036 return TokError("expected symbol name"); 4037 if (parseEOL("unexpected tokens")) 4038 return addErrorSuffix(" in '.cv_fpo_data' directive"); 4039 MCSymbol *ProcSym = getContext().getOrCreateSymbol(ProcName); 4040 getStreamer().EmitCVFPOData(ProcSym, DirLoc); 4041 return false; 4042 } 4043 4044 /// parseDirectiveCFISections 4045 /// ::= .cfi_sections section [, section] 4046 bool AsmParser::parseDirectiveCFISections() { 4047 StringRef Name; 4048 bool EH = false; 4049 bool Debug = false; 4050 4051 if (parseIdentifier(Name)) 4052 return TokError("Expected an identifier"); 4053 4054 if (Name == ".eh_frame") 4055 EH = true; 4056 else if (Name == ".debug_frame") 4057 Debug = true; 4058 4059 if (getLexer().is(AsmToken::Comma)) { 4060 Lex(); 4061 4062 if (parseIdentifier(Name)) 4063 return TokError("Expected an identifier"); 4064 4065 if (Name == ".eh_frame") 4066 EH = true; 4067 else if (Name == ".debug_frame") 4068 Debug = true; 4069 } 4070 4071 getStreamer().emitCFISections(EH, Debug); 4072 return false; 4073 } 4074 4075 /// parseDirectiveCFIStartProc 4076 /// ::= .cfi_startproc [simple] 4077 bool AsmParser::parseDirectiveCFIStartProc() { 4078 StringRef Simple; 4079 if (!parseOptionalToken(AsmToken::EndOfStatement)) { 4080 if (check(parseIdentifier(Simple) || Simple != "simple", 4081 "unexpected token") || 4082 parseToken(AsmToken::EndOfStatement)) 4083 return addErrorSuffix(" in '.cfi_startproc' directive"); 4084 } 4085 4086 // TODO(kristina): Deal with a corner case of incorrect diagnostic context 4087 // being produced if this directive is emitted as part of preprocessor macro 4088 // expansion which can *ONLY* happen if Clang's cc1as is the API consumer. 4089 // Tools like llvm-mc on the other hand are not affected by it, and report 4090 // correct context information. 4091 getStreamer().emitCFIStartProc(!Simple.empty(), Lexer.getLoc()); 4092 return false; 4093 } 4094 4095 /// parseDirectiveCFIEndProc 4096 /// ::= .cfi_endproc 4097 bool AsmParser::parseDirectiveCFIEndProc() { 4098 getStreamer().emitCFIEndProc(); 4099 return false; 4100 } 4101 4102 /// parse register name or number. 4103 bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register, 4104 SMLoc DirectiveLoc) { 4105 unsigned RegNo; 4106 4107 if (getLexer().isNot(AsmToken::Integer)) { 4108 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc)) 4109 return true; 4110 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true); 4111 } else 4112 return parseAbsoluteExpression(Register); 4113 4114 return false; 4115 } 4116 4117 /// parseDirectiveCFIDefCfa 4118 /// ::= .cfi_def_cfa register, offset 4119 bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) { 4120 int64_t Register = 0, Offset = 0; 4121 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) || 4122 parseToken(AsmToken::Comma, "unexpected token in directive") || 4123 parseAbsoluteExpression(Offset)) 4124 return true; 4125 4126 getStreamer().emitCFIDefCfa(Register, Offset); 4127 return false; 4128 } 4129 4130 /// parseDirectiveCFIDefCfaOffset 4131 /// ::= .cfi_def_cfa_offset offset 4132 bool AsmParser::parseDirectiveCFIDefCfaOffset() { 4133 int64_t Offset = 0; 4134 if (parseAbsoluteExpression(Offset)) 4135 return true; 4136 4137 getStreamer().emitCFIDefCfaOffset(Offset); 4138 return false; 4139 } 4140 4141 /// parseDirectiveCFIRegister 4142 /// ::= .cfi_register register, register 4143 bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) { 4144 int64_t Register1 = 0, Register2 = 0; 4145 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc) || 4146 parseToken(AsmToken::Comma, "unexpected token in directive") || 4147 parseRegisterOrRegisterNumber(Register2, DirectiveLoc)) 4148 return true; 4149 4150 getStreamer().emitCFIRegister(Register1, Register2); 4151 return false; 4152 } 4153 4154 /// parseDirectiveCFIWindowSave 4155 /// ::= .cfi_window_save 4156 bool AsmParser::parseDirectiveCFIWindowSave() { 4157 getStreamer().emitCFIWindowSave(); 4158 return false; 4159 } 4160 4161 /// parseDirectiveCFIAdjustCfaOffset 4162 /// ::= .cfi_adjust_cfa_offset adjustment 4163 bool AsmParser::parseDirectiveCFIAdjustCfaOffset() { 4164 int64_t Adjustment = 0; 4165 if (parseAbsoluteExpression(Adjustment)) 4166 return true; 4167 4168 getStreamer().emitCFIAdjustCfaOffset(Adjustment); 4169 return false; 4170 } 4171 4172 /// parseDirectiveCFIDefCfaRegister 4173 /// ::= .cfi_def_cfa_register register 4174 bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) { 4175 int64_t Register = 0; 4176 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc)) 4177 return true; 4178 4179 getStreamer().emitCFIDefCfaRegister(Register); 4180 return false; 4181 } 4182 4183 /// parseDirectiveCFIOffset 4184 /// ::= .cfi_offset register, offset 4185 bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) { 4186 int64_t Register = 0; 4187 int64_t Offset = 0; 4188 4189 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) || 4190 parseToken(AsmToken::Comma, "unexpected token in directive") || 4191 parseAbsoluteExpression(Offset)) 4192 return true; 4193 4194 getStreamer().emitCFIOffset(Register, Offset); 4195 return false; 4196 } 4197 4198 /// parseDirectiveCFIRelOffset 4199 /// ::= .cfi_rel_offset register, offset 4200 bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) { 4201 int64_t Register = 0, Offset = 0; 4202 4203 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) || 4204 parseToken(AsmToken::Comma, "unexpected token in directive") || 4205 parseAbsoluteExpression(Offset)) 4206 return true; 4207 4208 getStreamer().emitCFIRelOffset(Register, Offset); 4209 return false; 4210 } 4211 4212 static bool isValidEncoding(int64_t Encoding) { 4213 if (Encoding & ~0xff) 4214 return false; 4215 4216 if (Encoding == dwarf::DW_EH_PE_omit) 4217 return true; 4218 4219 const unsigned Format = Encoding & 0xf; 4220 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 && 4221 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 && 4222 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 && 4223 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed) 4224 return false; 4225 4226 const unsigned Application = Encoding & 0x70; 4227 if (Application != dwarf::DW_EH_PE_absptr && 4228 Application != dwarf::DW_EH_PE_pcrel) 4229 return false; 4230 4231 return true; 4232 } 4233 4234 /// parseDirectiveCFIPersonalityOrLsda 4235 /// IsPersonality true for cfi_personality, false for cfi_lsda 4236 /// ::= .cfi_personality encoding, [symbol_name] 4237 /// ::= .cfi_lsda encoding, [symbol_name] 4238 bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) { 4239 int64_t Encoding = 0; 4240 if (parseAbsoluteExpression(Encoding)) 4241 return true; 4242 if (Encoding == dwarf::DW_EH_PE_omit) 4243 return false; 4244 4245 StringRef Name; 4246 if (check(!isValidEncoding(Encoding), "unsupported encoding.") || 4247 parseToken(AsmToken::Comma, "unexpected token in directive") || 4248 check(parseIdentifier(Name), "expected identifier in directive")) 4249 return true; 4250 4251 MCSymbol *Sym = getContext().getOrCreateSymbol(Name); 4252 4253 if (IsPersonality) 4254 getStreamer().emitCFIPersonality(Sym, Encoding); 4255 else 4256 getStreamer().emitCFILsda(Sym, Encoding); 4257 return false; 4258 } 4259 4260 /// parseDirectiveCFIRememberState 4261 /// ::= .cfi_remember_state 4262 bool AsmParser::parseDirectiveCFIRememberState() { 4263 getStreamer().emitCFIRememberState(); 4264 return false; 4265 } 4266 4267 /// parseDirectiveCFIRestoreState 4268 /// ::= .cfi_remember_state 4269 bool AsmParser::parseDirectiveCFIRestoreState() { 4270 getStreamer().emitCFIRestoreState(); 4271 return false; 4272 } 4273 4274 /// parseDirectiveCFISameValue 4275 /// ::= .cfi_same_value register 4276 bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) { 4277 int64_t Register = 0; 4278 4279 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc)) 4280 return true; 4281 4282 getStreamer().emitCFISameValue(Register); 4283 return false; 4284 } 4285 4286 /// parseDirectiveCFIRestore 4287 /// ::= .cfi_restore register 4288 bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) { 4289 int64_t Register = 0; 4290 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc)) 4291 return true; 4292 4293 getStreamer().emitCFIRestore(Register); 4294 return false; 4295 } 4296 4297 /// parseDirectiveCFIEscape 4298 /// ::= .cfi_escape expression[,...] 4299 bool AsmParser::parseDirectiveCFIEscape() { 4300 std::string Values; 4301 int64_t CurrValue; 4302 if (parseAbsoluteExpression(CurrValue)) 4303 return true; 4304 4305 Values.push_back((uint8_t)CurrValue); 4306 4307 while (getLexer().is(AsmToken::Comma)) { 4308 Lex(); 4309 4310 if (parseAbsoluteExpression(CurrValue)) 4311 return true; 4312 4313 Values.push_back((uint8_t)CurrValue); 4314 } 4315 4316 getStreamer().emitCFIEscape(Values); 4317 return false; 4318 } 4319 4320 /// parseDirectiveCFIReturnColumn 4321 /// ::= .cfi_return_column register 4322 bool AsmParser::parseDirectiveCFIReturnColumn(SMLoc DirectiveLoc) { 4323 int64_t Register = 0; 4324 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc)) 4325 return true; 4326 getStreamer().emitCFIReturnColumn(Register); 4327 return false; 4328 } 4329 4330 /// parseDirectiveCFISignalFrame 4331 /// ::= .cfi_signal_frame 4332 bool AsmParser::parseDirectiveCFISignalFrame() { 4333 if (parseToken(AsmToken::EndOfStatement, 4334 "unexpected token in '.cfi_signal_frame'")) 4335 return true; 4336 4337 getStreamer().emitCFISignalFrame(); 4338 return false; 4339 } 4340 4341 /// parseDirectiveCFIUndefined 4342 /// ::= .cfi_undefined register 4343 bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) { 4344 int64_t Register = 0; 4345 4346 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc)) 4347 return true; 4348 4349 getStreamer().emitCFIUndefined(Register); 4350 return false; 4351 } 4352 4353 /// parseDirectiveAltmacro 4354 /// ::= .altmacro 4355 /// ::= .noaltmacro 4356 bool AsmParser::parseDirectiveAltmacro(StringRef Directive) { 4357 if (getLexer().isNot(AsmToken::EndOfStatement)) 4358 return TokError("unexpected token in '" + Directive + "' directive"); 4359 AltMacroMode = (Directive == ".altmacro"); 4360 return false; 4361 } 4362 4363 /// parseDirectiveMacrosOnOff 4364 /// ::= .macros_on 4365 /// ::= .macros_off 4366 bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) { 4367 if (parseToken(AsmToken::EndOfStatement, 4368 "unexpected token in '" + Directive + "' directive")) 4369 return true; 4370 4371 setMacrosEnabled(Directive == ".macros_on"); 4372 return false; 4373 } 4374 4375 /// parseDirectiveMacro 4376 /// ::= .macro name[,] [parameters] 4377 bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) { 4378 StringRef Name; 4379 if (parseIdentifier(Name)) 4380 return TokError("expected identifier in '.macro' directive"); 4381 4382 if (getLexer().is(AsmToken::Comma)) 4383 Lex(); 4384 4385 MCAsmMacroParameters Parameters; 4386 while (getLexer().isNot(AsmToken::EndOfStatement)) { 4387 4388 if (!Parameters.empty() && Parameters.back().Vararg) 4389 return Error(Lexer.getLoc(), "vararg parameter '" + 4390 Parameters.back().Name + 4391 "' should be the last parameter"); 4392 4393 MCAsmMacroParameter Parameter; 4394 if (parseIdentifier(Parameter.Name)) 4395 return TokError("expected identifier in '.macro' directive"); 4396 4397 // Emit an error if two (or more) named parameters share the same name 4398 for (const MCAsmMacroParameter& CurrParam : Parameters) 4399 if (CurrParam.Name.equals(Parameter.Name)) 4400 return TokError("macro '" + Name + "' has multiple parameters" 4401 " named '" + Parameter.Name + "'"); 4402 4403 if (Lexer.is(AsmToken::Colon)) { 4404 Lex(); // consume ':' 4405 4406 SMLoc QualLoc; 4407 StringRef Qualifier; 4408 4409 QualLoc = Lexer.getLoc(); 4410 if (parseIdentifier(Qualifier)) 4411 return Error(QualLoc, "missing parameter qualifier for " 4412 "'" + Parameter.Name + "' in macro '" + Name + "'"); 4413 4414 if (Qualifier == "req") 4415 Parameter.Required = true; 4416 else if (Qualifier == "vararg") 4417 Parameter.Vararg = true; 4418 else 4419 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier " 4420 "for '" + Parameter.Name + "' in macro '" + Name + "'"); 4421 } 4422 4423 if (getLexer().is(AsmToken::Equal)) { 4424 Lex(); 4425 4426 SMLoc ParamLoc; 4427 4428 ParamLoc = Lexer.getLoc(); 4429 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false )) 4430 return true; 4431 4432 if (Parameter.Required) 4433 Warning(ParamLoc, "pointless default value for required parameter " 4434 "'" + Parameter.Name + "' in macro '" + Name + "'"); 4435 } 4436 4437 Parameters.push_back(std::move(Parameter)); 4438 4439 if (getLexer().is(AsmToken::Comma)) 4440 Lex(); 4441 } 4442 4443 // Eat just the end of statement. 4444 Lexer.Lex(); 4445 4446 // Consuming deferred text, so use Lexer.Lex to ignore Lexing Errors 4447 AsmToken EndToken, StartToken = getTok(); 4448 unsigned MacroDepth = 0; 4449 // Lex the macro definition. 4450 while (true) { 4451 // Ignore Lexing errors in macros. 4452 while (Lexer.is(AsmToken::Error)) { 4453 Lexer.Lex(); 4454 } 4455 4456 // Check whether we have reached the end of the file. 4457 if (getLexer().is(AsmToken::Eof)) 4458 return Error(DirectiveLoc, "no matching '.endmacro' in definition"); 4459 4460 // Otherwise, check whether we have reach the .endmacro or the start of a 4461 // preprocessor line marker. 4462 if (getLexer().is(AsmToken::Identifier)) { 4463 if (getTok().getIdentifier() == ".endm" || 4464 getTok().getIdentifier() == ".endmacro") { 4465 if (MacroDepth == 0) { // Outermost macro. 4466 EndToken = getTok(); 4467 Lexer.Lex(); 4468 if (getLexer().isNot(AsmToken::EndOfStatement)) 4469 return TokError("unexpected token in '" + EndToken.getIdentifier() + 4470 "' directive"); 4471 break; 4472 } else { 4473 // Otherwise we just found the end of an inner macro. 4474 --MacroDepth; 4475 } 4476 } else if (getTok().getIdentifier() == ".macro") { 4477 // We allow nested macros. Those aren't instantiated until the outermost 4478 // macro is expanded so just ignore them for now. 4479 ++MacroDepth; 4480 } 4481 } else if (Lexer.is(AsmToken::HashDirective)) { 4482 (void)parseCppHashLineFilenameComment(getLexer().getLoc()); 4483 } 4484 4485 // Otherwise, scan til the end of the statement. 4486 eatToEndOfStatement(); 4487 } 4488 4489 if (getContext().lookupMacro(Name)) { 4490 return Error(DirectiveLoc, "macro '" + Name + "' is already defined"); 4491 } 4492 4493 const char *BodyStart = StartToken.getLoc().getPointer(); 4494 const char *BodyEnd = EndToken.getLoc().getPointer(); 4495 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart); 4496 checkForBadMacro(DirectiveLoc, Name, Body, Parameters); 4497 MCAsmMacro Macro(Name, Body, std::move(Parameters)); 4498 DEBUG_WITH_TYPE("asm-macros", dbgs() << "Defining new macro:\n"; 4499 Macro.dump()); 4500 getContext().defineMacro(Name, std::move(Macro)); 4501 return false; 4502 } 4503 4504 /// checkForBadMacro 4505 /// 4506 /// With the support added for named parameters there may be code out there that 4507 /// is transitioning from positional parameters. In versions of gas that did 4508 /// not support named parameters they would be ignored on the macro definition. 4509 /// But to support both styles of parameters this is not possible so if a macro 4510 /// definition has named parameters but does not use them and has what appears 4511 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a 4512 /// warning that the positional parameter found in body which have no effect. 4513 /// Hoping the developer will either remove the named parameters from the macro 4514 /// definition so the positional parameters get used if that was what was 4515 /// intended or change the macro to use the named parameters. It is possible 4516 /// this warning will trigger when the none of the named parameters are used 4517 /// and the strings like $1 are infact to simply to be passed trough unchanged. 4518 void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, 4519 StringRef Body, 4520 ArrayRef<MCAsmMacroParameter> Parameters) { 4521 // If this macro is not defined with named parameters the warning we are 4522 // checking for here doesn't apply. 4523 unsigned NParameters = Parameters.size(); 4524 if (NParameters == 0) 4525 return; 4526 4527 bool NamedParametersFound = false; 4528 bool PositionalParametersFound = false; 4529 4530 // Look at the body of the macro for use of both the named parameters and what 4531 // are likely to be positional parameters. This is what expandMacro() is 4532 // doing when it finds the parameters in the body. 4533 while (!Body.empty()) { 4534 // Scan for the next possible parameter. 4535 std::size_t End = Body.size(), Pos = 0; 4536 for (; Pos != End; ++Pos) { 4537 // Check for a substitution or escape. 4538 // This macro is defined with parameters, look for \foo, \bar, etc. 4539 if (Body[Pos] == '\\' && Pos + 1 != End) 4540 break; 4541 4542 // This macro should have parameters, but look for $0, $1, ..., $n too. 4543 if (Body[Pos] != '$' || Pos + 1 == End) 4544 continue; 4545 char Next = Body[Pos + 1]; 4546 if (Next == '$' || Next == 'n' || 4547 isdigit(static_cast<unsigned char>(Next))) 4548 break; 4549 } 4550 4551 // Check if we reached the end. 4552 if (Pos == End) 4553 break; 4554 4555 if (Body[Pos] == '$') { 4556 switch (Body[Pos + 1]) { 4557 // $$ => $ 4558 case '$': 4559 break; 4560 4561 // $n => number of arguments 4562 case 'n': 4563 PositionalParametersFound = true; 4564 break; 4565 4566 // $[0-9] => argument 4567 default: { 4568 PositionalParametersFound = true; 4569 break; 4570 } 4571 } 4572 Pos += 2; 4573 } else { 4574 unsigned I = Pos + 1; 4575 while (isIdentifierChar(Body[I]) && I + 1 != End) 4576 ++I; 4577 4578 const char *Begin = Body.data() + Pos + 1; 4579 StringRef Argument(Begin, I - (Pos + 1)); 4580 unsigned Index = 0; 4581 for (; Index < NParameters; ++Index) 4582 if (Parameters[Index].Name == Argument) 4583 break; 4584 4585 if (Index == NParameters) { 4586 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')') 4587 Pos += 3; 4588 else { 4589 Pos = I; 4590 } 4591 } else { 4592 NamedParametersFound = true; 4593 Pos += 1 + Argument.size(); 4594 } 4595 } 4596 // Update the scan point. 4597 Body = Body.substr(Pos); 4598 } 4599 4600 if (!NamedParametersFound && PositionalParametersFound) 4601 Warning(DirectiveLoc, "macro defined with named parameters which are not " 4602 "used in macro body, possible positional parameter " 4603 "found in body which will have no effect"); 4604 } 4605 4606 /// parseDirectiveExitMacro 4607 /// ::= .exitm 4608 bool AsmParser::parseDirectiveExitMacro(StringRef Directive) { 4609 if (parseToken(AsmToken::EndOfStatement, 4610 "unexpected token in '" + Directive + "' directive")) 4611 return true; 4612 4613 if (!isInsideMacroInstantiation()) 4614 return TokError("unexpected '" + Directive + "' in file, " 4615 "no current macro definition"); 4616 4617 // Exit all conditionals that are active in the current macro. 4618 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) { 4619 TheCondState = TheCondStack.back(); 4620 TheCondStack.pop_back(); 4621 } 4622 4623 handleMacroExit(); 4624 return false; 4625 } 4626 4627 /// parseDirectiveEndMacro 4628 /// ::= .endm 4629 /// ::= .endmacro 4630 bool AsmParser::parseDirectiveEndMacro(StringRef Directive) { 4631 if (getLexer().isNot(AsmToken::EndOfStatement)) 4632 return TokError("unexpected token in '" + Directive + "' directive"); 4633 4634 // If we are inside a macro instantiation, terminate the current 4635 // instantiation. 4636 if (isInsideMacroInstantiation()) { 4637 handleMacroExit(); 4638 return false; 4639 } 4640 4641 // Otherwise, this .endmacro is a stray entry in the file; well formed 4642 // .endmacro directives are handled during the macro definition parsing. 4643 return TokError("unexpected '" + Directive + "' in file, " 4644 "no current macro definition"); 4645 } 4646 4647 /// parseDirectivePurgeMacro 4648 /// ::= .purgem 4649 bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) { 4650 StringRef Name; 4651 SMLoc Loc; 4652 if (parseTokenLoc(Loc) || 4653 check(parseIdentifier(Name), Loc, 4654 "expected identifier in '.purgem' directive") || 4655 parseToken(AsmToken::EndOfStatement, 4656 "unexpected token in '.purgem' directive")) 4657 return true; 4658 4659 if (!getContext().lookupMacro(Name)) 4660 return Error(DirectiveLoc, "macro '" + Name + "' is not defined"); 4661 4662 getContext().undefineMacro(Name); 4663 DEBUG_WITH_TYPE("asm-macros", dbgs() 4664 << "Un-defining macro: " << Name << "\n"); 4665 return false; 4666 } 4667 4668 /// parseDirectiveBundleAlignMode 4669 /// ::= {.bundle_align_mode} expression 4670 bool AsmParser::parseDirectiveBundleAlignMode() { 4671 // Expect a single argument: an expression that evaluates to a constant 4672 // in the inclusive range 0-30. 4673 SMLoc ExprLoc = getLexer().getLoc(); 4674 int64_t AlignSizePow2; 4675 if (checkForValidSection() || parseAbsoluteExpression(AlignSizePow2) || 4676 parseToken(AsmToken::EndOfStatement, "unexpected token after expression " 4677 "in '.bundle_align_mode' " 4678 "directive") || 4679 check(AlignSizePow2 < 0 || AlignSizePow2 > 30, ExprLoc, 4680 "invalid bundle alignment size (expected between 0 and 30)")) 4681 return true; 4682 4683 // Because of AlignSizePow2's verified range we can safely truncate it to 4684 // unsigned. 4685 getStreamer().emitBundleAlignMode(static_cast<unsigned>(AlignSizePow2)); 4686 return false; 4687 } 4688 4689 /// parseDirectiveBundleLock 4690 /// ::= {.bundle_lock} [align_to_end] 4691 bool AsmParser::parseDirectiveBundleLock() { 4692 if (checkForValidSection()) 4693 return true; 4694 bool AlignToEnd = false; 4695 4696 StringRef Option; 4697 SMLoc Loc = getTok().getLoc(); 4698 const char *kInvalidOptionError = 4699 "invalid option for '.bundle_lock' directive"; 4700 4701 if (!parseOptionalToken(AsmToken::EndOfStatement)) { 4702 if (check(parseIdentifier(Option), Loc, kInvalidOptionError) || 4703 check(Option != "align_to_end", Loc, kInvalidOptionError) || 4704 parseToken(AsmToken::EndOfStatement, 4705 "unexpected token after '.bundle_lock' directive option")) 4706 return true; 4707 AlignToEnd = true; 4708 } 4709 4710 getStreamer().emitBundleLock(AlignToEnd); 4711 return false; 4712 } 4713 4714 /// parseDirectiveBundleLock 4715 /// ::= {.bundle_lock} 4716 bool AsmParser::parseDirectiveBundleUnlock() { 4717 if (checkForValidSection() || 4718 parseToken(AsmToken::EndOfStatement, 4719 "unexpected token in '.bundle_unlock' directive")) 4720 return true; 4721 4722 getStreamer().emitBundleUnlock(); 4723 return false; 4724 } 4725 4726 /// parseDirectiveSpace 4727 /// ::= (.skip | .space) expression [ , expression ] 4728 bool AsmParser::parseDirectiveSpace(StringRef IDVal) { 4729 SMLoc NumBytesLoc = Lexer.getLoc(); 4730 const MCExpr *NumBytes; 4731 if (checkForValidSection() || parseExpression(NumBytes)) 4732 return true; 4733 4734 int64_t FillExpr = 0; 4735 if (parseOptionalToken(AsmToken::Comma)) 4736 if (parseAbsoluteExpression(FillExpr)) 4737 return addErrorSuffix("in '" + Twine(IDVal) + "' directive"); 4738 if (parseToken(AsmToken::EndOfStatement)) 4739 return addErrorSuffix("in '" + Twine(IDVal) + "' directive"); 4740 4741 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0. 4742 getStreamer().emitFill(*NumBytes, FillExpr, NumBytesLoc); 4743 4744 return false; 4745 } 4746 4747 /// parseDirectiveDCB 4748 /// ::= .dcb.{b, l, w} expression, expression 4749 bool AsmParser::parseDirectiveDCB(StringRef IDVal, unsigned Size) { 4750 SMLoc NumValuesLoc = Lexer.getLoc(); 4751 int64_t NumValues; 4752 if (checkForValidSection() || parseAbsoluteExpression(NumValues)) 4753 return true; 4754 4755 if (NumValues < 0) { 4756 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect"); 4757 return false; 4758 } 4759 4760 if (parseToken(AsmToken::Comma, 4761 "unexpected token in '" + Twine(IDVal) + "' directive")) 4762 return true; 4763 4764 const MCExpr *Value; 4765 SMLoc ExprLoc = getLexer().getLoc(); 4766 if (parseExpression(Value)) 4767 return true; 4768 4769 // Special case constant expressions to match code generator. 4770 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) { 4771 assert(Size <= 8 && "Invalid size"); 4772 uint64_t IntValue = MCE->getValue(); 4773 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue)) 4774 return Error(ExprLoc, "literal value out of range for directive"); 4775 for (uint64_t i = 0, e = NumValues; i != e; ++i) 4776 getStreamer().emitIntValue(IntValue, Size); 4777 } else { 4778 for (uint64_t i = 0, e = NumValues; i != e; ++i) 4779 getStreamer().emitValue(Value, Size, ExprLoc); 4780 } 4781 4782 if (parseToken(AsmToken::EndOfStatement, 4783 "unexpected token in '" + Twine(IDVal) + "' directive")) 4784 return true; 4785 4786 return false; 4787 } 4788 4789 /// parseDirectiveRealDCB 4790 /// ::= .dcb.{d, s} expression, expression 4791 bool AsmParser::parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &Semantics) { 4792 SMLoc NumValuesLoc = Lexer.getLoc(); 4793 int64_t NumValues; 4794 if (checkForValidSection() || parseAbsoluteExpression(NumValues)) 4795 return true; 4796 4797 if (NumValues < 0) { 4798 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect"); 4799 return false; 4800 } 4801 4802 if (parseToken(AsmToken::Comma, 4803 "unexpected token in '" + Twine(IDVal) + "' directive")) 4804 return true; 4805 4806 APInt AsInt; 4807 if (parseRealValue(Semantics, AsInt)) 4808 return true; 4809 4810 if (parseToken(AsmToken::EndOfStatement, 4811 "unexpected token in '" + Twine(IDVal) + "' directive")) 4812 return true; 4813 4814 for (uint64_t i = 0, e = NumValues; i != e; ++i) 4815 getStreamer().emitIntValue(AsInt.getLimitedValue(), 4816 AsInt.getBitWidth() / 8); 4817 4818 return false; 4819 } 4820 4821 /// parseDirectiveDS 4822 /// ::= .ds.{b, d, l, p, s, w, x} expression 4823 bool AsmParser::parseDirectiveDS(StringRef IDVal, unsigned Size) { 4824 SMLoc NumValuesLoc = Lexer.getLoc(); 4825 int64_t NumValues; 4826 if (checkForValidSection() || parseAbsoluteExpression(NumValues)) 4827 return true; 4828 4829 if (NumValues < 0) { 4830 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect"); 4831 return false; 4832 } 4833 4834 if (parseToken(AsmToken::EndOfStatement, 4835 "unexpected token in '" + Twine(IDVal) + "' directive")) 4836 return true; 4837 4838 for (uint64_t i = 0, e = NumValues; i != e; ++i) 4839 getStreamer().emitFill(Size, 0); 4840 4841 return false; 4842 } 4843 4844 /// parseDirectiveLEB128 4845 /// ::= (.sleb128 | .uleb128) [ expression (, expression)* ] 4846 bool AsmParser::parseDirectiveLEB128(bool Signed) { 4847 if (checkForValidSection()) 4848 return true; 4849 4850 auto parseOp = [&]() -> bool { 4851 const MCExpr *Value; 4852 if (parseExpression(Value)) 4853 return true; 4854 if (Signed) 4855 getStreamer().emitSLEB128Value(Value); 4856 else 4857 getStreamer().emitULEB128Value(Value); 4858 return false; 4859 }; 4860 4861 if (parseMany(parseOp)) 4862 return addErrorSuffix(" in directive"); 4863 4864 return false; 4865 } 4866 4867 /// parseDirectiveSymbolAttribute 4868 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ] 4869 bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) { 4870 auto parseOp = [&]() -> bool { 4871 StringRef Name; 4872 SMLoc Loc = getTok().getLoc(); 4873 if (parseIdentifier(Name)) 4874 return Error(Loc, "expected identifier"); 4875 MCSymbol *Sym = getContext().getOrCreateSymbol(Name); 4876 4877 // Assembler local symbols don't make any sense here. Complain loudly. 4878 if (Sym->isTemporary()) 4879 return Error(Loc, "non-local symbol required"); 4880 4881 if (!getStreamer().emitSymbolAttribute(Sym, Attr)) 4882 return Error(Loc, "unable to emit symbol attribute"); 4883 return false; 4884 }; 4885 4886 if (parseMany(parseOp)) 4887 return addErrorSuffix(" in directive"); 4888 return false; 4889 } 4890 4891 /// parseDirectiveComm 4892 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ] 4893 bool AsmParser::parseDirectiveComm(bool IsLocal) { 4894 if (checkForValidSection()) 4895 return true; 4896 4897 SMLoc IDLoc = getLexer().getLoc(); 4898 StringRef Name; 4899 if (parseIdentifier(Name)) 4900 return TokError("expected identifier in directive"); 4901 4902 // Handle the identifier as the key symbol. 4903 MCSymbol *Sym = getContext().getOrCreateSymbol(Name); 4904 4905 if (getLexer().isNot(AsmToken::Comma)) 4906 return TokError("unexpected token in directive"); 4907 Lex(); 4908 4909 int64_t Size; 4910 SMLoc SizeLoc = getLexer().getLoc(); 4911 if (parseAbsoluteExpression(Size)) 4912 return true; 4913 4914 int64_t Pow2Alignment = 0; 4915 SMLoc Pow2AlignmentLoc; 4916 if (getLexer().is(AsmToken::Comma)) { 4917 Lex(); 4918 Pow2AlignmentLoc = getLexer().getLoc(); 4919 if (parseAbsoluteExpression(Pow2Alignment)) 4920 return true; 4921 4922 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType(); 4923 if (IsLocal && LCOMM == LCOMM::NoAlignment) 4924 return Error(Pow2AlignmentLoc, "alignment not supported on this target"); 4925 4926 // If this target takes alignments in bytes (not log) validate and convert. 4927 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) || 4928 (IsLocal && LCOMM == LCOMM::ByteAlignment)) { 4929 if (!isPowerOf2_64(Pow2Alignment)) 4930 return Error(Pow2AlignmentLoc, "alignment must be a power of 2"); 4931 Pow2Alignment = Log2_64(Pow2Alignment); 4932 } 4933 } 4934 4935 if (parseToken(AsmToken::EndOfStatement, 4936 "unexpected token in '.comm' or '.lcomm' directive")) 4937 return true; 4938 4939 // NOTE: a size of zero for a .comm should create a undefined symbol 4940 // but a size of .lcomm creates a bss symbol of size zero. 4941 if (Size < 0) 4942 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't " 4943 "be less than zero"); 4944 4945 // NOTE: The alignment in the directive is a power of 2 value, the assembler 4946 // may internally end up wanting an alignment in bytes. 4947 // FIXME: Diagnose overflow. 4948 if (Pow2Alignment < 0) 4949 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive " 4950 "alignment, can't be less than zero"); 4951 4952 Sym->redefineIfPossible(); 4953 if (!Sym->isUndefined()) 4954 return Error(IDLoc, "invalid symbol redefinition"); 4955 4956 // Create the Symbol as a common or local common with Size and Pow2Alignment 4957 if (IsLocal) { 4958 getStreamer().emitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment); 4959 return false; 4960 } 4961 4962 getStreamer().emitCommonSymbol(Sym, Size, 1 << Pow2Alignment); 4963 return false; 4964 } 4965 4966 /// parseDirectiveAbort 4967 /// ::= .abort [... message ...] 4968 bool AsmParser::parseDirectiveAbort() { 4969 // FIXME: Use loc from directive. 4970 SMLoc Loc = getLexer().getLoc(); 4971 4972 StringRef Str = parseStringToEndOfStatement(); 4973 if (parseToken(AsmToken::EndOfStatement, 4974 "unexpected token in '.abort' directive")) 4975 return true; 4976 4977 if (Str.empty()) 4978 return Error(Loc, ".abort detected. Assembly stopping."); 4979 else 4980 return Error(Loc, ".abort '" + Str + "' detected. Assembly stopping."); 4981 // FIXME: Actually abort assembly here. 4982 4983 return false; 4984 } 4985 4986 /// parseDirectiveInclude 4987 /// ::= .include "filename" 4988 bool AsmParser::parseDirectiveInclude() { 4989 // Allow the strings to have escaped octal character sequence. 4990 std::string Filename; 4991 SMLoc IncludeLoc = getTok().getLoc(); 4992 4993 if (check(getTok().isNot(AsmToken::String), 4994 "expected string in '.include' directive") || 4995 parseEscapedString(Filename) || 4996 check(getTok().isNot(AsmToken::EndOfStatement), 4997 "unexpected token in '.include' directive") || 4998 // Attempt to switch the lexer to the included file before consuming the 4999 // end of statement to avoid losing it when we switch. 5000 check(enterIncludeFile(Filename), IncludeLoc, 5001 "Could not find include file '" + Filename + "'")) 5002 return true; 5003 5004 return false; 5005 } 5006 5007 /// parseDirectiveIncbin 5008 /// ::= .incbin "filename" [ , skip [ , count ] ] 5009 bool AsmParser::parseDirectiveIncbin() { 5010 // Allow the strings to have escaped octal character sequence. 5011 std::string Filename; 5012 SMLoc IncbinLoc = getTok().getLoc(); 5013 if (check(getTok().isNot(AsmToken::String), 5014 "expected string in '.incbin' directive") || 5015 parseEscapedString(Filename)) 5016 return true; 5017 5018 int64_t Skip = 0; 5019 const MCExpr *Count = nullptr; 5020 SMLoc SkipLoc, CountLoc; 5021 if (parseOptionalToken(AsmToken::Comma)) { 5022 // The skip expression can be omitted while specifying the count, e.g: 5023 // .incbin "filename",,4 5024 if (getTok().isNot(AsmToken::Comma)) { 5025 if (parseTokenLoc(SkipLoc) || parseAbsoluteExpression(Skip)) 5026 return true; 5027 } 5028 if (parseOptionalToken(AsmToken::Comma)) { 5029 CountLoc = getTok().getLoc(); 5030 if (parseExpression(Count)) 5031 return true; 5032 } 5033 } 5034 5035 if (parseToken(AsmToken::EndOfStatement, 5036 "unexpected token in '.incbin' directive")) 5037 return true; 5038 5039 if (check(Skip < 0, SkipLoc, "skip is negative")) 5040 return true; 5041 5042 // Attempt to process the included file. 5043 if (processIncbinFile(Filename, Skip, Count, CountLoc)) 5044 return Error(IncbinLoc, "Could not find incbin file '" + Filename + "'"); 5045 return false; 5046 } 5047 5048 /// parseDirectiveIf 5049 /// ::= .if{,eq,ge,gt,le,lt,ne} expression 5050 bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) { 5051 TheCondStack.push_back(TheCondState); 5052 TheCondState.TheCond = AsmCond::IfCond; 5053 if (TheCondState.Ignore) { 5054 eatToEndOfStatement(); 5055 } else { 5056 int64_t ExprValue; 5057 if (parseAbsoluteExpression(ExprValue) || 5058 parseToken(AsmToken::EndOfStatement, 5059 "unexpected token in '.if' directive")) 5060 return true; 5061 5062 switch (DirKind) { 5063 default: 5064 llvm_unreachable("unsupported directive"); 5065 case DK_IF: 5066 case DK_IFNE: 5067 break; 5068 case DK_IFEQ: 5069 ExprValue = ExprValue == 0; 5070 break; 5071 case DK_IFGE: 5072 ExprValue = ExprValue >= 0; 5073 break; 5074 case DK_IFGT: 5075 ExprValue = ExprValue > 0; 5076 break; 5077 case DK_IFLE: 5078 ExprValue = ExprValue <= 0; 5079 break; 5080 case DK_IFLT: 5081 ExprValue = ExprValue < 0; 5082 break; 5083 } 5084 5085 TheCondState.CondMet = ExprValue; 5086 TheCondState.Ignore = !TheCondState.CondMet; 5087 } 5088 5089 return false; 5090 } 5091 5092 /// parseDirectiveIfb 5093 /// ::= .ifb string 5094 bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) { 5095 TheCondStack.push_back(TheCondState); 5096 TheCondState.TheCond = AsmCond::IfCond; 5097 5098 if (TheCondState.Ignore) { 5099 eatToEndOfStatement(); 5100 } else { 5101 StringRef Str = parseStringToEndOfStatement(); 5102 5103 if (parseToken(AsmToken::EndOfStatement, 5104 "unexpected token in '.ifb' directive")) 5105 return true; 5106 5107 TheCondState.CondMet = ExpectBlank == Str.empty(); 5108 TheCondState.Ignore = !TheCondState.CondMet; 5109 } 5110 5111 return false; 5112 } 5113 5114 /// parseDirectiveIfc 5115 /// ::= .ifc string1, string2 5116 /// ::= .ifnc string1, string2 5117 bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) { 5118 TheCondStack.push_back(TheCondState); 5119 TheCondState.TheCond = AsmCond::IfCond; 5120 5121 if (TheCondState.Ignore) { 5122 eatToEndOfStatement(); 5123 } else { 5124 StringRef Str1 = parseStringToComma(); 5125 5126 if (parseToken(AsmToken::Comma, "unexpected token in '.ifc' directive")) 5127 return true; 5128 5129 StringRef Str2 = parseStringToEndOfStatement(); 5130 5131 if (parseToken(AsmToken::EndOfStatement, 5132 "unexpected token in '.ifc' directive")) 5133 return true; 5134 5135 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim()); 5136 TheCondState.Ignore = !TheCondState.CondMet; 5137 } 5138 5139 return false; 5140 } 5141 5142 /// parseDirectiveIfeqs 5143 /// ::= .ifeqs string1, string2 5144 bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) { 5145 if (Lexer.isNot(AsmToken::String)) { 5146 if (ExpectEqual) 5147 return TokError("expected string parameter for '.ifeqs' directive"); 5148 return TokError("expected string parameter for '.ifnes' directive"); 5149 } 5150 5151 StringRef String1 = getTok().getStringContents(); 5152 Lex(); 5153 5154 if (Lexer.isNot(AsmToken::Comma)) { 5155 if (ExpectEqual) 5156 return TokError( 5157 "expected comma after first string for '.ifeqs' directive"); 5158 return TokError("expected comma after first string for '.ifnes' directive"); 5159 } 5160 5161 Lex(); 5162 5163 if (Lexer.isNot(AsmToken::String)) { 5164 if (ExpectEqual) 5165 return TokError("expected string parameter for '.ifeqs' directive"); 5166 return TokError("expected string parameter for '.ifnes' directive"); 5167 } 5168 5169 StringRef String2 = getTok().getStringContents(); 5170 Lex(); 5171 5172 TheCondStack.push_back(TheCondState); 5173 TheCondState.TheCond = AsmCond::IfCond; 5174 TheCondState.CondMet = ExpectEqual == (String1 == String2); 5175 TheCondState.Ignore = !TheCondState.CondMet; 5176 5177 return false; 5178 } 5179 5180 /// parseDirectiveIfdef 5181 /// ::= .ifdef symbol 5182 bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) { 5183 StringRef Name; 5184 TheCondStack.push_back(TheCondState); 5185 TheCondState.TheCond = AsmCond::IfCond; 5186 5187 if (TheCondState.Ignore) { 5188 eatToEndOfStatement(); 5189 } else { 5190 if (check(parseIdentifier(Name), "expected identifier after '.ifdef'") || 5191 parseToken(AsmToken::EndOfStatement, "unexpected token in '.ifdef'")) 5192 return true; 5193 5194 MCSymbol *Sym = getContext().lookupSymbol(Name); 5195 5196 if (expect_defined) 5197 TheCondState.CondMet = (Sym && !Sym->isUndefined(false)); 5198 else 5199 TheCondState.CondMet = (!Sym || Sym->isUndefined(false)); 5200 TheCondState.Ignore = !TheCondState.CondMet; 5201 } 5202 5203 return false; 5204 } 5205 5206 /// parseDirectiveElseIf 5207 /// ::= .elseif expression 5208 bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) { 5209 if (TheCondState.TheCond != AsmCond::IfCond && 5210 TheCondState.TheCond != AsmCond::ElseIfCond) 5211 return Error(DirectiveLoc, "Encountered a .elseif that doesn't follow an" 5212 " .if or an .elseif"); 5213 TheCondState.TheCond = AsmCond::ElseIfCond; 5214 5215 bool LastIgnoreState = false; 5216 if (!TheCondStack.empty()) 5217 LastIgnoreState = TheCondStack.back().Ignore; 5218 if (LastIgnoreState || TheCondState.CondMet) { 5219 TheCondState.Ignore = true; 5220 eatToEndOfStatement(); 5221 } else { 5222 int64_t ExprValue; 5223 if (parseAbsoluteExpression(ExprValue)) 5224 return true; 5225 5226 if (parseToken(AsmToken::EndOfStatement, 5227 "unexpected token in '.elseif' directive")) 5228 return true; 5229 5230 TheCondState.CondMet = ExprValue; 5231 TheCondState.Ignore = !TheCondState.CondMet; 5232 } 5233 5234 return false; 5235 } 5236 5237 /// parseDirectiveElse 5238 /// ::= .else 5239 bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) { 5240 if (parseToken(AsmToken::EndOfStatement, 5241 "unexpected token in '.else' directive")) 5242 return true; 5243 5244 if (TheCondState.TheCond != AsmCond::IfCond && 5245 TheCondState.TheCond != AsmCond::ElseIfCond) 5246 return Error(DirectiveLoc, "Encountered a .else that doesn't follow " 5247 " an .if or an .elseif"); 5248 TheCondState.TheCond = AsmCond::ElseCond; 5249 bool LastIgnoreState = false; 5250 if (!TheCondStack.empty()) 5251 LastIgnoreState = TheCondStack.back().Ignore; 5252 if (LastIgnoreState || TheCondState.CondMet) 5253 TheCondState.Ignore = true; 5254 else 5255 TheCondState.Ignore = false; 5256 5257 return false; 5258 } 5259 5260 /// parseDirectiveEnd 5261 /// ::= .end 5262 bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) { 5263 if (parseToken(AsmToken::EndOfStatement, 5264 "unexpected token in '.end' directive")) 5265 return true; 5266 5267 while (Lexer.isNot(AsmToken::Eof)) 5268 Lexer.Lex(); 5269 5270 return false; 5271 } 5272 5273 /// parseDirectiveError 5274 /// ::= .err 5275 /// ::= .error [string] 5276 bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) { 5277 if (!TheCondStack.empty()) { 5278 if (TheCondStack.back().Ignore) { 5279 eatToEndOfStatement(); 5280 return false; 5281 } 5282 } 5283 5284 if (!WithMessage) 5285 return Error(L, ".err encountered"); 5286 5287 StringRef Message = ".error directive invoked in source file"; 5288 if (Lexer.isNot(AsmToken::EndOfStatement)) { 5289 if (Lexer.isNot(AsmToken::String)) 5290 return TokError(".error argument must be a string"); 5291 5292 Message = getTok().getStringContents(); 5293 Lex(); 5294 } 5295 5296 return Error(L, Message); 5297 } 5298 5299 /// parseDirectiveWarning 5300 /// ::= .warning [string] 5301 bool AsmParser::parseDirectiveWarning(SMLoc L) { 5302 if (!TheCondStack.empty()) { 5303 if (TheCondStack.back().Ignore) { 5304 eatToEndOfStatement(); 5305 return false; 5306 } 5307 } 5308 5309 StringRef Message = ".warning directive invoked in source file"; 5310 5311 if (!parseOptionalToken(AsmToken::EndOfStatement)) { 5312 if (Lexer.isNot(AsmToken::String)) 5313 return TokError(".warning argument must be a string"); 5314 5315 Message = getTok().getStringContents(); 5316 Lex(); 5317 if (parseToken(AsmToken::EndOfStatement, 5318 "expected end of statement in '.warning' directive")) 5319 return true; 5320 } 5321 5322 return Warning(L, Message); 5323 } 5324 5325 /// parseDirectiveEndIf 5326 /// ::= .endif 5327 bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) { 5328 if (parseToken(AsmToken::EndOfStatement, 5329 "unexpected token in '.endif' directive")) 5330 return true; 5331 5332 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty()) 5333 return Error(DirectiveLoc, "Encountered a .endif that doesn't follow " 5334 "an .if or .else"); 5335 if (!TheCondStack.empty()) { 5336 TheCondState = TheCondStack.back(); 5337 TheCondStack.pop_back(); 5338 } 5339 5340 return false; 5341 } 5342 5343 void AsmParser::initializeDirectiveKindMap() { 5344 /* Lookup will be done with the directive 5345 * converted to lower case, so all these 5346 * keys should be lower case. 5347 * (target specific directives are handled 5348 * elsewhere) 5349 */ 5350 DirectiveKindMap[".set"] = DK_SET; 5351 DirectiveKindMap[".equ"] = DK_EQU; 5352 DirectiveKindMap[".equiv"] = DK_EQUIV; 5353 DirectiveKindMap[".ascii"] = DK_ASCII; 5354 DirectiveKindMap[".asciz"] = DK_ASCIZ; 5355 DirectiveKindMap[".string"] = DK_STRING; 5356 DirectiveKindMap[".byte"] = DK_BYTE; 5357 DirectiveKindMap[".short"] = DK_SHORT; 5358 DirectiveKindMap[".value"] = DK_VALUE; 5359 DirectiveKindMap[".2byte"] = DK_2BYTE; 5360 DirectiveKindMap[".long"] = DK_LONG; 5361 DirectiveKindMap[".int"] = DK_INT; 5362 DirectiveKindMap[".4byte"] = DK_4BYTE; 5363 DirectiveKindMap[".quad"] = DK_QUAD; 5364 DirectiveKindMap[".8byte"] = DK_8BYTE; 5365 DirectiveKindMap[".octa"] = DK_OCTA; 5366 DirectiveKindMap[".single"] = DK_SINGLE; 5367 DirectiveKindMap[".float"] = DK_FLOAT; 5368 DirectiveKindMap[".double"] = DK_DOUBLE; 5369 DirectiveKindMap[".align"] = DK_ALIGN; 5370 DirectiveKindMap[".align32"] = DK_ALIGN32; 5371 DirectiveKindMap[".balign"] = DK_BALIGN; 5372 DirectiveKindMap[".balignw"] = DK_BALIGNW; 5373 DirectiveKindMap[".balignl"] = DK_BALIGNL; 5374 DirectiveKindMap[".p2align"] = DK_P2ALIGN; 5375 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW; 5376 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL; 5377 DirectiveKindMap[".org"] = DK_ORG; 5378 DirectiveKindMap[".fill"] = DK_FILL; 5379 DirectiveKindMap[".zero"] = DK_ZERO; 5380 DirectiveKindMap[".extern"] = DK_EXTERN; 5381 DirectiveKindMap[".globl"] = DK_GLOBL; 5382 DirectiveKindMap[".global"] = DK_GLOBAL; 5383 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE; 5384 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP; 5385 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER; 5386 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN; 5387 DirectiveKindMap[".reference"] = DK_REFERENCE; 5388 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION; 5389 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE; 5390 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN; 5391 DirectiveKindMap[".cold"] = DK_COLD; 5392 DirectiveKindMap[".comm"] = DK_COMM; 5393 DirectiveKindMap[".common"] = DK_COMMON; 5394 DirectiveKindMap[".lcomm"] = DK_LCOMM; 5395 DirectiveKindMap[".abort"] = DK_ABORT; 5396 DirectiveKindMap[".include"] = DK_INCLUDE; 5397 DirectiveKindMap[".incbin"] = DK_INCBIN; 5398 DirectiveKindMap[".code16"] = DK_CODE16; 5399 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC; 5400 DirectiveKindMap[".rept"] = DK_REPT; 5401 DirectiveKindMap[".rep"] = DK_REPT; 5402 DirectiveKindMap[".irp"] = DK_IRP; 5403 DirectiveKindMap[".irpc"] = DK_IRPC; 5404 DirectiveKindMap[".endr"] = DK_ENDR; 5405 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE; 5406 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK; 5407 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK; 5408 DirectiveKindMap[".if"] = DK_IF; 5409 DirectiveKindMap[".ifeq"] = DK_IFEQ; 5410 DirectiveKindMap[".ifge"] = DK_IFGE; 5411 DirectiveKindMap[".ifgt"] = DK_IFGT; 5412 DirectiveKindMap[".ifle"] = DK_IFLE; 5413 DirectiveKindMap[".iflt"] = DK_IFLT; 5414 DirectiveKindMap[".ifne"] = DK_IFNE; 5415 DirectiveKindMap[".ifb"] = DK_IFB; 5416 DirectiveKindMap[".ifnb"] = DK_IFNB; 5417 DirectiveKindMap[".ifc"] = DK_IFC; 5418 DirectiveKindMap[".ifeqs"] = DK_IFEQS; 5419 DirectiveKindMap[".ifnc"] = DK_IFNC; 5420 DirectiveKindMap[".ifnes"] = DK_IFNES; 5421 DirectiveKindMap[".ifdef"] = DK_IFDEF; 5422 DirectiveKindMap[".ifndef"] = DK_IFNDEF; 5423 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF; 5424 DirectiveKindMap[".elseif"] = DK_ELSEIF; 5425 DirectiveKindMap[".else"] = DK_ELSE; 5426 DirectiveKindMap[".end"] = DK_END; 5427 DirectiveKindMap[".endif"] = DK_ENDIF; 5428 DirectiveKindMap[".skip"] = DK_SKIP; 5429 DirectiveKindMap[".space"] = DK_SPACE; 5430 DirectiveKindMap[".file"] = DK_FILE; 5431 DirectiveKindMap[".line"] = DK_LINE; 5432 DirectiveKindMap[".loc"] = DK_LOC; 5433 DirectiveKindMap[".stabs"] = DK_STABS; 5434 DirectiveKindMap[".cv_file"] = DK_CV_FILE; 5435 DirectiveKindMap[".cv_func_id"] = DK_CV_FUNC_ID; 5436 DirectiveKindMap[".cv_loc"] = DK_CV_LOC; 5437 DirectiveKindMap[".cv_linetable"] = DK_CV_LINETABLE; 5438 DirectiveKindMap[".cv_inline_linetable"] = DK_CV_INLINE_LINETABLE; 5439 DirectiveKindMap[".cv_inline_site_id"] = DK_CV_INLINE_SITE_ID; 5440 DirectiveKindMap[".cv_def_range"] = DK_CV_DEF_RANGE; 5441 DirectiveKindMap[".cv_string"] = DK_CV_STRING; 5442 DirectiveKindMap[".cv_stringtable"] = DK_CV_STRINGTABLE; 5443 DirectiveKindMap[".cv_filechecksums"] = DK_CV_FILECHECKSUMS; 5444 DirectiveKindMap[".cv_filechecksumoffset"] = DK_CV_FILECHECKSUM_OFFSET; 5445 DirectiveKindMap[".cv_fpo_data"] = DK_CV_FPO_DATA; 5446 DirectiveKindMap[".sleb128"] = DK_SLEB128; 5447 DirectiveKindMap[".uleb128"] = DK_ULEB128; 5448 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS; 5449 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC; 5450 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC; 5451 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA; 5452 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET; 5453 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET; 5454 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER; 5455 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET; 5456 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET; 5457 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY; 5458 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA; 5459 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE; 5460 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE; 5461 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE; 5462 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE; 5463 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE; 5464 DirectiveKindMap[".cfi_return_column"] = DK_CFI_RETURN_COLUMN; 5465 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME; 5466 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED; 5467 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER; 5468 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE; 5469 DirectiveKindMap[".cfi_b_key_frame"] = DK_CFI_B_KEY_FRAME; 5470 DirectiveKindMap[".macros_on"] = DK_MACROS_ON; 5471 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF; 5472 DirectiveKindMap[".macro"] = DK_MACRO; 5473 DirectiveKindMap[".exitm"] = DK_EXITM; 5474 DirectiveKindMap[".endm"] = DK_ENDM; 5475 DirectiveKindMap[".endmacro"] = DK_ENDMACRO; 5476 DirectiveKindMap[".purgem"] = DK_PURGEM; 5477 DirectiveKindMap[".err"] = DK_ERR; 5478 DirectiveKindMap[".error"] = DK_ERROR; 5479 DirectiveKindMap[".warning"] = DK_WARNING; 5480 DirectiveKindMap[".altmacro"] = DK_ALTMACRO; 5481 DirectiveKindMap[".noaltmacro"] = DK_NOALTMACRO; 5482 DirectiveKindMap[".reloc"] = DK_RELOC; 5483 DirectiveKindMap[".dc"] = DK_DC; 5484 DirectiveKindMap[".dc.a"] = DK_DC_A; 5485 DirectiveKindMap[".dc.b"] = DK_DC_B; 5486 DirectiveKindMap[".dc.d"] = DK_DC_D; 5487 DirectiveKindMap[".dc.l"] = DK_DC_L; 5488 DirectiveKindMap[".dc.s"] = DK_DC_S; 5489 DirectiveKindMap[".dc.w"] = DK_DC_W; 5490 DirectiveKindMap[".dc.x"] = DK_DC_X; 5491 DirectiveKindMap[".dcb"] = DK_DCB; 5492 DirectiveKindMap[".dcb.b"] = DK_DCB_B; 5493 DirectiveKindMap[".dcb.d"] = DK_DCB_D; 5494 DirectiveKindMap[".dcb.l"] = DK_DCB_L; 5495 DirectiveKindMap[".dcb.s"] = DK_DCB_S; 5496 DirectiveKindMap[".dcb.w"] = DK_DCB_W; 5497 DirectiveKindMap[".dcb.x"] = DK_DCB_X; 5498 DirectiveKindMap[".ds"] = DK_DS; 5499 DirectiveKindMap[".ds.b"] = DK_DS_B; 5500 DirectiveKindMap[".ds.d"] = DK_DS_D; 5501 DirectiveKindMap[".ds.l"] = DK_DS_L; 5502 DirectiveKindMap[".ds.p"] = DK_DS_P; 5503 DirectiveKindMap[".ds.s"] = DK_DS_S; 5504 DirectiveKindMap[".ds.w"] = DK_DS_W; 5505 DirectiveKindMap[".ds.x"] = DK_DS_X; 5506 DirectiveKindMap[".print"] = DK_PRINT; 5507 DirectiveKindMap[".addrsig"] = DK_ADDRSIG; 5508 DirectiveKindMap[".addrsig_sym"] = DK_ADDRSIG_SYM; 5509 } 5510 5511 MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) { 5512 AsmToken EndToken, StartToken = getTok(); 5513 5514 unsigned NestLevel = 0; 5515 while (true) { 5516 // Check whether we have reached the end of the file. 5517 if (getLexer().is(AsmToken::Eof)) { 5518 printError(DirectiveLoc, "no matching '.endr' in definition"); 5519 return nullptr; 5520 } 5521 5522 if (Lexer.is(AsmToken::Identifier) && 5523 (getTok().getIdentifier() == ".rep" || 5524 getTok().getIdentifier() == ".rept" || 5525 getTok().getIdentifier() == ".irp" || 5526 getTok().getIdentifier() == ".irpc")) { 5527 ++NestLevel; 5528 } 5529 5530 // Otherwise, check whether we have reached the .endr. 5531 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") { 5532 if (NestLevel == 0) { 5533 EndToken = getTok(); 5534 Lex(); 5535 if (Lexer.isNot(AsmToken::EndOfStatement)) { 5536 printError(getTok().getLoc(), 5537 "unexpected token in '.endr' directive"); 5538 return nullptr; 5539 } 5540 break; 5541 } 5542 --NestLevel; 5543 } 5544 5545 // Otherwise, scan till the end of the statement. 5546 eatToEndOfStatement(); 5547 } 5548 5549 const char *BodyStart = StartToken.getLoc().getPointer(); 5550 const char *BodyEnd = EndToken.getLoc().getPointer(); 5551 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart); 5552 5553 // We Are Anonymous. 5554 MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters()); 5555 return &MacroLikeBodies.back(); 5556 } 5557 5558 void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc, 5559 raw_svector_ostream &OS) { 5560 OS << ".endr\n"; 5561 5562 std::unique_ptr<MemoryBuffer> Instantiation = 5563 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>"); 5564 5565 // Create the macro instantiation object and add to the current macro 5566 // instantiation stack. 5567 MacroInstantiation *MI = new MacroInstantiation{ 5568 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size()}; 5569 ActiveMacros.push_back(MI); 5570 5571 // Jump to the macro instantiation and prime the lexer. 5572 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc()); 5573 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer()); 5574 Lex(); 5575 } 5576 5577 /// parseDirectiveRept 5578 /// ::= .rep | .rept count 5579 bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) { 5580 const MCExpr *CountExpr; 5581 SMLoc CountLoc = getTok().getLoc(); 5582 if (parseExpression(CountExpr)) 5583 return true; 5584 5585 int64_t Count; 5586 if (!CountExpr->evaluateAsAbsolute(Count, getStreamer().getAssemblerPtr())) { 5587 return Error(CountLoc, "unexpected token in '" + Dir + "' directive"); 5588 } 5589 5590 if (check(Count < 0, CountLoc, "Count is negative") || 5591 parseToken(AsmToken::EndOfStatement, 5592 "unexpected token in '" + Dir + "' directive")) 5593 return true; 5594 5595 // Lex the rept definition. 5596 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc); 5597 if (!M) 5598 return true; 5599 5600 // Macro instantiation is lexical, unfortunately. We construct a new buffer 5601 // to hold the macro body with substitutions. 5602 SmallString<256> Buf; 5603 raw_svector_ostream OS(Buf); 5604 while (Count--) { 5605 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t). 5606 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc())) 5607 return true; 5608 } 5609 instantiateMacroLikeBody(M, DirectiveLoc, OS); 5610 5611 return false; 5612 } 5613 5614 /// parseDirectiveIrp 5615 /// ::= .irp symbol,values 5616 bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) { 5617 MCAsmMacroParameter Parameter; 5618 MCAsmMacroArguments A; 5619 if (check(parseIdentifier(Parameter.Name), 5620 "expected identifier in '.irp' directive") || 5621 parseToken(AsmToken::Comma, "expected comma in '.irp' directive") || 5622 parseMacroArguments(nullptr, A) || 5623 parseToken(AsmToken::EndOfStatement, "expected End of Statement")) 5624 return true; 5625 5626 // Lex the irp definition. 5627 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc); 5628 if (!M) 5629 return true; 5630 5631 // Macro instantiation is lexical, unfortunately. We construct a new buffer 5632 // to hold the macro body with substitutions. 5633 SmallString<256> Buf; 5634 raw_svector_ostream OS(Buf); 5635 5636 for (const MCAsmMacroArgument &Arg : A) { 5637 // Note that the AtPseudoVariable is enabled for instantiations of .irp. 5638 // This is undocumented, but GAS seems to support it. 5639 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc())) 5640 return true; 5641 } 5642 5643 instantiateMacroLikeBody(M, DirectiveLoc, OS); 5644 5645 return false; 5646 } 5647 5648 /// parseDirectiveIrpc 5649 /// ::= .irpc symbol,values 5650 bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) { 5651 MCAsmMacroParameter Parameter; 5652 MCAsmMacroArguments A; 5653 5654 if (check(parseIdentifier(Parameter.Name), 5655 "expected identifier in '.irpc' directive") || 5656 parseToken(AsmToken::Comma, "expected comma in '.irpc' directive") || 5657 parseMacroArguments(nullptr, A)) 5658 return true; 5659 5660 if (A.size() != 1 || A.front().size() != 1) 5661 return TokError("unexpected token in '.irpc' directive"); 5662 5663 // Eat the end of statement. 5664 if (parseToken(AsmToken::EndOfStatement, "expected end of statement")) 5665 return true; 5666 5667 // Lex the irpc definition. 5668 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc); 5669 if (!M) 5670 return true; 5671 5672 // Macro instantiation is lexical, unfortunately. We construct a new buffer 5673 // to hold the macro body with substitutions. 5674 SmallString<256> Buf; 5675 raw_svector_ostream OS(Buf); 5676 5677 StringRef Values = A.front().front().getString(); 5678 for (std::size_t I = 0, End = Values.size(); I != End; ++I) { 5679 MCAsmMacroArgument Arg; 5680 Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1)); 5681 5682 // Note that the AtPseudoVariable is enabled for instantiations of .irpc. 5683 // This is undocumented, but GAS seems to support it. 5684 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc())) 5685 return true; 5686 } 5687 5688 instantiateMacroLikeBody(M, DirectiveLoc, OS); 5689 5690 return false; 5691 } 5692 5693 bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) { 5694 if (ActiveMacros.empty()) 5695 return TokError("unmatched '.endr' directive"); 5696 5697 // The only .repl that should get here are the ones created by 5698 // instantiateMacroLikeBody. 5699 assert(getLexer().is(AsmToken::EndOfStatement)); 5700 5701 handleMacroExit(); 5702 return false; 5703 } 5704 5705 bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info, 5706 size_t Len) { 5707 const MCExpr *Value; 5708 SMLoc ExprLoc = getLexer().getLoc(); 5709 if (parseExpression(Value)) 5710 return true; 5711 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value); 5712 if (!MCE) 5713 return Error(ExprLoc, "unexpected expression in _emit"); 5714 uint64_t IntValue = MCE->getValue(); 5715 if (!isUInt<8>(IntValue) && !isInt<8>(IntValue)) 5716 return Error(ExprLoc, "literal value out of range for directive"); 5717 5718 Info.AsmRewrites->emplace_back(AOK_Emit, IDLoc, Len); 5719 return false; 5720 } 5721 5722 bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) { 5723 const MCExpr *Value; 5724 SMLoc ExprLoc = getLexer().getLoc(); 5725 if (parseExpression(Value)) 5726 return true; 5727 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value); 5728 if (!MCE) 5729 return Error(ExprLoc, "unexpected expression in align"); 5730 uint64_t IntValue = MCE->getValue(); 5731 if (!isPowerOf2_64(IntValue)) 5732 return Error(ExprLoc, "literal value not a power of two greater then zero"); 5733 5734 Info.AsmRewrites->emplace_back(AOK_Align, IDLoc, 5, Log2_64(IntValue)); 5735 return false; 5736 } 5737 5738 bool AsmParser::parseDirectivePrint(SMLoc DirectiveLoc) { 5739 const AsmToken StrTok = getTok(); 5740 Lex(); 5741 if (StrTok.isNot(AsmToken::String) || StrTok.getString().front() != '"') 5742 return Error(DirectiveLoc, "expected double quoted string after .print"); 5743 if (parseToken(AsmToken::EndOfStatement, "expected end of statement")) 5744 return true; 5745 llvm::outs() << StrTok.getStringContents() << '\n'; 5746 return false; 5747 } 5748 5749 bool AsmParser::parseDirectiveAddrsig() { 5750 getStreamer().emitAddrsig(); 5751 return false; 5752 } 5753 5754 bool AsmParser::parseDirectiveAddrsigSym() { 5755 StringRef Name; 5756 if (check(parseIdentifier(Name), 5757 "expected identifier in '.addrsig_sym' directive")) 5758 return true; 5759 MCSymbol *Sym = getContext().getOrCreateSymbol(Name); 5760 getStreamer().emitAddrsigSym(Sym); 5761 return false; 5762 } 5763 5764 // We are comparing pointers, but the pointers are relative to a single string. 5765 // Thus, this should always be deterministic. 5766 static int rewritesSort(const AsmRewrite *AsmRewriteA, 5767 const AsmRewrite *AsmRewriteB) { 5768 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer()) 5769 return -1; 5770 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer()) 5771 return 1; 5772 5773 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output 5774 // rewrite to the same location. Make sure the SizeDirective rewrite is 5775 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This 5776 // ensures the sort algorithm is stable. 5777 if (AsmRewritePrecedence[AsmRewriteA->Kind] > 5778 AsmRewritePrecedence[AsmRewriteB->Kind]) 5779 return -1; 5780 5781 if (AsmRewritePrecedence[AsmRewriteA->Kind] < 5782 AsmRewritePrecedence[AsmRewriteB->Kind]) 5783 return 1; 5784 llvm_unreachable("Unstable rewrite sort."); 5785 } 5786 5787 bool AsmParser::parseMSInlineAsm( 5788 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs, 5789 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool>> &OpDecls, 5790 SmallVectorImpl<std::string> &Constraints, 5791 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII, 5792 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) { 5793 SmallVector<void *, 4> InputDecls; 5794 SmallVector<void *, 4> OutputDecls; 5795 SmallVector<bool, 4> InputDeclsAddressOf; 5796 SmallVector<bool, 4> OutputDeclsAddressOf; 5797 SmallVector<std::string, 4> InputConstraints; 5798 SmallVector<std::string, 4> OutputConstraints; 5799 SmallVector<unsigned, 4> ClobberRegs; 5800 5801 SmallVector<AsmRewrite, 4> AsmStrRewrites; 5802 5803 // Prime the lexer. 5804 Lex(); 5805 5806 // While we have input, parse each statement. 5807 unsigned InputIdx = 0; 5808 unsigned OutputIdx = 0; 5809 while (getLexer().isNot(AsmToken::Eof)) { 5810 // Parse curly braces marking block start/end 5811 if (parseCurlyBlockScope(AsmStrRewrites)) 5812 continue; 5813 5814 ParseStatementInfo Info(&AsmStrRewrites); 5815 bool StatementErr = parseStatement(Info, &SI); 5816 5817 if (StatementErr || Info.ParseError) { 5818 // Emit pending errors if any exist. 5819 printPendingErrors(); 5820 return true; 5821 } 5822 5823 // No pending error should exist here. 5824 assert(!hasPendingError() && "unexpected error from parseStatement"); 5825 5826 if (Info.Opcode == ~0U) 5827 continue; 5828 5829 const MCInstrDesc &Desc = MII->get(Info.Opcode); 5830 5831 // Build the list of clobbers, outputs and inputs. 5832 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) { 5833 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i]; 5834 5835 // Register operand. 5836 if (Operand.isReg() && !Operand.needAddressOf() && 5837 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) { 5838 unsigned NumDefs = Desc.getNumDefs(); 5839 // Clobber. 5840 if (NumDefs && Operand.getMCOperandNum() < NumDefs) 5841 ClobberRegs.push_back(Operand.getReg()); 5842 continue; 5843 } 5844 5845 // Expr/Input or Output. 5846 StringRef SymName = Operand.getSymName(); 5847 if (SymName.empty()) 5848 continue; 5849 5850 void *OpDecl = Operand.getOpDecl(); 5851 if (!OpDecl) 5852 continue; 5853 5854 StringRef Constraint = Operand.getConstraint(); 5855 if (Operand.isImm()) { 5856 // Offset as immediate 5857 if (Operand.isOffsetOfLocal()) 5858 Constraint = "r"; 5859 else 5860 Constraint = "i"; 5861 } 5862 5863 bool isOutput = (i == 1) && Desc.mayStore(); 5864 SMLoc Start = SMLoc::getFromPointer(SymName.data()); 5865 if (isOutput) { 5866 ++InputIdx; 5867 OutputDecls.push_back(OpDecl); 5868 OutputDeclsAddressOf.push_back(Operand.needAddressOf()); 5869 OutputConstraints.push_back(("=" + Constraint).str()); 5870 AsmStrRewrites.emplace_back(AOK_Output, Start, SymName.size()); 5871 } else { 5872 InputDecls.push_back(OpDecl); 5873 InputDeclsAddressOf.push_back(Operand.needAddressOf()); 5874 InputConstraints.push_back(Constraint.str()); 5875 if (Desc.OpInfo[i - 1].isBranchTarget()) 5876 AsmStrRewrites.emplace_back(AOK_CallInput, Start, SymName.size()); 5877 else 5878 AsmStrRewrites.emplace_back(AOK_Input, Start, SymName.size()); 5879 } 5880 } 5881 5882 // Consider implicit defs to be clobbers. Think of cpuid and push. 5883 ArrayRef<MCPhysReg> ImpDefs(Desc.getImplicitDefs(), 5884 Desc.getNumImplicitDefs()); 5885 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end()); 5886 } 5887 5888 // Set the number of Outputs and Inputs. 5889 NumOutputs = OutputDecls.size(); 5890 NumInputs = InputDecls.size(); 5891 5892 // Set the unique clobbers. 5893 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end()); 5894 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()), 5895 ClobberRegs.end()); 5896 Clobbers.assign(ClobberRegs.size(), std::string()); 5897 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) { 5898 raw_string_ostream OS(Clobbers[I]); 5899 IP->printRegName(OS, ClobberRegs[I]); 5900 } 5901 5902 // Merge the various outputs and inputs. Output are expected first. 5903 if (NumOutputs || NumInputs) { 5904 unsigned NumExprs = NumOutputs + NumInputs; 5905 OpDecls.resize(NumExprs); 5906 Constraints.resize(NumExprs); 5907 for (unsigned i = 0; i < NumOutputs; ++i) { 5908 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]); 5909 Constraints[i] = OutputConstraints[i]; 5910 } 5911 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) { 5912 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]); 5913 Constraints[j] = InputConstraints[i]; 5914 } 5915 } 5916 5917 // Build the IR assembly string. 5918 std::string AsmStringIR; 5919 raw_string_ostream OS(AsmStringIR); 5920 StringRef ASMString = 5921 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer(); 5922 const char *AsmStart = ASMString.begin(); 5923 const char *AsmEnd = ASMString.end(); 5924 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort); 5925 for (auto it = AsmStrRewrites.begin(); it != AsmStrRewrites.end(); ++it) { 5926 const AsmRewrite &AR = *it; 5927 // Check if this has already been covered by another rewrite... 5928 if (AR.Done) 5929 continue; 5930 AsmRewriteKind Kind = AR.Kind; 5931 5932 const char *Loc = AR.Loc.getPointer(); 5933 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!"); 5934 5935 // Emit everything up to the immediate/expression. 5936 if (unsigned Len = Loc - AsmStart) 5937 OS << StringRef(AsmStart, Len); 5938 5939 // Skip the original expression. 5940 if (Kind == AOK_Skip) { 5941 AsmStart = Loc + AR.Len; 5942 continue; 5943 } 5944 5945 unsigned AdditionalSkip = 0; 5946 // Rewrite expressions in $N notation. 5947 switch (Kind) { 5948 default: 5949 break; 5950 case AOK_IntelExpr: 5951 assert(AR.IntelExp.isValid() && "cannot write invalid intel expression"); 5952 if (AR.IntelExp.NeedBracs) 5953 OS << "["; 5954 if (AR.IntelExp.hasBaseReg()) 5955 OS << AR.IntelExp.BaseReg; 5956 if (AR.IntelExp.hasIndexReg()) 5957 OS << (AR.IntelExp.hasBaseReg() ? " + " : "") 5958 << AR.IntelExp.IndexReg; 5959 if (AR.IntelExp.Scale > 1) 5960 OS << " * $$" << AR.IntelExp.Scale; 5961 if (AR.IntelExp.hasOffset()) { 5962 if (AR.IntelExp.hasRegs()) 5963 OS << " + "; 5964 // Fuse this rewrite with a rewrite of the offset name, if present. 5965 StringRef OffsetName = AR.IntelExp.OffsetName; 5966 SMLoc OffsetLoc = SMLoc::getFromPointer(AR.IntelExp.OffsetName.data()); 5967 size_t OffsetLen = OffsetName.size(); 5968 auto rewrite_it = std::find_if( 5969 it, AsmStrRewrites.end(), [&](const AsmRewrite &FusingAR) { 5970 return FusingAR.Loc == OffsetLoc && FusingAR.Len == OffsetLen && 5971 (FusingAR.Kind == AOK_Input || 5972 FusingAR.Kind == AOK_CallInput); 5973 }); 5974 if (rewrite_it == AsmStrRewrites.end()) { 5975 OS << "offset " << OffsetName; 5976 } else if (rewrite_it->Kind == AOK_CallInput) { 5977 OS << "${" << InputIdx++ << ":P}"; 5978 rewrite_it->Done = true; 5979 } else { 5980 OS << '$' << InputIdx++; 5981 rewrite_it->Done = true; 5982 } 5983 } 5984 if (AR.IntelExp.Imm || AR.IntelExp.emitImm()) 5985 OS << (AR.IntelExp.emitImm() ? "$$" : " + $$") << AR.IntelExp.Imm; 5986 if (AR.IntelExp.NeedBracs) 5987 OS << "]"; 5988 break; 5989 case AOK_Label: 5990 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label; 5991 break; 5992 case AOK_Input: 5993 OS << '$' << InputIdx++; 5994 break; 5995 case AOK_CallInput: 5996 OS << "${" << InputIdx++ << ":P}"; 5997 break; 5998 case AOK_Output: 5999 OS << '$' << OutputIdx++; 6000 break; 6001 case AOK_SizeDirective: 6002 switch (AR.Val) { 6003 default: break; 6004 case 8: OS << "byte ptr "; break; 6005 case 16: OS << "word ptr "; break; 6006 case 32: OS << "dword ptr "; break; 6007 case 64: OS << "qword ptr "; break; 6008 case 80: OS << "xword ptr "; break; 6009 case 128: OS << "xmmword ptr "; break; 6010 case 256: OS << "ymmword ptr "; break; 6011 } 6012 break; 6013 case AOK_Emit: 6014 OS << ".byte"; 6015 break; 6016 case AOK_Align: { 6017 // MS alignment directives are measured in bytes. If the native assembler 6018 // measures alignment in bytes, we can pass it straight through. 6019 OS << ".align"; 6020 if (getContext().getAsmInfo()->getAlignmentIsInBytes()) 6021 break; 6022 6023 // Alignment is in log2 form, so print that instead and skip the original 6024 // immediate. 6025 unsigned Val = AR.Val; 6026 OS << ' ' << Val; 6027 assert(Val < 10 && "Expected alignment less then 2^10."); 6028 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4; 6029 break; 6030 } 6031 case AOK_EVEN: 6032 OS << ".even"; 6033 break; 6034 case AOK_EndOfStatement: 6035 OS << "\n\t"; 6036 break; 6037 } 6038 6039 // Skip the original expression. 6040 AsmStart = Loc + AR.Len + AdditionalSkip; 6041 } 6042 6043 // Emit the remainder of the asm string. 6044 if (AsmStart != AsmEnd) 6045 OS << StringRef(AsmStart, AsmEnd - AsmStart); 6046 6047 AsmString = OS.str(); 6048 return false; 6049 } 6050 6051 namespace llvm { 6052 namespace MCParserUtils { 6053 6054 /// Returns whether the given symbol is used anywhere in the given expression, 6055 /// or subexpressions. 6056 static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) { 6057 switch (Value->getKind()) { 6058 case MCExpr::Binary: { 6059 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value); 6060 return isSymbolUsedInExpression(Sym, BE->getLHS()) || 6061 isSymbolUsedInExpression(Sym, BE->getRHS()); 6062 } 6063 case MCExpr::Target: 6064 case MCExpr::Constant: 6065 return false; 6066 case MCExpr::SymbolRef: { 6067 const MCSymbol &S = 6068 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol(); 6069 if (S.isVariable()) 6070 return isSymbolUsedInExpression(Sym, S.getVariableValue()); 6071 return &S == Sym; 6072 } 6073 case MCExpr::Unary: 6074 return isSymbolUsedInExpression( 6075 Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr()); 6076 } 6077 6078 llvm_unreachable("Unknown expr kind!"); 6079 } 6080 6081 bool parseAssignmentExpression(StringRef Name, bool allow_redef, 6082 MCAsmParser &Parser, MCSymbol *&Sym, 6083 const MCExpr *&Value) { 6084 6085 // FIXME: Use better location, we should use proper tokens. 6086 SMLoc EqualLoc = Parser.getTok().getLoc(); 6087 if (Parser.parseExpression(Value)) 6088 return Parser.TokError("missing expression"); 6089 6090 // Note: we don't count b as used in "a = b". This is to allow 6091 // a = b 6092 // b = c 6093 6094 if (Parser.parseToken(AsmToken::EndOfStatement)) 6095 return true; 6096 6097 // Validate that the LHS is allowed to be a variable (either it has not been 6098 // used as a symbol, or it is an absolute symbol). 6099 Sym = Parser.getContext().lookupSymbol(Name); 6100 if (Sym) { 6101 // Diagnose assignment to a label. 6102 // 6103 // FIXME: Diagnostics. Note the location of the definition as a label. 6104 // FIXME: Diagnose assignment to protected identifier (e.g., register name). 6105 if (isSymbolUsedInExpression(Sym, Value)) 6106 return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'"); 6107 else if (Sym->isUndefined(/*SetUsed*/ false) && !Sym->isUsed() && 6108 !Sym->isVariable()) 6109 ; // Allow redefinitions of undefined symbols only used in directives. 6110 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef) 6111 ; // Allow redefinitions of variables that haven't yet been used. 6112 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef)) 6113 return Parser.Error(EqualLoc, "redefinition of '" + Name + "'"); 6114 else if (!Sym->isVariable()) 6115 return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'"); 6116 else if (!isa<MCConstantExpr>(Sym->getVariableValue())) 6117 return Parser.Error(EqualLoc, 6118 "invalid reassignment of non-absolute variable '" + 6119 Name + "'"); 6120 } else if (Name == ".") { 6121 Parser.getStreamer().emitValueToOffset(Value, 0, EqualLoc); 6122 return false; 6123 } else 6124 Sym = Parser.getContext().getOrCreateSymbol(Name); 6125 6126 Sym->setRedefinable(allow_redef); 6127 6128 return false; 6129 } 6130 6131 } // end namespace MCParserUtils 6132 } // end namespace llvm 6133 6134 /// Create an MCAsmParser instance. 6135 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C, 6136 MCStreamer &Out, const MCAsmInfo &MAI, 6137 unsigned CB) { 6138 return new AsmParser(SM, C, Out, MAI, CB); 6139 } 6140