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