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