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 (parseEOL()) 3063 return true; 3064 3065 const MCTargetAsmParser &MCT = getTargetParser(); 3066 const MCSubtargetInfo &STI = MCT.getSTI(); 3067 if (Optional<std::pair<bool, std::string>> Err = 3068 getStreamer().emitRelocDirective(*Offset, Name, Expr, DirectiveLoc, 3069 STI)) 3070 return Error(Err->first ? NameLoc : OffsetLoc, Err->second); 3071 3072 return false; 3073 } 3074 3075 /// parseDirectiveValue 3076 /// ::= (.byte | .short | ... ) [ expression (, expression)* ] 3077 bool AsmParser::parseDirectiveValue(StringRef IDVal, unsigned Size) { 3078 auto parseOp = [&]() -> bool { 3079 const MCExpr *Value; 3080 SMLoc ExprLoc = getLexer().getLoc(); 3081 if (checkForValidSection() || parseExpression(Value)) 3082 return true; 3083 // Special case constant expressions to match code generator. 3084 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) { 3085 assert(Size <= 8 && "Invalid size"); 3086 uint64_t IntValue = MCE->getValue(); 3087 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue)) 3088 return Error(ExprLoc, "out of range literal value"); 3089 getStreamer().emitIntValue(IntValue, Size); 3090 } else 3091 getStreamer().emitValue(Value, Size, ExprLoc); 3092 return false; 3093 }; 3094 3095 if (parseMany(parseOp)) 3096 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive"); 3097 return false; 3098 } 3099 3100 static bool parseHexOcta(AsmParser &Asm, uint64_t &hi, uint64_t &lo) { 3101 if (Asm.getTok().isNot(AsmToken::Integer) && 3102 Asm.getTok().isNot(AsmToken::BigNum)) 3103 return Asm.TokError("unknown token in expression"); 3104 SMLoc ExprLoc = Asm.getTok().getLoc(); 3105 APInt IntValue = Asm.getTok().getAPIntVal(); 3106 Asm.Lex(); 3107 if (!IntValue.isIntN(128)) 3108 return Asm.Error(ExprLoc, "out of range literal value"); 3109 if (!IntValue.isIntN(64)) { 3110 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue(); 3111 lo = IntValue.getLoBits(64).getZExtValue(); 3112 } else { 3113 hi = 0; 3114 lo = IntValue.getZExtValue(); 3115 } 3116 return false; 3117 } 3118 3119 /// ParseDirectiveOctaValue 3120 /// ::= .octa [ hexconstant (, hexconstant)* ] 3121 3122 bool AsmParser::parseDirectiveOctaValue(StringRef IDVal) { 3123 auto parseOp = [&]() -> bool { 3124 if (checkForValidSection()) 3125 return true; 3126 uint64_t hi, lo; 3127 if (parseHexOcta(*this, hi, lo)) 3128 return true; 3129 if (MAI.isLittleEndian()) { 3130 getStreamer().emitInt64(lo); 3131 getStreamer().emitInt64(hi); 3132 } else { 3133 getStreamer().emitInt64(hi); 3134 getStreamer().emitInt64(lo); 3135 } 3136 return false; 3137 }; 3138 3139 if (parseMany(parseOp)) 3140 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive"); 3141 return false; 3142 } 3143 3144 bool AsmParser::parseRealValue(const fltSemantics &Semantics, APInt &Res) { 3145 // We don't truly support arithmetic on floating point expressions, so we 3146 // have to manually parse unary prefixes. 3147 bool IsNeg = false; 3148 if (getLexer().is(AsmToken::Minus)) { 3149 Lexer.Lex(); 3150 IsNeg = true; 3151 } else if (getLexer().is(AsmToken::Plus)) 3152 Lexer.Lex(); 3153 3154 if (Lexer.is(AsmToken::Error)) 3155 return TokError(Lexer.getErr()); 3156 if (Lexer.isNot(AsmToken::Integer) && Lexer.isNot(AsmToken::Real) && 3157 Lexer.isNot(AsmToken::Identifier)) 3158 return TokError("unexpected token in directive"); 3159 3160 // Convert to an APFloat. 3161 APFloat Value(Semantics); 3162 StringRef IDVal = getTok().getString(); 3163 if (getLexer().is(AsmToken::Identifier)) { 3164 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf")) 3165 Value = APFloat::getInf(Semantics); 3166 else if (!IDVal.compare_lower("nan")) 3167 Value = APFloat::getNaN(Semantics, false, ~0); 3168 else 3169 return TokError("invalid floating point literal"); 3170 } else if (errorToBool( 3171 Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) 3172 .takeError())) 3173 return TokError("invalid floating point literal"); 3174 if (IsNeg) 3175 Value.changeSign(); 3176 3177 // Consume the numeric token. 3178 Lex(); 3179 3180 Res = Value.bitcastToAPInt(); 3181 3182 return false; 3183 } 3184 3185 /// parseDirectiveRealValue 3186 /// ::= (.single | .double) [ expression (, expression)* ] 3187 bool AsmParser::parseDirectiveRealValue(StringRef IDVal, 3188 const fltSemantics &Semantics) { 3189 auto parseOp = [&]() -> bool { 3190 APInt AsInt; 3191 if (checkForValidSection() || parseRealValue(Semantics, AsInt)) 3192 return true; 3193 getStreamer().emitIntValue(AsInt.getLimitedValue(), 3194 AsInt.getBitWidth() / 8); 3195 return false; 3196 }; 3197 3198 if (parseMany(parseOp)) 3199 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive"); 3200 return false; 3201 } 3202 3203 /// parseDirectiveZero 3204 /// ::= .zero expression 3205 bool AsmParser::parseDirectiveZero() { 3206 SMLoc NumBytesLoc = Lexer.getLoc(); 3207 const MCExpr *NumBytes; 3208 if (checkForValidSection() || parseExpression(NumBytes)) 3209 return true; 3210 3211 int64_t Val = 0; 3212 if (getLexer().is(AsmToken::Comma)) { 3213 Lex(); 3214 if (parseAbsoluteExpression(Val)) 3215 return true; 3216 } 3217 3218 if (parseEOL()) 3219 return true; 3220 getStreamer().emitFill(*NumBytes, Val, NumBytesLoc); 3221 3222 return false; 3223 } 3224 3225 /// parseDirectiveFill 3226 /// ::= .fill expression [ , expression [ , expression ] ] 3227 bool AsmParser::parseDirectiveFill() { 3228 SMLoc NumValuesLoc = Lexer.getLoc(); 3229 const MCExpr *NumValues; 3230 if (checkForValidSection() || parseExpression(NumValues)) 3231 return true; 3232 3233 int64_t FillSize = 1; 3234 int64_t FillExpr = 0; 3235 3236 SMLoc SizeLoc, ExprLoc; 3237 3238 if (parseOptionalToken(AsmToken::Comma)) { 3239 SizeLoc = getTok().getLoc(); 3240 if (parseAbsoluteExpression(FillSize)) 3241 return true; 3242 if (parseOptionalToken(AsmToken::Comma)) { 3243 ExprLoc = getTok().getLoc(); 3244 if (parseAbsoluteExpression(FillExpr)) 3245 return true; 3246 } 3247 } 3248 if (parseEOL()) 3249 return true; 3250 3251 if (FillSize < 0) { 3252 Warning(SizeLoc, "'.fill' directive with negative size has no effect"); 3253 return false; 3254 } 3255 if (FillSize > 8) { 3256 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8"); 3257 FillSize = 8; 3258 } 3259 3260 if (!isUInt<32>(FillExpr) && FillSize > 4) 3261 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits"); 3262 3263 getStreamer().emitFill(*NumValues, FillSize, FillExpr, NumValuesLoc); 3264 3265 return false; 3266 } 3267 3268 /// parseDirectiveOrg 3269 /// ::= .org expression [ , expression ] 3270 bool AsmParser::parseDirectiveOrg() { 3271 const MCExpr *Offset; 3272 SMLoc OffsetLoc = Lexer.getLoc(); 3273 if (checkForValidSection() || parseExpression(Offset)) 3274 return true; 3275 3276 // Parse optional fill expression. 3277 int64_t FillExpr = 0; 3278 if (parseOptionalToken(AsmToken::Comma)) 3279 if (parseAbsoluteExpression(FillExpr)) 3280 return addErrorSuffix(" in '.org' directive"); 3281 if (parseEOL()) 3282 return addErrorSuffix(" in '.org' directive"); 3283 3284 getStreamer().emitValueToOffset(Offset, FillExpr, OffsetLoc); 3285 return false; 3286 } 3287 3288 /// parseDirectiveAlign 3289 /// ::= {.align, ...} expression [ , expression [ , expression ]] 3290 bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) { 3291 SMLoc AlignmentLoc = getLexer().getLoc(); 3292 int64_t Alignment; 3293 SMLoc MaxBytesLoc; 3294 bool HasFillExpr = false; 3295 int64_t FillExpr = 0; 3296 int64_t MaxBytesToFill = 0; 3297 3298 auto parseAlign = [&]() -> bool { 3299 if (parseAbsoluteExpression(Alignment)) 3300 return true; 3301 if (parseOptionalToken(AsmToken::Comma)) { 3302 // The fill expression can be omitted while specifying a maximum number of 3303 // alignment bytes, e.g: 3304 // .align 3,,4 3305 if (getTok().isNot(AsmToken::Comma)) { 3306 HasFillExpr = true; 3307 if (parseAbsoluteExpression(FillExpr)) 3308 return true; 3309 } 3310 if (parseOptionalToken(AsmToken::Comma)) 3311 if (parseTokenLoc(MaxBytesLoc) || 3312 parseAbsoluteExpression(MaxBytesToFill)) 3313 return true; 3314 } 3315 return parseEOL(); 3316 }; 3317 3318 if (checkForValidSection()) 3319 return addErrorSuffix(" in directive"); 3320 // Ignore empty '.p2align' directives for GNU-as compatibility 3321 if (IsPow2 && (ValueSize == 1) && getTok().is(AsmToken::EndOfStatement)) { 3322 Warning(AlignmentLoc, "p2align directive with no operand(s) is ignored"); 3323 return parseEOL(); 3324 } 3325 if (parseAlign()) 3326 return addErrorSuffix(" in directive"); 3327 3328 // Always emit an alignment here even if we thrown an error. 3329 bool ReturnVal = false; 3330 3331 // Compute alignment in bytes. 3332 if (IsPow2) { 3333 // FIXME: Diagnose overflow. 3334 if (Alignment >= 32) { 3335 ReturnVal |= Error(AlignmentLoc, "invalid alignment value"); 3336 Alignment = 31; 3337 } 3338 3339 Alignment = 1ULL << Alignment; 3340 } else { 3341 // Reject alignments that aren't either a power of two or zero, 3342 // for gas compatibility. Alignment of zero is silently rounded 3343 // up to one. 3344 if (Alignment == 0) 3345 Alignment = 1; 3346 if (!isPowerOf2_64(Alignment)) 3347 ReturnVal |= Error(AlignmentLoc, "alignment must be a power of 2"); 3348 if (!isUInt<32>(Alignment)) 3349 ReturnVal |= Error(AlignmentLoc, "alignment must be smaller than 2**32"); 3350 } 3351 3352 // Diagnose non-sensical max bytes to align. 3353 if (MaxBytesLoc.isValid()) { 3354 if (MaxBytesToFill < 1) { 3355 ReturnVal |= Error(MaxBytesLoc, 3356 "alignment directive can never be satisfied in this " 3357 "many bytes, ignoring maximum bytes expression"); 3358 MaxBytesToFill = 0; 3359 } 3360 3361 if (MaxBytesToFill >= Alignment) { 3362 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and " 3363 "has no effect"); 3364 MaxBytesToFill = 0; 3365 } 3366 } 3367 3368 // Check whether we should use optimal code alignment for this .align 3369 // directive. 3370 const MCSection *Section = getStreamer().getCurrentSectionOnly(); 3371 assert(Section && "must have section to emit alignment"); 3372 bool UseCodeAlign = Section->UseCodeAlign(); 3373 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) && 3374 ValueSize == 1 && UseCodeAlign) { 3375 getStreamer().emitCodeAlignment(Alignment, MaxBytesToFill); 3376 } else { 3377 // FIXME: Target specific behavior about how the "extra" bytes are filled. 3378 getStreamer().emitValueToAlignment(Alignment, FillExpr, ValueSize, 3379 MaxBytesToFill); 3380 } 3381 3382 return ReturnVal; 3383 } 3384 3385 /// parseDirectiveFile 3386 /// ::= .file filename 3387 /// ::= .file number [directory] filename [md5 checksum] [source source-text] 3388 bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) { 3389 // FIXME: I'm not sure what this is. 3390 int64_t FileNumber = -1; 3391 if (getLexer().is(AsmToken::Integer)) { 3392 FileNumber = getTok().getIntVal(); 3393 Lex(); 3394 3395 if (FileNumber < 0) 3396 return TokError("negative file number"); 3397 } 3398 3399 std::string Path; 3400 3401 // Usually the directory and filename together, otherwise just the directory. 3402 // Allow the strings to have escaped octal character sequence. 3403 if (check(getTok().isNot(AsmToken::String), 3404 "unexpected token in '.file' directive") || 3405 parseEscapedString(Path)) 3406 return true; 3407 3408 StringRef Directory; 3409 StringRef Filename; 3410 std::string FilenameData; 3411 if (getLexer().is(AsmToken::String)) { 3412 if (check(FileNumber == -1, 3413 "explicit path specified, but no file number") || 3414 parseEscapedString(FilenameData)) 3415 return true; 3416 Filename = FilenameData; 3417 Directory = Path; 3418 } else { 3419 Filename = Path; 3420 } 3421 3422 uint64_t MD5Hi, MD5Lo; 3423 bool HasMD5 = false; 3424 3425 Optional<StringRef> Source; 3426 bool HasSource = false; 3427 std::string SourceString; 3428 3429 while (!parseOptionalToken(AsmToken::EndOfStatement)) { 3430 StringRef Keyword; 3431 if (check(getTok().isNot(AsmToken::Identifier), 3432 "unexpected token in '.file' directive") || 3433 parseIdentifier(Keyword)) 3434 return true; 3435 if (Keyword == "md5") { 3436 HasMD5 = true; 3437 if (check(FileNumber == -1, 3438 "MD5 checksum specified, but no file number") || 3439 parseHexOcta(*this, MD5Hi, MD5Lo)) 3440 return true; 3441 } else if (Keyword == "source") { 3442 HasSource = true; 3443 if (check(FileNumber == -1, 3444 "source specified, but no file number") || 3445 check(getTok().isNot(AsmToken::String), 3446 "unexpected token in '.file' directive") || 3447 parseEscapedString(SourceString)) 3448 return true; 3449 } else { 3450 return TokError("unexpected token in '.file' directive"); 3451 } 3452 } 3453 3454 if (FileNumber == -1) { 3455 // Ignore the directive if there is no number and the target doesn't support 3456 // numberless .file directives. This allows some portability of assembler 3457 // between different object file formats. 3458 if (getContext().getAsmInfo()->hasSingleParameterDotFile()) 3459 getStreamer().emitFileDirective(Filename); 3460 } else { 3461 // In case there is a -g option as well as debug info from directive .file, 3462 // we turn off the -g option, directly use the existing debug info instead. 3463 // Throw away any implicit file table for the assembler source. 3464 if (Ctx.getGenDwarfForAssembly()) { 3465 Ctx.getMCDwarfLineTable(0).resetFileTable(); 3466 Ctx.setGenDwarfForAssembly(false); 3467 } 3468 3469 Optional<MD5::MD5Result> CKMem; 3470 if (HasMD5) { 3471 MD5::MD5Result Sum; 3472 for (unsigned i = 0; i != 8; ++i) { 3473 Sum.Bytes[i] = uint8_t(MD5Hi >> ((7 - i) * 8)); 3474 Sum.Bytes[i + 8] = uint8_t(MD5Lo >> ((7 - i) * 8)); 3475 } 3476 CKMem = Sum; 3477 } 3478 if (HasSource) { 3479 char *SourceBuf = static_cast<char *>(Ctx.allocate(SourceString.size())); 3480 memcpy(SourceBuf, SourceString.data(), SourceString.size()); 3481 Source = StringRef(SourceBuf, SourceString.size()); 3482 } 3483 if (FileNumber == 0) { 3484 // Upgrade to Version 5 for assembly actions like clang -c a.s. 3485 if (Ctx.getDwarfVersion() < 5) 3486 Ctx.setDwarfVersion(5); 3487 getStreamer().emitDwarfFile0Directive(Directory, Filename, CKMem, Source); 3488 } else { 3489 Expected<unsigned> FileNumOrErr = getStreamer().tryEmitDwarfFileDirective( 3490 FileNumber, Directory, Filename, CKMem, Source); 3491 if (!FileNumOrErr) 3492 return Error(DirectiveLoc, toString(FileNumOrErr.takeError())); 3493 } 3494 // Alert the user if there are some .file directives with MD5 and some not. 3495 // But only do that once. 3496 if (!ReportedInconsistentMD5 && !Ctx.isDwarfMD5UsageConsistent(0)) { 3497 ReportedInconsistentMD5 = true; 3498 return Warning(DirectiveLoc, "inconsistent use of MD5 checksums"); 3499 } 3500 } 3501 3502 return false; 3503 } 3504 3505 /// parseDirectiveLine 3506 /// ::= .line [number] 3507 bool AsmParser::parseDirectiveLine() { 3508 int64_t LineNumber; 3509 if (getLexer().is(AsmToken::Integer)) { 3510 if (parseIntToken(LineNumber, "unexpected token in '.line' directive")) 3511 return true; 3512 (void)LineNumber; 3513 // FIXME: Do something with the .line. 3514 } 3515 return parseEOL(); 3516 } 3517 3518 /// parseDirectiveLoc 3519 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end] 3520 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE] 3521 /// The first number is a file number, must have been previously assigned with 3522 /// a .file directive, the second number is the line number and optionally the 3523 /// third number is a column position (zero if not specified). The remaining 3524 /// optional items are .loc sub-directives. 3525 bool AsmParser::parseDirectiveLoc() { 3526 int64_t FileNumber = 0, LineNumber = 0; 3527 SMLoc Loc = getTok().getLoc(); 3528 if (parseIntToken(FileNumber, "unexpected token in '.loc' directive") || 3529 check(FileNumber < 1 && Ctx.getDwarfVersion() < 5, Loc, 3530 "file number less than one in '.loc' directive") || 3531 check(!getContext().isValidDwarfFileNumber(FileNumber), Loc, 3532 "unassigned file number in '.loc' directive")) 3533 return true; 3534 3535 // optional 3536 if (getLexer().is(AsmToken::Integer)) { 3537 LineNumber = getTok().getIntVal(); 3538 if (LineNumber < 0) 3539 return TokError("line number less than zero in '.loc' directive"); 3540 Lex(); 3541 } 3542 3543 int64_t ColumnPos = 0; 3544 if (getLexer().is(AsmToken::Integer)) { 3545 ColumnPos = getTok().getIntVal(); 3546 if (ColumnPos < 0) 3547 return TokError("column position less than zero in '.loc' directive"); 3548 Lex(); 3549 } 3550 3551 auto PrevFlags = getContext().getCurrentDwarfLoc().getFlags(); 3552 unsigned Flags = PrevFlags & DWARF2_FLAG_IS_STMT; 3553 unsigned Isa = 0; 3554 int64_t Discriminator = 0; 3555 3556 auto parseLocOp = [&]() -> bool { 3557 StringRef Name; 3558 SMLoc Loc = getTok().getLoc(); 3559 if (parseIdentifier(Name)) 3560 return TokError("unexpected token in '.loc' directive"); 3561 3562 if (Name == "basic_block") 3563 Flags |= DWARF2_FLAG_BASIC_BLOCK; 3564 else if (Name == "prologue_end") 3565 Flags |= DWARF2_FLAG_PROLOGUE_END; 3566 else if (Name == "epilogue_begin") 3567 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN; 3568 else if (Name == "is_stmt") { 3569 Loc = getTok().getLoc(); 3570 const MCExpr *Value; 3571 if (parseExpression(Value)) 3572 return true; 3573 // The expression must be the constant 0 or 1. 3574 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) { 3575 int Value = MCE->getValue(); 3576 if (Value == 0) 3577 Flags &= ~DWARF2_FLAG_IS_STMT; 3578 else if (Value == 1) 3579 Flags |= DWARF2_FLAG_IS_STMT; 3580 else 3581 return Error(Loc, "is_stmt value not 0 or 1"); 3582 } else { 3583 return Error(Loc, "is_stmt value not the constant value of 0 or 1"); 3584 } 3585 } else if (Name == "isa") { 3586 Loc = getTok().getLoc(); 3587 const MCExpr *Value; 3588 if (parseExpression(Value)) 3589 return true; 3590 // The expression must be a constant greater or equal to 0. 3591 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) { 3592 int Value = MCE->getValue(); 3593 if (Value < 0) 3594 return Error(Loc, "isa number less than zero"); 3595 Isa = Value; 3596 } else { 3597 return Error(Loc, "isa number not a constant value"); 3598 } 3599 } else if (Name == "discriminator") { 3600 if (parseAbsoluteExpression(Discriminator)) 3601 return true; 3602 } else { 3603 return Error(Loc, "unknown sub-directive in '.loc' directive"); 3604 } 3605 return false; 3606 }; 3607 3608 if (parseMany(parseLocOp, false /*hasComma*/)) 3609 return true; 3610 3611 getStreamer().emitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags, 3612 Isa, Discriminator, StringRef()); 3613 3614 return false; 3615 } 3616 3617 /// parseDirectiveStabs 3618 /// ::= .stabs string, number, number, number 3619 bool AsmParser::parseDirectiveStabs() { 3620 return TokError("unsupported directive '.stabs'"); 3621 } 3622 3623 /// parseDirectiveCVFile 3624 /// ::= .cv_file number filename [checksum] [checksumkind] 3625 bool AsmParser::parseDirectiveCVFile() { 3626 SMLoc FileNumberLoc = getTok().getLoc(); 3627 int64_t FileNumber; 3628 std::string Filename; 3629 std::string Checksum; 3630 int64_t ChecksumKind = 0; 3631 3632 if (parseIntToken(FileNumber, 3633 "expected file number in '.cv_file' directive") || 3634 check(FileNumber < 1, FileNumberLoc, "file number less than one") || 3635 check(getTok().isNot(AsmToken::String), 3636 "unexpected token in '.cv_file' directive") || 3637 parseEscapedString(Filename)) 3638 return true; 3639 if (!parseOptionalToken(AsmToken::EndOfStatement)) { 3640 if (check(getTok().isNot(AsmToken::String), 3641 "unexpected token in '.cv_file' directive") || 3642 parseEscapedString(Checksum) || 3643 parseIntToken(ChecksumKind, 3644 "expected checksum kind in '.cv_file' directive") || 3645 parseToken(AsmToken::EndOfStatement, 3646 "unexpected token in '.cv_file' directive")) 3647 return true; 3648 } 3649 3650 Checksum = fromHex(Checksum); 3651 void *CKMem = Ctx.allocate(Checksum.size(), 1); 3652 memcpy(CKMem, Checksum.data(), Checksum.size()); 3653 ArrayRef<uint8_t> ChecksumAsBytes(reinterpret_cast<const uint8_t *>(CKMem), 3654 Checksum.size()); 3655 3656 if (!getStreamer().EmitCVFileDirective(FileNumber, Filename, ChecksumAsBytes, 3657 static_cast<uint8_t>(ChecksumKind))) 3658 return Error(FileNumberLoc, "file number already allocated"); 3659 3660 return false; 3661 } 3662 3663 bool AsmParser::parseCVFunctionId(int64_t &FunctionId, 3664 StringRef DirectiveName) { 3665 SMLoc Loc; 3666 return parseTokenLoc(Loc) || 3667 parseIntToken(FunctionId, "expected function id in '" + DirectiveName + 3668 "' directive") || 3669 check(FunctionId < 0 || FunctionId >= UINT_MAX, Loc, 3670 "expected function id within range [0, UINT_MAX)"); 3671 } 3672 3673 bool AsmParser::parseCVFileId(int64_t &FileNumber, StringRef DirectiveName) { 3674 SMLoc Loc; 3675 return parseTokenLoc(Loc) || 3676 parseIntToken(FileNumber, "expected integer in '" + DirectiveName + 3677 "' directive") || 3678 check(FileNumber < 1, Loc, "file number less than one in '" + 3679 DirectiveName + "' directive") || 3680 check(!getCVContext().isValidFileNumber(FileNumber), Loc, 3681 "unassigned file number in '" + DirectiveName + "' directive"); 3682 } 3683 3684 /// parseDirectiveCVFuncId 3685 /// ::= .cv_func_id FunctionId 3686 /// 3687 /// Introduces a function ID that can be used with .cv_loc. 3688 bool AsmParser::parseDirectiveCVFuncId() { 3689 SMLoc FunctionIdLoc = getTok().getLoc(); 3690 int64_t FunctionId; 3691 3692 if (parseCVFunctionId(FunctionId, ".cv_func_id") || 3693 parseToken(AsmToken::EndOfStatement, 3694 "unexpected token in '.cv_func_id' directive")) 3695 return true; 3696 3697 if (!getStreamer().EmitCVFuncIdDirective(FunctionId)) 3698 return Error(FunctionIdLoc, "function id already allocated"); 3699 3700 return false; 3701 } 3702 3703 /// parseDirectiveCVInlineSiteId 3704 /// ::= .cv_inline_site_id FunctionId 3705 /// "within" IAFunc 3706 /// "inlined_at" IAFile IALine [IACol] 3707 /// 3708 /// Introduces a function ID that can be used with .cv_loc. Includes "inlined 3709 /// at" source location information for use in the line table of the caller, 3710 /// whether the caller is a real function or another inlined call site. 3711 bool AsmParser::parseDirectiveCVInlineSiteId() { 3712 SMLoc FunctionIdLoc = getTok().getLoc(); 3713 int64_t FunctionId; 3714 int64_t IAFunc; 3715 int64_t IAFile; 3716 int64_t IALine; 3717 int64_t IACol = 0; 3718 3719 // FunctionId 3720 if (parseCVFunctionId(FunctionId, ".cv_inline_site_id")) 3721 return true; 3722 3723 // "within" 3724 if (check((getLexer().isNot(AsmToken::Identifier) || 3725 getTok().getIdentifier() != "within"), 3726 "expected 'within' identifier in '.cv_inline_site_id' directive")) 3727 return true; 3728 Lex(); 3729 3730 // IAFunc 3731 if (parseCVFunctionId(IAFunc, ".cv_inline_site_id")) 3732 return true; 3733 3734 // "inlined_at" 3735 if (check((getLexer().isNot(AsmToken::Identifier) || 3736 getTok().getIdentifier() != "inlined_at"), 3737 "expected 'inlined_at' identifier in '.cv_inline_site_id' " 3738 "directive") ) 3739 return true; 3740 Lex(); 3741 3742 // IAFile IALine 3743 if (parseCVFileId(IAFile, ".cv_inline_site_id") || 3744 parseIntToken(IALine, "expected line number after 'inlined_at'")) 3745 return true; 3746 3747 // [IACol] 3748 if (getLexer().is(AsmToken::Integer)) { 3749 IACol = getTok().getIntVal(); 3750 Lex(); 3751 } 3752 3753 if (parseToken(AsmToken::EndOfStatement, 3754 "unexpected token in '.cv_inline_site_id' directive")) 3755 return true; 3756 3757 if (!getStreamer().EmitCVInlineSiteIdDirective(FunctionId, IAFunc, IAFile, 3758 IALine, IACol, FunctionIdLoc)) 3759 return Error(FunctionIdLoc, "function id already allocated"); 3760 3761 return false; 3762 } 3763 3764 /// parseDirectiveCVLoc 3765 /// ::= .cv_loc FunctionId FileNumber [LineNumber] [ColumnPos] [prologue_end] 3766 /// [is_stmt VALUE] 3767 /// The first number is a file number, must have been previously assigned with 3768 /// a .file directive, the second number is the line number and optionally the 3769 /// third number is a column position (zero if not specified). The remaining 3770 /// optional items are .loc sub-directives. 3771 bool AsmParser::parseDirectiveCVLoc() { 3772 SMLoc DirectiveLoc = getTok().getLoc(); 3773 int64_t FunctionId, FileNumber; 3774 if (parseCVFunctionId(FunctionId, ".cv_loc") || 3775 parseCVFileId(FileNumber, ".cv_loc")) 3776 return true; 3777 3778 int64_t LineNumber = 0; 3779 if (getLexer().is(AsmToken::Integer)) { 3780 LineNumber = getTok().getIntVal(); 3781 if (LineNumber < 0) 3782 return TokError("line number less than zero in '.cv_loc' directive"); 3783 Lex(); 3784 } 3785 3786 int64_t ColumnPos = 0; 3787 if (getLexer().is(AsmToken::Integer)) { 3788 ColumnPos = getTok().getIntVal(); 3789 if (ColumnPos < 0) 3790 return TokError("column position less than zero in '.cv_loc' directive"); 3791 Lex(); 3792 } 3793 3794 bool PrologueEnd = false; 3795 uint64_t IsStmt = 0; 3796 3797 auto parseOp = [&]() -> bool { 3798 StringRef Name; 3799 SMLoc Loc = getTok().getLoc(); 3800 if (parseIdentifier(Name)) 3801 return TokError("unexpected token in '.cv_loc' directive"); 3802 if (Name == "prologue_end") 3803 PrologueEnd = true; 3804 else if (Name == "is_stmt") { 3805 Loc = getTok().getLoc(); 3806 const MCExpr *Value; 3807 if (parseExpression(Value)) 3808 return true; 3809 // The expression must be the constant 0 or 1. 3810 IsStmt = ~0ULL; 3811 if (const auto *MCE = dyn_cast<MCConstantExpr>(Value)) 3812 IsStmt = MCE->getValue(); 3813 3814 if (IsStmt > 1) 3815 return Error(Loc, "is_stmt value not 0 or 1"); 3816 } else { 3817 return Error(Loc, "unknown sub-directive in '.cv_loc' directive"); 3818 } 3819 return false; 3820 }; 3821 3822 if (parseMany(parseOp, false /*hasComma*/)) 3823 return true; 3824 3825 getStreamer().emitCVLocDirective(FunctionId, FileNumber, LineNumber, 3826 ColumnPos, PrologueEnd, IsStmt, StringRef(), 3827 DirectiveLoc); 3828 return false; 3829 } 3830 3831 /// parseDirectiveCVLinetable 3832 /// ::= .cv_linetable FunctionId, FnStart, FnEnd 3833 bool AsmParser::parseDirectiveCVLinetable() { 3834 int64_t FunctionId; 3835 StringRef FnStartName, FnEndName; 3836 SMLoc Loc = getTok().getLoc(); 3837 if (parseCVFunctionId(FunctionId, ".cv_linetable") || 3838 parseToken(AsmToken::Comma, 3839 "unexpected token in '.cv_linetable' directive") || 3840 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc, 3841 "expected identifier in directive") || 3842 parseToken(AsmToken::Comma, 3843 "unexpected token in '.cv_linetable' directive") || 3844 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc, 3845 "expected identifier in directive")) 3846 return true; 3847 3848 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName); 3849 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName); 3850 3851 getStreamer().emitCVLinetableDirective(FunctionId, FnStartSym, FnEndSym); 3852 return false; 3853 } 3854 3855 /// parseDirectiveCVInlineLinetable 3856 /// ::= .cv_inline_linetable PrimaryFunctionId FileId LineNum FnStart FnEnd 3857 bool AsmParser::parseDirectiveCVInlineLinetable() { 3858 int64_t PrimaryFunctionId, SourceFileId, SourceLineNum; 3859 StringRef FnStartName, FnEndName; 3860 SMLoc Loc = getTok().getLoc(); 3861 if (parseCVFunctionId(PrimaryFunctionId, ".cv_inline_linetable") || 3862 parseTokenLoc(Loc) || 3863 parseIntToken( 3864 SourceFileId, 3865 "expected SourceField in '.cv_inline_linetable' directive") || 3866 check(SourceFileId <= 0, Loc, 3867 "File id less than zero in '.cv_inline_linetable' directive") || 3868 parseTokenLoc(Loc) || 3869 parseIntToken( 3870 SourceLineNum, 3871 "expected SourceLineNum in '.cv_inline_linetable' directive") || 3872 check(SourceLineNum < 0, Loc, 3873 "Line number less than zero in '.cv_inline_linetable' directive") || 3874 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc, 3875 "expected identifier in directive") || 3876 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc, 3877 "expected identifier in directive")) 3878 return true; 3879 3880 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement")) 3881 return true; 3882 3883 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName); 3884 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName); 3885 getStreamer().emitCVInlineLinetableDirective(PrimaryFunctionId, SourceFileId, 3886 SourceLineNum, FnStartSym, 3887 FnEndSym); 3888 return false; 3889 } 3890 3891 void AsmParser::initializeCVDefRangeTypeMap() { 3892 CVDefRangeTypeMap["reg"] = CVDR_DEFRANGE_REGISTER; 3893 CVDefRangeTypeMap["frame_ptr_rel"] = CVDR_DEFRANGE_FRAMEPOINTER_REL; 3894 CVDefRangeTypeMap["subfield_reg"] = CVDR_DEFRANGE_SUBFIELD_REGISTER; 3895 CVDefRangeTypeMap["reg_rel"] = CVDR_DEFRANGE_REGISTER_REL; 3896 } 3897 3898 /// parseDirectiveCVDefRange 3899 /// ::= .cv_def_range RangeStart RangeEnd (GapStart GapEnd)*, bytes* 3900 bool AsmParser::parseDirectiveCVDefRange() { 3901 SMLoc Loc; 3902 std::vector<std::pair<const MCSymbol *, const MCSymbol *>> Ranges; 3903 while (getLexer().is(AsmToken::Identifier)) { 3904 Loc = getLexer().getLoc(); 3905 StringRef GapStartName; 3906 if (parseIdentifier(GapStartName)) 3907 return Error(Loc, "expected identifier in directive"); 3908 MCSymbol *GapStartSym = getContext().getOrCreateSymbol(GapStartName); 3909 3910 Loc = getLexer().getLoc(); 3911 StringRef GapEndName; 3912 if (parseIdentifier(GapEndName)) 3913 return Error(Loc, "expected identifier in directive"); 3914 MCSymbol *GapEndSym = getContext().getOrCreateSymbol(GapEndName); 3915 3916 Ranges.push_back({GapStartSym, GapEndSym}); 3917 } 3918 3919 StringRef CVDefRangeTypeStr; 3920 if (parseToken( 3921 AsmToken::Comma, 3922 "expected comma before def_range type in .cv_def_range directive") || 3923 parseIdentifier(CVDefRangeTypeStr)) 3924 return Error(Loc, "expected def_range type in directive"); 3925 3926 StringMap<CVDefRangeType>::const_iterator CVTypeIt = 3927 CVDefRangeTypeMap.find(CVDefRangeTypeStr); 3928 CVDefRangeType CVDRType = (CVTypeIt == CVDefRangeTypeMap.end()) 3929 ? CVDR_DEFRANGE 3930 : CVTypeIt->getValue(); 3931 switch (CVDRType) { 3932 case CVDR_DEFRANGE_REGISTER: { 3933 int64_t DRRegister; 3934 if (parseToken(AsmToken::Comma, "expected comma before register number in " 3935 ".cv_def_range directive") || 3936 parseAbsoluteExpression(DRRegister)) 3937 return Error(Loc, "expected register number"); 3938 3939 codeview::DefRangeRegisterHeader DRHdr; 3940 DRHdr.Register = DRRegister; 3941 DRHdr.MayHaveNoName = 0; 3942 getStreamer().emitCVDefRangeDirective(Ranges, DRHdr); 3943 break; 3944 } 3945 case CVDR_DEFRANGE_FRAMEPOINTER_REL: { 3946 int64_t DROffset; 3947 if (parseToken(AsmToken::Comma, 3948 "expected comma before offset in .cv_def_range directive") || 3949 parseAbsoluteExpression(DROffset)) 3950 return Error(Loc, "expected offset value"); 3951 3952 codeview::DefRangeFramePointerRelHeader DRHdr; 3953 DRHdr.Offset = DROffset; 3954 getStreamer().emitCVDefRangeDirective(Ranges, DRHdr); 3955 break; 3956 } 3957 case CVDR_DEFRANGE_SUBFIELD_REGISTER: { 3958 int64_t DRRegister; 3959 int64_t DROffsetInParent; 3960 if (parseToken(AsmToken::Comma, "expected comma before register number in " 3961 ".cv_def_range directive") || 3962 parseAbsoluteExpression(DRRegister)) 3963 return Error(Loc, "expected register number"); 3964 if (parseToken(AsmToken::Comma, 3965 "expected comma before offset in .cv_def_range directive") || 3966 parseAbsoluteExpression(DROffsetInParent)) 3967 return Error(Loc, "expected offset value"); 3968 3969 codeview::DefRangeSubfieldRegisterHeader DRHdr; 3970 DRHdr.Register = DRRegister; 3971 DRHdr.MayHaveNoName = 0; 3972 DRHdr.OffsetInParent = DROffsetInParent; 3973 getStreamer().emitCVDefRangeDirective(Ranges, DRHdr); 3974 break; 3975 } 3976 case CVDR_DEFRANGE_REGISTER_REL: { 3977 int64_t DRRegister; 3978 int64_t DRFlags; 3979 int64_t DRBasePointerOffset; 3980 if (parseToken(AsmToken::Comma, "expected comma before register number in " 3981 ".cv_def_range directive") || 3982 parseAbsoluteExpression(DRRegister)) 3983 return Error(Loc, "expected register value"); 3984 if (parseToken( 3985 AsmToken::Comma, 3986 "expected comma before flag value in .cv_def_range directive") || 3987 parseAbsoluteExpression(DRFlags)) 3988 return Error(Loc, "expected flag value"); 3989 if (parseToken(AsmToken::Comma, "expected comma before base pointer offset " 3990 "in .cv_def_range directive") || 3991 parseAbsoluteExpression(DRBasePointerOffset)) 3992 return Error(Loc, "expected base pointer offset value"); 3993 3994 codeview::DefRangeRegisterRelHeader DRHdr; 3995 DRHdr.Register = DRRegister; 3996 DRHdr.Flags = DRFlags; 3997 DRHdr.BasePointerOffset = DRBasePointerOffset; 3998 getStreamer().emitCVDefRangeDirective(Ranges, DRHdr); 3999 break; 4000 } 4001 default: 4002 return Error(Loc, "unexpected def_range type in .cv_def_range directive"); 4003 } 4004 return true; 4005 } 4006 4007 /// parseDirectiveCVString 4008 /// ::= .cv_stringtable "string" 4009 bool AsmParser::parseDirectiveCVString() { 4010 std::string Data; 4011 if (checkForValidSection() || parseEscapedString(Data)) 4012 return addErrorSuffix(" in '.cv_string' directive"); 4013 4014 // Put the string in the table and emit the offset. 4015 std::pair<StringRef, unsigned> Insertion = 4016 getCVContext().addToStringTable(Data); 4017 getStreamer().emitInt32(Insertion.second); 4018 return false; 4019 } 4020 4021 /// parseDirectiveCVStringTable 4022 /// ::= .cv_stringtable 4023 bool AsmParser::parseDirectiveCVStringTable() { 4024 getStreamer().emitCVStringTableDirective(); 4025 return false; 4026 } 4027 4028 /// parseDirectiveCVFileChecksums 4029 /// ::= .cv_filechecksums 4030 bool AsmParser::parseDirectiveCVFileChecksums() { 4031 getStreamer().emitCVFileChecksumsDirective(); 4032 return false; 4033 } 4034 4035 /// parseDirectiveCVFileChecksumOffset 4036 /// ::= .cv_filechecksumoffset fileno 4037 bool AsmParser::parseDirectiveCVFileChecksumOffset() { 4038 int64_t FileNo; 4039 if (parseIntToken(FileNo, "expected identifier in directive")) 4040 return true; 4041 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement")) 4042 return true; 4043 getStreamer().emitCVFileChecksumOffsetDirective(FileNo); 4044 return false; 4045 } 4046 4047 /// parseDirectiveCVFPOData 4048 /// ::= .cv_fpo_data procsym 4049 bool AsmParser::parseDirectiveCVFPOData() { 4050 SMLoc DirLoc = getLexer().getLoc(); 4051 StringRef ProcName; 4052 if (parseIdentifier(ProcName)) 4053 return TokError("expected symbol name"); 4054 if (parseEOL("unexpected tokens")) 4055 return addErrorSuffix(" in '.cv_fpo_data' directive"); 4056 MCSymbol *ProcSym = getContext().getOrCreateSymbol(ProcName); 4057 getStreamer().EmitCVFPOData(ProcSym, DirLoc); 4058 return false; 4059 } 4060 4061 /// parseDirectiveCFISections 4062 /// ::= .cfi_sections section [, section] 4063 bool AsmParser::parseDirectiveCFISections() { 4064 StringRef Name; 4065 bool EH = false; 4066 bool Debug = false; 4067 4068 if (!parseOptionalToken(AsmToken::EndOfStatement)) { 4069 for (;;) { 4070 if (parseIdentifier(Name)) 4071 return TokError("expected .eh_frame or .debug_frame"); 4072 if (Name == ".eh_frame") 4073 EH = true; 4074 else if (Name == ".debug_frame") 4075 Debug = true; 4076 if (parseOptionalToken(AsmToken::EndOfStatement)) 4077 break; 4078 if (parseToken(AsmToken::Comma)) 4079 return true; 4080 } 4081 } 4082 getStreamer().emitCFISections(EH, Debug); 4083 return false; 4084 } 4085 4086 /// parseDirectiveCFIStartProc 4087 /// ::= .cfi_startproc [simple] 4088 bool AsmParser::parseDirectiveCFIStartProc() { 4089 StringRef Simple; 4090 if (!parseOptionalToken(AsmToken::EndOfStatement)) { 4091 if (check(parseIdentifier(Simple) || Simple != "simple", 4092 "unexpected token") || 4093 parseEOL()) 4094 return addErrorSuffix(" in '.cfi_startproc' directive"); 4095 } 4096 4097 // TODO(kristina): Deal with a corner case of incorrect diagnostic context 4098 // being produced if this directive is emitted as part of preprocessor macro 4099 // expansion which can *ONLY* happen if Clang's cc1as is the API consumer. 4100 // Tools like llvm-mc on the other hand are not affected by it, and report 4101 // correct context information. 4102 getStreamer().emitCFIStartProc(!Simple.empty(), Lexer.getLoc()); 4103 return false; 4104 } 4105 4106 /// parseDirectiveCFIEndProc 4107 /// ::= .cfi_endproc 4108 bool AsmParser::parseDirectiveCFIEndProc() { 4109 if (parseEOL()) 4110 return addErrorSuffix(" in '.cfi_endproc' directive"); 4111 getStreamer().emitCFIEndProc(); 4112 return false; 4113 } 4114 4115 /// parse register name or number. 4116 bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register, 4117 SMLoc DirectiveLoc) { 4118 unsigned RegNo; 4119 4120 if (getLexer().isNot(AsmToken::Integer)) { 4121 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc)) 4122 return true; 4123 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true); 4124 } else 4125 return parseAbsoluteExpression(Register); 4126 4127 return false; 4128 } 4129 4130 /// parseDirectiveCFIDefCfa 4131 /// ::= .cfi_def_cfa register, offset 4132 bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) { 4133 int64_t Register = 0, Offset = 0; 4134 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) || 4135 parseToken(AsmToken::Comma, "unexpected token in directive") || 4136 parseAbsoluteExpression(Offset) || parseEOL()) 4137 return true; 4138 4139 getStreamer().emitCFIDefCfa(Register, Offset); 4140 return false; 4141 } 4142 4143 /// parseDirectiveCFIDefCfaOffset 4144 /// ::= .cfi_def_cfa_offset offset 4145 bool AsmParser::parseDirectiveCFIDefCfaOffset() { 4146 int64_t Offset = 0; 4147 if (parseAbsoluteExpression(Offset) || parseEOL()) 4148 return true; 4149 4150 getStreamer().emitCFIDefCfaOffset(Offset); 4151 return false; 4152 } 4153 4154 /// parseDirectiveCFIRegister 4155 /// ::= .cfi_register register, register 4156 bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) { 4157 int64_t Register1 = 0, Register2 = 0; 4158 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc) || 4159 parseToken(AsmToken::Comma, "unexpected token in directive") || 4160 parseRegisterOrRegisterNumber(Register2, DirectiveLoc) || parseEOL()) 4161 return true; 4162 4163 getStreamer().emitCFIRegister(Register1, Register2); 4164 return false; 4165 } 4166 4167 /// parseDirectiveCFIWindowSave 4168 /// ::= .cfi_window_save 4169 bool AsmParser::parseDirectiveCFIWindowSave() { 4170 if (parseEOL()) 4171 return true; 4172 getStreamer().emitCFIWindowSave(); 4173 return false; 4174 } 4175 4176 /// parseDirectiveCFIAdjustCfaOffset 4177 /// ::= .cfi_adjust_cfa_offset adjustment 4178 bool AsmParser::parseDirectiveCFIAdjustCfaOffset() { 4179 int64_t Adjustment = 0; 4180 if (parseAbsoluteExpression(Adjustment) || parseEOL()) 4181 return true; 4182 4183 getStreamer().emitCFIAdjustCfaOffset(Adjustment); 4184 return false; 4185 } 4186 4187 /// parseDirectiveCFIDefCfaRegister 4188 /// ::= .cfi_def_cfa_register register 4189 bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) { 4190 int64_t Register = 0; 4191 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) || parseEOL()) 4192 return true; 4193 4194 getStreamer().emitCFIDefCfaRegister(Register); 4195 return false; 4196 } 4197 4198 /// parseDirectiveCFIOffset 4199 /// ::= .cfi_offset register, offset 4200 bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) { 4201 int64_t Register = 0; 4202 int64_t Offset = 0; 4203 4204 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) || 4205 parseToken(AsmToken::Comma, "unexpected token in directive") || 4206 parseAbsoluteExpression(Offset) || parseEOL()) 4207 return true; 4208 4209 getStreamer().emitCFIOffset(Register, Offset); 4210 return false; 4211 } 4212 4213 /// parseDirectiveCFIRelOffset 4214 /// ::= .cfi_rel_offset register, offset 4215 bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) { 4216 int64_t Register = 0, Offset = 0; 4217 4218 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) || 4219 parseToken(AsmToken::Comma, "unexpected token in directive") || 4220 parseAbsoluteExpression(Offset) || parseEOL()) 4221 return true; 4222 4223 getStreamer().emitCFIRelOffset(Register, Offset); 4224 return false; 4225 } 4226 4227 static bool isValidEncoding(int64_t Encoding) { 4228 if (Encoding & ~0xff) 4229 return false; 4230 4231 if (Encoding == dwarf::DW_EH_PE_omit) 4232 return true; 4233 4234 const unsigned Format = Encoding & 0xf; 4235 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 && 4236 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 && 4237 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 && 4238 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed) 4239 return false; 4240 4241 const unsigned Application = Encoding & 0x70; 4242 if (Application != dwarf::DW_EH_PE_absptr && 4243 Application != dwarf::DW_EH_PE_pcrel) 4244 return false; 4245 4246 return true; 4247 } 4248 4249 /// parseDirectiveCFIPersonalityOrLsda 4250 /// IsPersonality true for cfi_personality, false for cfi_lsda 4251 /// ::= .cfi_personality encoding, [symbol_name] 4252 /// ::= .cfi_lsda encoding, [symbol_name] 4253 bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) { 4254 int64_t Encoding = 0; 4255 if (parseAbsoluteExpression(Encoding)) 4256 return true; 4257 if (Encoding == dwarf::DW_EH_PE_omit) 4258 return false; 4259 4260 StringRef Name; 4261 if (check(!isValidEncoding(Encoding), "unsupported encoding.") || 4262 parseToken(AsmToken::Comma, "unexpected token in directive") || 4263 check(parseIdentifier(Name), "expected identifier in directive") || 4264 parseEOL()) 4265 return true; 4266 4267 MCSymbol *Sym = getContext().getOrCreateSymbol(Name); 4268 4269 if (IsPersonality) 4270 getStreamer().emitCFIPersonality(Sym, Encoding); 4271 else 4272 getStreamer().emitCFILsda(Sym, Encoding); 4273 return false; 4274 } 4275 4276 /// parseDirectiveCFIRememberState 4277 /// ::= .cfi_remember_state 4278 bool AsmParser::parseDirectiveCFIRememberState() { 4279 if (parseEOL()) 4280 return true; 4281 getStreamer().emitCFIRememberState(); 4282 return false; 4283 } 4284 4285 /// parseDirectiveCFIRestoreState 4286 /// ::= .cfi_remember_state 4287 bool AsmParser::parseDirectiveCFIRestoreState() { 4288 if (parseEOL()) 4289 return true; 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) || parseEOL()) 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) || parseEOL()) 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) || parseEOL()) 4345 return true; 4346 getStreamer().emitCFIReturnColumn(Register); 4347 return false; 4348 } 4349 4350 /// parseDirectiveCFISignalFrame 4351 /// ::= .cfi_signal_frame 4352 bool AsmParser::parseDirectiveCFISignalFrame() { 4353 if (parseEOL()) 4354 return true; 4355 4356 getStreamer().emitCFISignalFrame(); 4357 return false; 4358 } 4359 4360 /// parseDirectiveCFIUndefined 4361 /// ::= .cfi_undefined register 4362 bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) { 4363 int64_t Register = 0; 4364 4365 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) || parseEOL()) 4366 return true; 4367 4368 getStreamer().emitCFIUndefined(Register); 4369 return false; 4370 } 4371 4372 /// parseDirectiveAltmacro 4373 /// ::= .altmacro 4374 /// ::= .noaltmacro 4375 bool AsmParser::parseDirectiveAltmacro(StringRef Directive) { 4376 if (parseEOL()) 4377 return true; 4378 AltMacroMode = (Directive == ".altmacro"); 4379 return false; 4380 } 4381 4382 /// parseDirectiveMacrosOnOff 4383 /// ::= .macros_on 4384 /// ::= .macros_off 4385 bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) { 4386 if (parseEOL()) 4387 return true; 4388 setMacrosEnabled(Directive == ".macros_on"); 4389 return false; 4390 } 4391 4392 /// parseDirectiveMacro 4393 /// ::= .macro name[,] [parameters] 4394 bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) { 4395 StringRef Name; 4396 if (parseIdentifier(Name)) 4397 return TokError("expected identifier in '.macro' directive"); 4398 4399 if (getLexer().is(AsmToken::Comma)) 4400 Lex(); 4401 4402 MCAsmMacroParameters Parameters; 4403 while (getLexer().isNot(AsmToken::EndOfStatement)) { 4404 4405 if (!Parameters.empty() && Parameters.back().Vararg) 4406 return Error(Lexer.getLoc(), "vararg parameter '" + 4407 Parameters.back().Name + 4408 "' should be the last parameter"); 4409 4410 MCAsmMacroParameter Parameter; 4411 if (parseIdentifier(Parameter.Name)) 4412 return TokError("expected identifier in '.macro' directive"); 4413 4414 // Emit an error if two (or more) named parameters share the same name 4415 for (const MCAsmMacroParameter& CurrParam : Parameters) 4416 if (CurrParam.Name.equals(Parameter.Name)) 4417 return TokError("macro '" + Name + "' has multiple parameters" 4418 " named '" + Parameter.Name + "'"); 4419 4420 if (Lexer.is(AsmToken::Colon)) { 4421 Lex(); // consume ':' 4422 4423 SMLoc QualLoc; 4424 StringRef Qualifier; 4425 4426 QualLoc = Lexer.getLoc(); 4427 if (parseIdentifier(Qualifier)) 4428 return Error(QualLoc, "missing parameter qualifier for " 4429 "'" + Parameter.Name + "' in macro '" + Name + "'"); 4430 4431 if (Qualifier == "req") 4432 Parameter.Required = true; 4433 else if (Qualifier == "vararg") 4434 Parameter.Vararg = true; 4435 else 4436 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier " 4437 "for '" + Parameter.Name + "' in macro '" + Name + "'"); 4438 } 4439 4440 if (getLexer().is(AsmToken::Equal)) { 4441 Lex(); 4442 4443 SMLoc ParamLoc; 4444 4445 ParamLoc = Lexer.getLoc(); 4446 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false )) 4447 return true; 4448 4449 if (Parameter.Required) 4450 Warning(ParamLoc, "pointless default value for required parameter " 4451 "'" + Parameter.Name + "' in macro '" + Name + "'"); 4452 } 4453 4454 Parameters.push_back(std::move(Parameter)); 4455 4456 if (getLexer().is(AsmToken::Comma)) 4457 Lex(); 4458 } 4459 4460 // Eat just the end of statement. 4461 Lexer.Lex(); 4462 4463 // Consuming deferred text, so use Lexer.Lex to ignore Lexing Errors 4464 AsmToken EndToken, StartToken = getTok(); 4465 unsigned MacroDepth = 0; 4466 // Lex the macro definition. 4467 while (true) { 4468 // Ignore Lexing errors in macros. 4469 while (Lexer.is(AsmToken::Error)) { 4470 Lexer.Lex(); 4471 } 4472 4473 // Check whether we have reached the end of the file. 4474 if (getLexer().is(AsmToken::Eof)) 4475 return Error(DirectiveLoc, "no matching '.endmacro' in definition"); 4476 4477 // Otherwise, check whether we have reach the .endmacro or the start of a 4478 // preprocessor line marker. 4479 if (getLexer().is(AsmToken::Identifier)) { 4480 if (getTok().getIdentifier() == ".endm" || 4481 getTok().getIdentifier() == ".endmacro") { 4482 if (MacroDepth == 0) { // Outermost macro. 4483 EndToken = getTok(); 4484 Lexer.Lex(); 4485 if (getLexer().isNot(AsmToken::EndOfStatement)) 4486 return TokError("unexpected token in '" + EndToken.getIdentifier() + 4487 "' directive"); 4488 break; 4489 } else { 4490 // Otherwise we just found the end of an inner macro. 4491 --MacroDepth; 4492 } 4493 } else if (getTok().getIdentifier() == ".macro") { 4494 // We allow nested macros. Those aren't instantiated until the outermost 4495 // macro is expanded so just ignore them for now. 4496 ++MacroDepth; 4497 } 4498 } else if (Lexer.is(AsmToken::HashDirective)) { 4499 (void)parseCppHashLineFilenameComment(getLexer().getLoc()); 4500 } 4501 4502 // Otherwise, scan til the end of the statement. 4503 eatToEndOfStatement(); 4504 } 4505 4506 if (getContext().lookupMacro(Name)) { 4507 return Error(DirectiveLoc, "macro '" + Name + "' is already defined"); 4508 } 4509 4510 const char *BodyStart = StartToken.getLoc().getPointer(); 4511 const char *BodyEnd = EndToken.getLoc().getPointer(); 4512 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart); 4513 checkForBadMacro(DirectiveLoc, Name, Body, Parameters); 4514 MCAsmMacro Macro(Name, Body, std::move(Parameters)); 4515 DEBUG_WITH_TYPE("asm-macros", dbgs() << "Defining new macro:\n"; 4516 Macro.dump()); 4517 getContext().defineMacro(Name, std::move(Macro)); 4518 return false; 4519 } 4520 4521 /// checkForBadMacro 4522 /// 4523 /// With the support added for named parameters there may be code out there that 4524 /// is transitioning from positional parameters. In versions of gas that did 4525 /// not support named parameters they would be ignored on the macro definition. 4526 /// But to support both styles of parameters this is not possible so if a macro 4527 /// definition has named parameters but does not use them and has what appears 4528 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a 4529 /// warning that the positional parameter found in body which have no effect. 4530 /// Hoping the developer will either remove the named parameters from the macro 4531 /// definition so the positional parameters get used if that was what was 4532 /// intended or change the macro to use the named parameters. It is possible 4533 /// this warning will trigger when the none of the named parameters are used 4534 /// and the strings like $1 are infact to simply to be passed trough unchanged. 4535 void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, 4536 StringRef Body, 4537 ArrayRef<MCAsmMacroParameter> Parameters) { 4538 // If this macro is not defined with named parameters the warning we are 4539 // checking for here doesn't apply. 4540 unsigned NParameters = Parameters.size(); 4541 if (NParameters == 0) 4542 return; 4543 4544 bool NamedParametersFound = false; 4545 bool PositionalParametersFound = false; 4546 4547 // Look at the body of the macro for use of both the named parameters and what 4548 // are likely to be positional parameters. This is what expandMacro() is 4549 // doing when it finds the parameters in the body. 4550 while (!Body.empty()) { 4551 // Scan for the next possible parameter. 4552 std::size_t End = Body.size(), Pos = 0; 4553 for (; Pos != End; ++Pos) { 4554 // Check for a substitution or escape. 4555 // This macro is defined with parameters, look for \foo, \bar, etc. 4556 if (Body[Pos] == '\\' && Pos + 1 != End) 4557 break; 4558 4559 // This macro should have parameters, but look for $0, $1, ..., $n too. 4560 if (Body[Pos] != '$' || Pos + 1 == End) 4561 continue; 4562 char Next = Body[Pos + 1]; 4563 if (Next == '$' || Next == 'n' || 4564 isdigit(static_cast<unsigned char>(Next))) 4565 break; 4566 } 4567 4568 // Check if we reached the end. 4569 if (Pos == End) 4570 break; 4571 4572 if (Body[Pos] == '$') { 4573 switch (Body[Pos + 1]) { 4574 // $$ => $ 4575 case '$': 4576 break; 4577 4578 // $n => number of arguments 4579 case 'n': 4580 PositionalParametersFound = true; 4581 break; 4582 4583 // $[0-9] => argument 4584 default: { 4585 PositionalParametersFound = true; 4586 break; 4587 } 4588 } 4589 Pos += 2; 4590 } else { 4591 unsigned I = Pos + 1; 4592 while (isIdentifierChar(Body[I]) && I + 1 != End) 4593 ++I; 4594 4595 const char *Begin = Body.data() + Pos + 1; 4596 StringRef Argument(Begin, I - (Pos + 1)); 4597 unsigned Index = 0; 4598 for (; Index < NParameters; ++Index) 4599 if (Parameters[Index].Name == Argument) 4600 break; 4601 4602 if (Index == NParameters) { 4603 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')') 4604 Pos += 3; 4605 else { 4606 Pos = I; 4607 } 4608 } else { 4609 NamedParametersFound = true; 4610 Pos += 1 + Argument.size(); 4611 } 4612 } 4613 // Update the scan point. 4614 Body = Body.substr(Pos); 4615 } 4616 4617 if (!NamedParametersFound && PositionalParametersFound) 4618 Warning(DirectiveLoc, "macro defined with named parameters which are not " 4619 "used in macro body, possible positional parameter " 4620 "found in body which will have no effect"); 4621 } 4622 4623 /// parseDirectiveExitMacro 4624 /// ::= .exitm 4625 bool AsmParser::parseDirectiveExitMacro(StringRef Directive) { 4626 if (parseEOL()) 4627 return true; 4628 4629 if (!isInsideMacroInstantiation()) 4630 return TokError("unexpected '" + Directive + "' in file, " 4631 "no current macro definition"); 4632 4633 // Exit all conditionals that are active in the current macro. 4634 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) { 4635 TheCondState = TheCondStack.back(); 4636 TheCondStack.pop_back(); 4637 } 4638 4639 handleMacroExit(); 4640 return false; 4641 } 4642 4643 /// parseDirectiveEndMacro 4644 /// ::= .endm 4645 /// ::= .endmacro 4646 bool AsmParser::parseDirectiveEndMacro(StringRef Directive) { 4647 if (getLexer().isNot(AsmToken::EndOfStatement)) 4648 return TokError("unexpected token in '" + Directive + "' directive"); 4649 4650 // If we are inside a macro instantiation, terminate the current 4651 // instantiation. 4652 if (isInsideMacroInstantiation()) { 4653 handleMacroExit(); 4654 return false; 4655 } 4656 4657 // Otherwise, this .endmacro is a stray entry in the file; well formed 4658 // .endmacro directives are handled during the macro definition parsing. 4659 return TokError("unexpected '" + Directive + "' in file, " 4660 "no current macro definition"); 4661 } 4662 4663 /// parseDirectivePurgeMacro 4664 /// ::= .purgem name 4665 bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) { 4666 StringRef Name; 4667 SMLoc Loc; 4668 if (parseTokenLoc(Loc) || 4669 check(parseIdentifier(Name), Loc, 4670 "expected identifier in '.purgem' directive") || 4671 parseEOL()) 4672 return true; 4673 4674 if (!getContext().lookupMacro(Name)) 4675 return Error(DirectiveLoc, "macro '" + Name + "' is not defined"); 4676 4677 getContext().undefineMacro(Name); 4678 DEBUG_WITH_TYPE("asm-macros", dbgs() 4679 << "Un-defining macro: " << Name << "\n"); 4680 return false; 4681 } 4682 4683 /// parseDirectiveBundleAlignMode 4684 /// ::= {.bundle_align_mode} expression 4685 bool AsmParser::parseDirectiveBundleAlignMode() { 4686 // Expect a single argument: an expression that evaluates to a constant 4687 // in the inclusive range 0-30. 4688 SMLoc ExprLoc = getLexer().getLoc(); 4689 int64_t AlignSizePow2; 4690 if (checkForValidSection() || parseAbsoluteExpression(AlignSizePow2) || 4691 parseEOL() || 4692 check(AlignSizePow2 < 0 || AlignSizePow2 > 30, ExprLoc, 4693 "invalid bundle alignment size (expected between 0 and 30)")) 4694 return true; 4695 4696 // Because of AlignSizePow2's verified range we can safely truncate it to 4697 // unsigned. 4698 getStreamer().emitBundleAlignMode(static_cast<unsigned>(AlignSizePow2)); 4699 return false; 4700 } 4701 4702 /// parseDirectiveBundleLock 4703 /// ::= {.bundle_lock} [align_to_end] 4704 bool AsmParser::parseDirectiveBundleLock() { 4705 if (checkForValidSection()) 4706 return true; 4707 bool AlignToEnd = false; 4708 4709 StringRef Option; 4710 SMLoc Loc = getTok().getLoc(); 4711 const char *kInvalidOptionError = 4712 "invalid option for '.bundle_lock' directive"; 4713 4714 if (!parseOptionalToken(AsmToken::EndOfStatement)) { 4715 if (check(parseIdentifier(Option), Loc, kInvalidOptionError) || 4716 check(Option != "align_to_end", Loc, kInvalidOptionError) || parseEOL()) 4717 return true; 4718 AlignToEnd = true; 4719 } 4720 4721 getStreamer().emitBundleLock(AlignToEnd); 4722 return false; 4723 } 4724 4725 /// parseDirectiveBundleLock 4726 /// ::= {.bundle_lock} 4727 bool AsmParser::parseDirectiveBundleUnlock() { 4728 if (checkForValidSection() || parseEOL()) 4729 return true; 4730 4731 getStreamer().emitBundleUnlock(); 4732 return false; 4733 } 4734 4735 /// parseDirectiveSpace 4736 /// ::= (.skip | .space) expression [ , expression ] 4737 bool AsmParser::parseDirectiveSpace(StringRef IDVal) { 4738 SMLoc NumBytesLoc = Lexer.getLoc(); 4739 const MCExpr *NumBytes; 4740 if (checkForValidSection() || parseExpression(NumBytes)) 4741 return true; 4742 4743 int64_t FillExpr = 0; 4744 if (parseOptionalToken(AsmToken::Comma)) 4745 if (parseAbsoluteExpression(FillExpr)) 4746 return addErrorSuffix("in '" + Twine(IDVal) + "' directive"); 4747 if (parseEOL()) 4748 return addErrorSuffix("in '" + Twine(IDVal) + "' directive"); 4749 4750 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0. 4751 getStreamer().emitFill(*NumBytes, FillExpr, NumBytesLoc); 4752 4753 return false; 4754 } 4755 4756 /// parseDirectiveDCB 4757 /// ::= .dcb.{b, l, w} expression, expression 4758 bool AsmParser::parseDirectiveDCB(StringRef IDVal, unsigned Size) { 4759 SMLoc NumValuesLoc = Lexer.getLoc(); 4760 int64_t NumValues; 4761 if (checkForValidSection() || parseAbsoluteExpression(NumValues)) 4762 return true; 4763 4764 if (NumValues < 0) { 4765 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect"); 4766 return false; 4767 } 4768 4769 if (parseToken(AsmToken::Comma, 4770 "unexpected token in '" + Twine(IDVal) + "' directive")) 4771 return true; 4772 4773 const MCExpr *Value; 4774 SMLoc ExprLoc = getLexer().getLoc(); 4775 if (parseExpression(Value)) 4776 return true; 4777 4778 // Special case constant expressions to match code generator. 4779 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) { 4780 assert(Size <= 8 && "Invalid size"); 4781 uint64_t IntValue = MCE->getValue(); 4782 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue)) 4783 return Error(ExprLoc, "literal value out of range for directive"); 4784 for (uint64_t i = 0, e = NumValues; i != e; ++i) 4785 getStreamer().emitIntValue(IntValue, Size); 4786 } else { 4787 for (uint64_t i = 0, e = NumValues; i != e; ++i) 4788 getStreamer().emitValue(Value, Size, ExprLoc); 4789 } 4790 4791 return parseEOL(); 4792 } 4793 4794 /// parseDirectiveRealDCB 4795 /// ::= .dcb.{d, s} expression, expression 4796 bool AsmParser::parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &Semantics) { 4797 SMLoc NumValuesLoc = Lexer.getLoc(); 4798 int64_t NumValues; 4799 if (checkForValidSection() || parseAbsoluteExpression(NumValues)) 4800 return true; 4801 4802 if (NumValues < 0) { 4803 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect"); 4804 return false; 4805 } 4806 4807 if (parseToken(AsmToken::Comma, 4808 "unexpected token in '" + Twine(IDVal) + "' directive")) 4809 return true; 4810 4811 APInt AsInt; 4812 if (parseRealValue(Semantics, AsInt) || parseEOL()) 4813 return true; 4814 4815 for (uint64_t i = 0, e = NumValues; i != e; ++i) 4816 getStreamer().emitIntValue(AsInt.getLimitedValue(), 4817 AsInt.getBitWidth() / 8); 4818 4819 return false; 4820 } 4821 4822 /// parseDirectiveDS 4823 /// ::= .ds.{b, d, l, p, s, w, x} expression 4824 bool AsmParser::parseDirectiveDS(StringRef IDVal, unsigned Size) { 4825 SMLoc NumValuesLoc = Lexer.getLoc(); 4826 int64_t NumValues; 4827 if (checkForValidSection() || parseAbsoluteExpression(NumValues) || 4828 parseEOL()) 4829 return true; 4830 4831 if (NumValues < 0) { 4832 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect"); 4833 return false; 4834 } 4835 4836 for (uint64_t i = 0, e = NumValues; i != e; ++i) 4837 getStreamer().emitFill(Size, 0); 4838 4839 return false; 4840 } 4841 4842 /// parseDirectiveLEB128 4843 /// ::= (.sleb128 | .uleb128) [ expression (, expression)* ] 4844 bool AsmParser::parseDirectiveLEB128(bool Signed) { 4845 if (checkForValidSection()) 4846 return true; 4847 4848 auto parseOp = [&]() -> bool { 4849 const MCExpr *Value; 4850 if (parseExpression(Value)) 4851 return true; 4852 if (Signed) 4853 getStreamer().emitSLEB128Value(Value); 4854 else 4855 getStreamer().emitULEB128Value(Value); 4856 return false; 4857 }; 4858 4859 if (parseMany(parseOp)) 4860 return addErrorSuffix(" in directive"); 4861 4862 return false; 4863 } 4864 4865 /// parseDirectiveSymbolAttribute 4866 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ] 4867 bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) { 4868 auto parseOp = [&]() -> bool { 4869 StringRef Name; 4870 SMLoc Loc = getTok().getLoc(); 4871 if (parseIdentifier(Name)) 4872 return Error(Loc, "expected identifier"); 4873 MCSymbol *Sym = getContext().getOrCreateSymbol(Name); 4874 4875 // Assembler local symbols don't make any sense here. Complain loudly. 4876 if (Sym->isTemporary()) 4877 return Error(Loc, "non-local symbol required"); 4878 4879 if (!getStreamer().emitSymbolAttribute(Sym, Attr)) 4880 return Error(Loc, "unable to emit symbol attribute"); 4881 return false; 4882 }; 4883 4884 if (parseMany(parseOp)) 4885 return addErrorSuffix(" in directive"); 4886 return false; 4887 } 4888 4889 /// parseDirectiveComm 4890 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ] 4891 bool AsmParser::parseDirectiveComm(bool IsLocal) { 4892 if (checkForValidSection()) 4893 return true; 4894 4895 SMLoc IDLoc = getLexer().getLoc(); 4896 StringRef Name; 4897 if (parseIdentifier(Name)) 4898 return TokError("expected identifier in directive"); 4899 4900 // Handle the identifier as the key symbol. 4901 MCSymbol *Sym = getContext().getOrCreateSymbol(Name); 4902 4903 if (getLexer().isNot(AsmToken::Comma)) 4904 return TokError("unexpected token in directive"); 4905 Lex(); 4906 4907 int64_t Size; 4908 SMLoc SizeLoc = getLexer().getLoc(); 4909 if (parseAbsoluteExpression(Size)) 4910 return true; 4911 4912 int64_t Pow2Alignment = 0; 4913 SMLoc Pow2AlignmentLoc; 4914 if (getLexer().is(AsmToken::Comma)) { 4915 Lex(); 4916 Pow2AlignmentLoc = getLexer().getLoc(); 4917 if (parseAbsoluteExpression(Pow2Alignment)) 4918 return true; 4919 4920 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType(); 4921 if (IsLocal && LCOMM == LCOMM::NoAlignment) 4922 return Error(Pow2AlignmentLoc, "alignment not supported on this target"); 4923 4924 // If this target takes alignments in bytes (not log) validate and convert. 4925 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) || 4926 (IsLocal && LCOMM == LCOMM::ByteAlignment)) { 4927 if (!isPowerOf2_64(Pow2Alignment)) 4928 return Error(Pow2AlignmentLoc, "alignment must be a power of 2"); 4929 Pow2Alignment = Log2_64(Pow2Alignment); 4930 } 4931 } 4932 4933 if (parseEOL()) 4934 return true; 4935 4936 // NOTE: a size of zero for a .comm should create a undefined symbol 4937 // but a size of .lcomm creates a bss symbol of size zero. 4938 if (Size < 0) 4939 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't " 4940 "be less than zero"); 4941 4942 // NOTE: The alignment in the directive is a power of 2 value, the assembler 4943 // may internally end up wanting an alignment in bytes. 4944 // FIXME: Diagnose overflow. 4945 if (Pow2Alignment < 0) 4946 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive " 4947 "alignment, can't be less than zero"); 4948 4949 Sym->redefineIfPossible(); 4950 if (!Sym->isUndefined()) 4951 return Error(IDLoc, "invalid symbol redefinition"); 4952 4953 // Create the Symbol as a common or local common with Size and Pow2Alignment 4954 if (IsLocal) { 4955 getStreamer().emitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment); 4956 return false; 4957 } 4958 4959 getStreamer().emitCommonSymbol(Sym, Size, 1 << Pow2Alignment); 4960 return false; 4961 } 4962 4963 /// parseDirectiveAbort 4964 /// ::= .abort [... message ...] 4965 bool AsmParser::parseDirectiveAbort() { 4966 // FIXME: Use loc from directive. 4967 SMLoc Loc = getLexer().getLoc(); 4968 4969 StringRef Str = parseStringToEndOfStatement(); 4970 if (parseEOL()) 4971 return true; 4972 4973 if (Str.empty()) 4974 return Error(Loc, ".abort detected. Assembly stopping."); 4975 else 4976 return Error(Loc, ".abort '" + Str + "' detected. Assembly stopping."); 4977 // FIXME: Actually abort assembly here. 4978 4979 return false; 4980 } 4981 4982 /// parseDirectiveInclude 4983 /// ::= .include "filename" 4984 bool AsmParser::parseDirectiveInclude() { 4985 // Allow the strings to have escaped octal character sequence. 4986 std::string Filename; 4987 SMLoc IncludeLoc = getTok().getLoc(); 4988 4989 if (check(getTok().isNot(AsmToken::String), 4990 "expected string in '.include' directive") || 4991 parseEscapedString(Filename) || 4992 check(getTok().isNot(AsmToken::EndOfStatement), 4993 "unexpected token in '.include' directive") || 4994 // Attempt to switch the lexer to the included file before consuming the 4995 // end of statement to avoid losing it when we switch. 4996 check(enterIncludeFile(Filename), IncludeLoc, 4997 "Could not find include file '" + Filename + "'")) 4998 return true; 4999 5000 return false; 5001 } 5002 5003 /// parseDirectiveIncbin 5004 /// ::= .incbin "filename" [ , skip [ , count ] ] 5005 bool AsmParser::parseDirectiveIncbin() { 5006 // Allow the strings to have escaped octal character sequence. 5007 std::string Filename; 5008 SMLoc IncbinLoc = getTok().getLoc(); 5009 if (check(getTok().isNot(AsmToken::String), 5010 "expected string in '.incbin' directive") || 5011 parseEscapedString(Filename)) 5012 return true; 5013 5014 int64_t Skip = 0; 5015 const MCExpr *Count = nullptr; 5016 SMLoc SkipLoc, CountLoc; 5017 if (parseOptionalToken(AsmToken::Comma)) { 5018 // The skip expression can be omitted while specifying the count, e.g: 5019 // .incbin "filename",,4 5020 if (getTok().isNot(AsmToken::Comma)) { 5021 if (parseTokenLoc(SkipLoc) || parseAbsoluteExpression(Skip)) 5022 return true; 5023 } 5024 if (parseOptionalToken(AsmToken::Comma)) { 5025 CountLoc = getTok().getLoc(); 5026 if (parseExpression(Count)) 5027 return true; 5028 } 5029 } 5030 5031 if (parseEOL()) 5032 return true; 5033 5034 if (check(Skip < 0, SkipLoc, "skip is negative")) 5035 return true; 5036 5037 // Attempt to process the included file. 5038 if (processIncbinFile(Filename, Skip, Count, CountLoc)) 5039 return Error(IncbinLoc, "Could not find incbin file '" + Filename + "'"); 5040 return false; 5041 } 5042 5043 /// parseDirectiveIf 5044 /// ::= .if{,eq,ge,gt,le,lt,ne} expression 5045 bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) { 5046 TheCondStack.push_back(TheCondState); 5047 TheCondState.TheCond = AsmCond::IfCond; 5048 if (TheCondState.Ignore) { 5049 eatToEndOfStatement(); 5050 } else { 5051 int64_t ExprValue; 5052 if (parseAbsoluteExpression(ExprValue) || parseEOL()) 5053 return true; 5054 5055 switch (DirKind) { 5056 default: 5057 llvm_unreachable("unsupported directive"); 5058 case DK_IF: 5059 case DK_IFNE: 5060 break; 5061 case DK_IFEQ: 5062 ExprValue = ExprValue == 0; 5063 break; 5064 case DK_IFGE: 5065 ExprValue = ExprValue >= 0; 5066 break; 5067 case DK_IFGT: 5068 ExprValue = ExprValue > 0; 5069 break; 5070 case DK_IFLE: 5071 ExprValue = ExprValue <= 0; 5072 break; 5073 case DK_IFLT: 5074 ExprValue = ExprValue < 0; 5075 break; 5076 } 5077 5078 TheCondState.CondMet = ExprValue; 5079 TheCondState.Ignore = !TheCondState.CondMet; 5080 } 5081 5082 return false; 5083 } 5084 5085 /// parseDirectiveIfb 5086 /// ::= .ifb string 5087 bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) { 5088 TheCondStack.push_back(TheCondState); 5089 TheCondState.TheCond = AsmCond::IfCond; 5090 5091 if (TheCondState.Ignore) { 5092 eatToEndOfStatement(); 5093 } else { 5094 StringRef Str = parseStringToEndOfStatement(); 5095 5096 if (parseEOL()) 5097 return true; 5098 5099 TheCondState.CondMet = ExpectBlank == Str.empty(); 5100 TheCondState.Ignore = !TheCondState.CondMet; 5101 } 5102 5103 return false; 5104 } 5105 5106 /// parseDirectiveIfc 5107 /// ::= .ifc string1, string2 5108 /// ::= .ifnc string1, string2 5109 bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) { 5110 TheCondStack.push_back(TheCondState); 5111 TheCondState.TheCond = AsmCond::IfCond; 5112 5113 if (TheCondState.Ignore) { 5114 eatToEndOfStatement(); 5115 } else { 5116 StringRef Str1 = parseStringToComma(); 5117 5118 if (parseToken(AsmToken::Comma, "unexpected token in '.ifc' directive")) 5119 return true; 5120 5121 StringRef Str2 = parseStringToEndOfStatement(); 5122 5123 if (parseEOL()) 5124 return true; 5125 5126 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim()); 5127 TheCondState.Ignore = !TheCondState.CondMet; 5128 } 5129 5130 return false; 5131 } 5132 5133 /// parseDirectiveIfeqs 5134 /// ::= .ifeqs string1, string2 5135 bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) { 5136 if (Lexer.isNot(AsmToken::String)) { 5137 if (ExpectEqual) 5138 return TokError("expected string parameter for '.ifeqs' directive"); 5139 return TokError("expected string parameter for '.ifnes' directive"); 5140 } 5141 5142 StringRef String1 = getTok().getStringContents(); 5143 Lex(); 5144 5145 if (Lexer.isNot(AsmToken::Comma)) { 5146 if (ExpectEqual) 5147 return TokError( 5148 "expected comma after first string for '.ifeqs' directive"); 5149 return TokError("expected comma after first string for '.ifnes' directive"); 5150 } 5151 5152 Lex(); 5153 5154 if (Lexer.isNot(AsmToken::String)) { 5155 if (ExpectEqual) 5156 return TokError("expected string parameter for '.ifeqs' directive"); 5157 return TokError("expected string parameter for '.ifnes' directive"); 5158 } 5159 5160 StringRef String2 = getTok().getStringContents(); 5161 Lex(); 5162 5163 TheCondStack.push_back(TheCondState); 5164 TheCondState.TheCond = AsmCond::IfCond; 5165 TheCondState.CondMet = ExpectEqual == (String1 == String2); 5166 TheCondState.Ignore = !TheCondState.CondMet; 5167 5168 return false; 5169 } 5170 5171 /// parseDirectiveIfdef 5172 /// ::= .ifdef symbol 5173 bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) { 5174 StringRef Name; 5175 TheCondStack.push_back(TheCondState); 5176 TheCondState.TheCond = AsmCond::IfCond; 5177 5178 if (TheCondState.Ignore) { 5179 eatToEndOfStatement(); 5180 } else { 5181 if (check(parseIdentifier(Name), "expected identifier after '.ifdef'") || 5182 parseEOL()) 5183 return true; 5184 5185 MCSymbol *Sym = getContext().lookupSymbol(Name); 5186 5187 if (expect_defined) 5188 TheCondState.CondMet = (Sym && !Sym->isUndefined(false)); 5189 else 5190 TheCondState.CondMet = (!Sym || Sym->isUndefined(false)); 5191 TheCondState.Ignore = !TheCondState.CondMet; 5192 } 5193 5194 return false; 5195 } 5196 5197 /// parseDirectiveElseIf 5198 /// ::= .elseif expression 5199 bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) { 5200 if (TheCondState.TheCond != AsmCond::IfCond && 5201 TheCondState.TheCond != AsmCond::ElseIfCond) 5202 return Error(DirectiveLoc, "Encountered a .elseif that doesn't follow an" 5203 " .if or an .elseif"); 5204 TheCondState.TheCond = AsmCond::ElseIfCond; 5205 5206 bool LastIgnoreState = false; 5207 if (!TheCondStack.empty()) 5208 LastIgnoreState = TheCondStack.back().Ignore; 5209 if (LastIgnoreState || TheCondState.CondMet) { 5210 TheCondState.Ignore = true; 5211 eatToEndOfStatement(); 5212 } else { 5213 int64_t ExprValue; 5214 if (parseAbsoluteExpression(ExprValue)) 5215 return true; 5216 5217 if (parseEOL()) 5218 return true; 5219 5220 TheCondState.CondMet = ExprValue; 5221 TheCondState.Ignore = !TheCondState.CondMet; 5222 } 5223 5224 return false; 5225 } 5226 5227 /// parseDirectiveElse 5228 /// ::= .else 5229 bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) { 5230 if (parseEOL()) 5231 return true; 5232 5233 if (TheCondState.TheCond != AsmCond::IfCond && 5234 TheCondState.TheCond != AsmCond::ElseIfCond) 5235 return Error(DirectiveLoc, "Encountered a .else that doesn't follow " 5236 " an .if or an .elseif"); 5237 TheCondState.TheCond = AsmCond::ElseCond; 5238 bool LastIgnoreState = false; 5239 if (!TheCondStack.empty()) 5240 LastIgnoreState = TheCondStack.back().Ignore; 5241 if (LastIgnoreState || TheCondState.CondMet) 5242 TheCondState.Ignore = true; 5243 else 5244 TheCondState.Ignore = false; 5245 5246 return false; 5247 } 5248 5249 /// parseDirectiveEnd 5250 /// ::= .end 5251 bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) { 5252 if (parseEOL()) 5253 return true; 5254 5255 while (Lexer.isNot(AsmToken::Eof)) 5256 Lexer.Lex(); 5257 5258 return false; 5259 } 5260 5261 /// parseDirectiveError 5262 /// ::= .err 5263 /// ::= .error [string] 5264 bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) { 5265 if (!TheCondStack.empty()) { 5266 if (TheCondStack.back().Ignore) { 5267 eatToEndOfStatement(); 5268 return false; 5269 } 5270 } 5271 5272 if (!WithMessage) 5273 return Error(L, ".err encountered"); 5274 5275 StringRef Message = ".error directive invoked in source file"; 5276 if (Lexer.isNot(AsmToken::EndOfStatement)) { 5277 if (Lexer.isNot(AsmToken::String)) 5278 return TokError(".error argument must be a string"); 5279 5280 Message = getTok().getStringContents(); 5281 Lex(); 5282 } 5283 5284 return Error(L, Message); 5285 } 5286 5287 /// parseDirectiveWarning 5288 /// ::= .warning [string] 5289 bool AsmParser::parseDirectiveWarning(SMLoc L) { 5290 if (!TheCondStack.empty()) { 5291 if (TheCondStack.back().Ignore) { 5292 eatToEndOfStatement(); 5293 return false; 5294 } 5295 } 5296 5297 StringRef Message = ".warning directive invoked in source file"; 5298 5299 if (!parseOptionalToken(AsmToken::EndOfStatement)) { 5300 if (Lexer.isNot(AsmToken::String)) 5301 return TokError(".warning argument must be a string"); 5302 5303 Message = getTok().getStringContents(); 5304 Lex(); 5305 if (parseEOL()) 5306 return true; 5307 } 5308 5309 return Warning(L, Message); 5310 } 5311 5312 /// parseDirectiveEndIf 5313 /// ::= .endif 5314 bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) { 5315 if (parseEOL()) 5316 return true; 5317 5318 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty()) 5319 return Error(DirectiveLoc, "Encountered a .endif that doesn't follow " 5320 "an .if or .else"); 5321 if (!TheCondStack.empty()) { 5322 TheCondState = TheCondStack.back(); 5323 TheCondStack.pop_back(); 5324 } 5325 5326 return false; 5327 } 5328 5329 void AsmParser::initializeDirectiveKindMap() { 5330 /* Lookup will be done with the directive 5331 * converted to lower case, so all these 5332 * keys should be lower case. 5333 * (target specific directives are handled 5334 * elsewhere) 5335 */ 5336 DirectiveKindMap[".set"] = DK_SET; 5337 DirectiveKindMap[".equ"] = DK_EQU; 5338 DirectiveKindMap[".equiv"] = DK_EQUIV; 5339 DirectiveKindMap[".ascii"] = DK_ASCII; 5340 DirectiveKindMap[".asciz"] = DK_ASCIZ; 5341 DirectiveKindMap[".string"] = DK_STRING; 5342 DirectiveKindMap[".byte"] = DK_BYTE; 5343 DirectiveKindMap[".short"] = DK_SHORT; 5344 DirectiveKindMap[".value"] = DK_VALUE; 5345 DirectiveKindMap[".2byte"] = DK_2BYTE; 5346 DirectiveKindMap[".long"] = DK_LONG; 5347 DirectiveKindMap[".int"] = DK_INT; 5348 DirectiveKindMap[".4byte"] = DK_4BYTE; 5349 DirectiveKindMap[".quad"] = DK_QUAD; 5350 DirectiveKindMap[".8byte"] = DK_8BYTE; 5351 DirectiveKindMap[".octa"] = DK_OCTA; 5352 DirectiveKindMap[".single"] = DK_SINGLE; 5353 DirectiveKindMap[".float"] = DK_FLOAT; 5354 DirectiveKindMap[".double"] = DK_DOUBLE; 5355 DirectiveKindMap[".align"] = DK_ALIGN; 5356 DirectiveKindMap[".align32"] = DK_ALIGN32; 5357 DirectiveKindMap[".balign"] = DK_BALIGN; 5358 DirectiveKindMap[".balignw"] = DK_BALIGNW; 5359 DirectiveKindMap[".balignl"] = DK_BALIGNL; 5360 DirectiveKindMap[".p2align"] = DK_P2ALIGN; 5361 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW; 5362 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL; 5363 DirectiveKindMap[".org"] = DK_ORG; 5364 DirectiveKindMap[".fill"] = DK_FILL; 5365 DirectiveKindMap[".zero"] = DK_ZERO; 5366 DirectiveKindMap[".extern"] = DK_EXTERN; 5367 DirectiveKindMap[".globl"] = DK_GLOBL; 5368 DirectiveKindMap[".global"] = DK_GLOBAL; 5369 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE; 5370 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP; 5371 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER; 5372 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN; 5373 DirectiveKindMap[".reference"] = DK_REFERENCE; 5374 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION; 5375 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE; 5376 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN; 5377 DirectiveKindMap[".cold"] = DK_COLD; 5378 DirectiveKindMap[".comm"] = DK_COMM; 5379 DirectiveKindMap[".common"] = DK_COMMON; 5380 DirectiveKindMap[".lcomm"] = DK_LCOMM; 5381 DirectiveKindMap[".abort"] = DK_ABORT; 5382 DirectiveKindMap[".include"] = DK_INCLUDE; 5383 DirectiveKindMap[".incbin"] = DK_INCBIN; 5384 DirectiveKindMap[".code16"] = DK_CODE16; 5385 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC; 5386 DirectiveKindMap[".rept"] = DK_REPT; 5387 DirectiveKindMap[".rep"] = DK_REPT; 5388 DirectiveKindMap[".irp"] = DK_IRP; 5389 DirectiveKindMap[".irpc"] = DK_IRPC; 5390 DirectiveKindMap[".endr"] = DK_ENDR; 5391 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE; 5392 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK; 5393 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK; 5394 DirectiveKindMap[".if"] = DK_IF; 5395 DirectiveKindMap[".ifeq"] = DK_IFEQ; 5396 DirectiveKindMap[".ifge"] = DK_IFGE; 5397 DirectiveKindMap[".ifgt"] = DK_IFGT; 5398 DirectiveKindMap[".ifle"] = DK_IFLE; 5399 DirectiveKindMap[".iflt"] = DK_IFLT; 5400 DirectiveKindMap[".ifne"] = DK_IFNE; 5401 DirectiveKindMap[".ifb"] = DK_IFB; 5402 DirectiveKindMap[".ifnb"] = DK_IFNB; 5403 DirectiveKindMap[".ifc"] = DK_IFC; 5404 DirectiveKindMap[".ifeqs"] = DK_IFEQS; 5405 DirectiveKindMap[".ifnc"] = DK_IFNC; 5406 DirectiveKindMap[".ifnes"] = DK_IFNES; 5407 DirectiveKindMap[".ifdef"] = DK_IFDEF; 5408 DirectiveKindMap[".ifndef"] = DK_IFNDEF; 5409 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF; 5410 DirectiveKindMap[".elseif"] = DK_ELSEIF; 5411 DirectiveKindMap[".else"] = DK_ELSE; 5412 DirectiveKindMap[".end"] = DK_END; 5413 DirectiveKindMap[".endif"] = DK_ENDIF; 5414 DirectiveKindMap[".skip"] = DK_SKIP; 5415 DirectiveKindMap[".space"] = DK_SPACE; 5416 DirectiveKindMap[".file"] = DK_FILE; 5417 DirectiveKindMap[".line"] = DK_LINE; 5418 DirectiveKindMap[".loc"] = DK_LOC; 5419 DirectiveKindMap[".stabs"] = DK_STABS; 5420 DirectiveKindMap[".cv_file"] = DK_CV_FILE; 5421 DirectiveKindMap[".cv_func_id"] = DK_CV_FUNC_ID; 5422 DirectiveKindMap[".cv_loc"] = DK_CV_LOC; 5423 DirectiveKindMap[".cv_linetable"] = DK_CV_LINETABLE; 5424 DirectiveKindMap[".cv_inline_linetable"] = DK_CV_INLINE_LINETABLE; 5425 DirectiveKindMap[".cv_inline_site_id"] = DK_CV_INLINE_SITE_ID; 5426 DirectiveKindMap[".cv_def_range"] = DK_CV_DEF_RANGE; 5427 DirectiveKindMap[".cv_string"] = DK_CV_STRING; 5428 DirectiveKindMap[".cv_stringtable"] = DK_CV_STRINGTABLE; 5429 DirectiveKindMap[".cv_filechecksums"] = DK_CV_FILECHECKSUMS; 5430 DirectiveKindMap[".cv_filechecksumoffset"] = DK_CV_FILECHECKSUM_OFFSET; 5431 DirectiveKindMap[".cv_fpo_data"] = DK_CV_FPO_DATA; 5432 DirectiveKindMap[".sleb128"] = DK_SLEB128; 5433 DirectiveKindMap[".uleb128"] = DK_ULEB128; 5434 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS; 5435 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC; 5436 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC; 5437 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA; 5438 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET; 5439 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET; 5440 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER; 5441 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET; 5442 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET; 5443 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY; 5444 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA; 5445 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE; 5446 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE; 5447 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE; 5448 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE; 5449 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE; 5450 DirectiveKindMap[".cfi_return_column"] = DK_CFI_RETURN_COLUMN; 5451 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME; 5452 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED; 5453 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER; 5454 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE; 5455 DirectiveKindMap[".cfi_b_key_frame"] = DK_CFI_B_KEY_FRAME; 5456 DirectiveKindMap[".macros_on"] = DK_MACROS_ON; 5457 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF; 5458 DirectiveKindMap[".macro"] = DK_MACRO; 5459 DirectiveKindMap[".exitm"] = DK_EXITM; 5460 DirectiveKindMap[".endm"] = DK_ENDM; 5461 DirectiveKindMap[".endmacro"] = DK_ENDMACRO; 5462 DirectiveKindMap[".purgem"] = DK_PURGEM; 5463 DirectiveKindMap[".err"] = DK_ERR; 5464 DirectiveKindMap[".error"] = DK_ERROR; 5465 DirectiveKindMap[".warning"] = DK_WARNING; 5466 DirectiveKindMap[".altmacro"] = DK_ALTMACRO; 5467 DirectiveKindMap[".noaltmacro"] = DK_NOALTMACRO; 5468 DirectiveKindMap[".reloc"] = DK_RELOC; 5469 DirectiveKindMap[".dc"] = DK_DC; 5470 DirectiveKindMap[".dc.a"] = DK_DC_A; 5471 DirectiveKindMap[".dc.b"] = DK_DC_B; 5472 DirectiveKindMap[".dc.d"] = DK_DC_D; 5473 DirectiveKindMap[".dc.l"] = DK_DC_L; 5474 DirectiveKindMap[".dc.s"] = DK_DC_S; 5475 DirectiveKindMap[".dc.w"] = DK_DC_W; 5476 DirectiveKindMap[".dc.x"] = DK_DC_X; 5477 DirectiveKindMap[".dcb"] = DK_DCB; 5478 DirectiveKindMap[".dcb.b"] = DK_DCB_B; 5479 DirectiveKindMap[".dcb.d"] = DK_DCB_D; 5480 DirectiveKindMap[".dcb.l"] = DK_DCB_L; 5481 DirectiveKindMap[".dcb.s"] = DK_DCB_S; 5482 DirectiveKindMap[".dcb.w"] = DK_DCB_W; 5483 DirectiveKindMap[".dcb.x"] = DK_DCB_X; 5484 DirectiveKindMap[".ds"] = DK_DS; 5485 DirectiveKindMap[".ds.b"] = DK_DS_B; 5486 DirectiveKindMap[".ds.d"] = DK_DS_D; 5487 DirectiveKindMap[".ds.l"] = DK_DS_L; 5488 DirectiveKindMap[".ds.p"] = DK_DS_P; 5489 DirectiveKindMap[".ds.s"] = DK_DS_S; 5490 DirectiveKindMap[".ds.w"] = DK_DS_W; 5491 DirectiveKindMap[".ds.x"] = DK_DS_X; 5492 DirectiveKindMap[".print"] = DK_PRINT; 5493 DirectiveKindMap[".addrsig"] = DK_ADDRSIG; 5494 DirectiveKindMap[".addrsig_sym"] = DK_ADDRSIG_SYM; 5495 DirectiveKindMap[".pseudoprobe"] = DK_PSEUDO_PROBE; 5496 } 5497 5498 MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) { 5499 AsmToken EndToken, StartToken = getTok(); 5500 5501 unsigned NestLevel = 0; 5502 while (true) { 5503 // Check whether we have reached the end of the file. 5504 if (getLexer().is(AsmToken::Eof)) { 5505 printError(DirectiveLoc, "no matching '.endr' in definition"); 5506 return nullptr; 5507 } 5508 5509 if (Lexer.is(AsmToken::Identifier) && 5510 (getTok().getIdentifier() == ".rep" || 5511 getTok().getIdentifier() == ".rept" || 5512 getTok().getIdentifier() == ".irp" || 5513 getTok().getIdentifier() == ".irpc")) { 5514 ++NestLevel; 5515 } 5516 5517 // Otherwise, check whether we have reached the .endr. 5518 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") { 5519 if (NestLevel == 0) { 5520 EndToken = getTok(); 5521 Lex(); 5522 if (Lexer.isNot(AsmToken::EndOfStatement)) { 5523 printError(getTok().getLoc(), 5524 "unexpected token in '.endr' directive"); 5525 return nullptr; 5526 } 5527 break; 5528 } 5529 --NestLevel; 5530 } 5531 5532 // Otherwise, scan till the end of the statement. 5533 eatToEndOfStatement(); 5534 } 5535 5536 const char *BodyStart = StartToken.getLoc().getPointer(); 5537 const char *BodyEnd = EndToken.getLoc().getPointer(); 5538 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart); 5539 5540 // We Are Anonymous. 5541 MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters()); 5542 return &MacroLikeBodies.back(); 5543 } 5544 5545 void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc, 5546 raw_svector_ostream &OS) { 5547 OS << ".endr\n"; 5548 5549 std::unique_ptr<MemoryBuffer> Instantiation = 5550 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>"); 5551 5552 // Create the macro instantiation object and add to the current macro 5553 // instantiation stack. 5554 MacroInstantiation *MI = new MacroInstantiation{ 5555 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size()}; 5556 ActiveMacros.push_back(MI); 5557 5558 // Jump to the macro instantiation and prime the lexer. 5559 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc()); 5560 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer()); 5561 Lex(); 5562 } 5563 5564 /// parseDirectiveRept 5565 /// ::= .rep | .rept count 5566 bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) { 5567 const MCExpr *CountExpr; 5568 SMLoc CountLoc = getTok().getLoc(); 5569 if (parseExpression(CountExpr)) 5570 return true; 5571 5572 int64_t Count; 5573 if (!CountExpr->evaluateAsAbsolute(Count, getStreamer().getAssemblerPtr())) { 5574 return Error(CountLoc, "unexpected token in '" + Dir + "' directive"); 5575 } 5576 5577 if (check(Count < 0, CountLoc, "Count is negative") || parseEOL()) 5578 return true; 5579 5580 // Lex the rept definition. 5581 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc); 5582 if (!M) 5583 return true; 5584 5585 // Macro instantiation is lexical, unfortunately. We construct a new buffer 5586 // to hold the macro body with substitutions. 5587 SmallString<256> Buf; 5588 raw_svector_ostream OS(Buf); 5589 while (Count--) { 5590 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t). 5591 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc())) 5592 return true; 5593 } 5594 instantiateMacroLikeBody(M, DirectiveLoc, OS); 5595 5596 return false; 5597 } 5598 5599 /// parseDirectiveIrp 5600 /// ::= .irp symbol,values 5601 bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) { 5602 MCAsmMacroParameter Parameter; 5603 MCAsmMacroArguments A; 5604 if (check(parseIdentifier(Parameter.Name), 5605 "expected identifier in '.irp' directive") || 5606 parseToken(AsmToken::Comma, "expected comma in '.irp' directive") || 5607 parseMacroArguments(nullptr, A) || parseEOL()) 5608 return true; 5609 5610 // Lex the irp definition. 5611 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc); 5612 if (!M) 5613 return true; 5614 5615 // Macro instantiation is lexical, unfortunately. We construct a new buffer 5616 // to hold the macro body with substitutions. 5617 SmallString<256> Buf; 5618 raw_svector_ostream OS(Buf); 5619 5620 for (const MCAsmMacroArgument &Arg : A) { 5621 // Note that the AtPseudoVariable is enabled for instantiations of .irp. 5622 // This is undocumented, but GAS seems to support it. 5623 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc())) 5624 return true; 5625 } 5626 5627 instantiateMacroLikeBody(M, DirectiveLoc, OS); 5628 5629 return false; 5630 } 5631 5632 /// parseDirectiveIrpc 5633 /// ::= .irpc symbol,values 5634 bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) { 5635 MCAsmMacroParameter Parameter; 5636 MCAsmMacroArguments A; 5637 5638 if (check(parseIdentifier(Parameter.Name), 5639 "expected identifier in '.irpc' directive") || 5640 parseToken(AsmToken::Comma, "expected comma in '.irpc' directive") || 5641 parseMacroArguments(nullptr, A)) 5642 return true; 5643 5644 if (A.size() != 1 || A.front().size() != 1) 5645 return TokError("unexpected token in '.irpc' directive"); 5646 if (parseEOL()) 5647 return true; 5648 5649 // Lex the irpc definition. 5650 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc); 5651 if (!M) 5652 return true; 5653 5654 // Macro instantiation is lexical, unfortunately. We construct a new buffer 5655 // to hold the macro body with substitutions. 5656 SmallString<256> Buf; 5657 raw_svector_ostream OS(Buf); 5658 5659 StringRef Values = A.front().front().getString(); 5660 for (std::size_t I = 0, End = Values.size(); I != End; ++I) { 5661 MCAsmMacroArgument Arg; 5662 Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1)); 5663 5664 // Note that the AtPseudoVariable is enabled for instantiations of .irpc. 5665 // This is undocumented, but GAS seems to support it. 5666 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc())) 5667 return true; 5668 } 5669 5670 instantiateMacroLikeBody(M, DirectiveLoc, OS); 5671 5672 return false; 5673 } 5674 5675 bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) { 5676 if (ActiveMacros.empty()) 5677 return TokError("unmatched '.endr' directive"); 5678 5679 // The only .repl that should get here are the ones created by 5680 // instantiateMacroLikeBody. 5681 assert(getLexer().is(AsmToken::EndOfStatement)); 5682 5683 handleMacroExit(); 5684 return false; 5685 } 5686 5687 bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info, 5688 size_t Len) { 5689 const MCExpr *Value; 5690 SMLoc ExprLoc = getLexer().getLoc(); 5691 if (parseExpression(Value)) 5692 return true; 5693 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value); 5694 if (!MCE) 5695 return Error(ExprLoc, "unexpected expression in _emit"); 5696 uint64_t IntValue = MCE->getValue(); 5697 if (!isUInt<8>(IntValue) && !isInt<8>(IntValue)) 5698 return Error(ExprLoc, "literal value out of range for directive"); 5699 5700 Info.AsmRewrites->emplace_back(AOK_Emit, IDLoc, Len); 5701 return false; 5702 } 5703 5704 bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) { 5705 const MCExpr *Value; 5706 SMLoc ExprLoc = getLexer().getLoc(); 5707 if (parseExpression(Value)) 5708 return true; 5709 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value); 5710 if (!MCE) 5711 return Error(ExprLoc, "unexpected expression in align"); 5712 uint64_t IntValue = MCE->getValue(); 5713 if (!isPowerOf2_64(IntValue)) 5714 return Error(ExprLoc, "literal value not a power of two greater then zero"); 5715 5716 Info.AsmRewrites->emplace_back(AOK_Align, IDLoc, 5, Log2_64(IntValue)); 5717 return false; 5718 } 5719 5720 bool AsmParser::parseDirectivePrint(SMLoc DirectiveLoc) { 5721 const AsmToken StrTok = getTok(); 5722 Lex(); 5723 if (StrTok.isNot(AsmToken::String) || StrTok.getString().front() != '"') 5724 return Error(DirectiveLoc, "expected double quoted string after .print"); 5725 if (parseEOL()) 5726 return true; 5727 llvm::outs() << StrTok.getStringContents() << '\n'; 5728 return false; 5729 } 5730 5731 bool AsmParser::parseDirectiveAddrsig() { 5732 if (parseEOL()) 5733 return true; 5734 getStreamer().emitAddrsig(); 5735 return false; 5736 } 5737 5738 bool AsmParser::parseDirectiveAddrsigSym() { 5739 StringRef Name; 5740 if (check(parseIdentifier(Name), "expected identifier") || parseEOL()) 5741 return true; 5742 MCSymbol *Sym = getContext().getOrCreateSymbol(Name); 5743 getStreamer().emitAddrsigSym(Sym); 5744 return false; 5745 } 5746 5747 bool AsmParser::parseDirectivePseudoProbe() { 5748 int64_t Guid; 5749 int64_t Index; 5750 int64_t Type; 5751 int64_t Attr; 5752 5753 if (getLexer().is(AsmToken::Integer)) { 5754 if (parseIntToken(Guid, "unexpected token in '.pseudoprobe' directive")) 5755 return true; 5756 } 5757 5758 if (getLexer().is(AsmToken::Integer)) { 5759 if (parseIntToken(Index, "unexpected token in '.pseudoprobe' directive")) 5760 return true; 5761 } 5762 5763 if (getLexer().is(AsmToken::Integer)) { 5764 if (parseIntToken(Type, "unexpected token in '.pseudoprobe' directive")) 5765 return true; 5766 } 5767 5768 if (getLexer().is(AsmToken::Integer)) { 5769 if (parseIntToken(Attr, "unexpected token in '.pseudoprobe' directive")) 5770 return true; 5771 } 5772 5773 // Parse inline stack like @ GUID:11:12 @ GUID:1:11 @ GUID:3:21 5774 MCPseudoProbeInlineStack InlineStack; 5775 5776 while (getLexer().is(AsmToken::At)) { 5777 // eat @ 5778 Lex(); 5779 5780 int64_t CallerGuid = 0; 5781 if (getLexer().is(AsmToken::Integer)) { 5782 if (parseIntToken(CallerGuid, 5783 "unexpected token in '.pseudoprobe' directive")) 5784 return true; 5785 } 5786 5787 // eat colon 5788 if (getLexer().is(AsmToken::Colon)) 5789 Lex(); 5790 5791 int64_t CallerProbeId = 0; 5792 if (getLexer().is(AsmToken::Integer)) { 5793 if (parseIntToken(CallerProbeId, 5794 "unexpected token in '.pseudoprobe' directive")) 5795 return true; 5796 } 5797 5798 InlineSite Site(CallerGuid, CallerProbeId); 5799 InlineStack.push_back(Site); 5800 } 5801 5802 if (parseEOL()) 5803 return true; 5804 5805 getStreamer().emitPseudoProbe(Guid, Index, Type, Attr, InlineStack); 5806 return false; 5807 } 5808 5809 // We are comparing pointers, but the pointers are relative to a single string. 5810 // Thus, this should always be deterministic. 5811 static int rewritesSort(const AsmRewrite *AsmRewriteA, 5812 const AsmRewrite *AsmRewriteB) { 5813 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer()) 5814 return -1; 5815 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer()) 5816 return 1; 5817 5818 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output 5819 // rewrite to the same location. Make sure the SizeDirective rewrite is 5820 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This 5821 // ensures the sort algorithm is stable. 5822 if (AsmRewritePrecedence[AsmRewriteA->Kind] > 5823 AsmRewritePrecedence[AsmRewriteB->Kind]) 5824 return -1; 5825 5826 if (AsmRewritePrecedence[AsmRewriteA->Kind] < 5827 AsmRewritePrecedence[AsmRewriteB->Kind]) 5828 return 1; 5829 llvm_unreachable("Unstable rewrite sort."); 5830 } 5831 5832 bool AsmParser::parseMSInlineAsm( 5833 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs, 5834 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool>> &OpDecls, 5835 SmallVectorImpl<std::string> &Constraints, 5836 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII, 5837 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) { 5838 SmallVector<void *, 4> InputDecls; 5839 SmallVector<void *, 4> OutputDecls; 5840 SmallVector<bool, 4> InputDeclsAddressOf; 5841 SmallVector<bool, 4> OutputDeclsAddressOf; 5842 SmallVector<std::string, 4> InputConstraints; 5843 SmallVector<std::string, 4> OutputConstraints; 5844 SmallVector<unsigned, 4> ClobberRegs; 5845 5846 SmallVector<AsmRewrite, 4> AsmStrRewrites; 5847 5848 // Prime the lexer. 5849 Lex(); 5850 5851 // While we have input, parse each statement. 5852 unsigned InputIdx = 0; 5853 unsigned OutputIdx = 0; 5854 while (getLexer().isNot(AsmToken::Eof)) { 5855 // Parse curly braces marking block start/end 5856 if (parseCurlyBlockScope(AsmStrRewrites)) 5857 continue; 5858 5859 ParseStatementInfo Info(&AsmStrRewrites); 5860 bool StatementErr = parseStatement(Info, &SI); 5861 5862 if (StatementErr || Info.ParseError) { 5863 // Emit pending errors if any exist. 5864 printPendingErrors(); 5865 return true; 5866 } 5867 5868 // No pending error should exist here. 5869 assert(!hasPendingError() && "unexpected error from parseStatement"); 5870 5871 if (Info.Opcode == ~0U) 5872 continue; 5873 5874 const MCInstrDesc &Desc = MII->get(Info.Opcode); 5875 5876 // Build the list of clobbers, outputs and inputs. 5877 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) { 5878 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i]; 5879 5880 // Register operand. 5881 if (Operand.isReg() && !Operand.needAddressOf() && 5882 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) { 5883 unsigned NumDefs = Desc.getNumDefs(); 5884 // Clobber. 5885 if (NumDefs && Operand.getMCOperandNum() < NumDefs) 5886 ClobberRegs.push_back(Operand.getReg()); 5887 continue; 5888 } 5889 5890 // Expr/Input or Output. 5891 StringRef SymName = Operand.getSymName(); 5892 if (SymName.empty()) 5893 continue; 5894 5895 void *OpDecl = Operand.getOpDecl(); 5896 if (!OpDecl) 5897 continue; 5898 5899 StringRef Constraint = Operand.getConstraint(); 5900 if (Operand.isImm()) { 5901 // Offset as immediate 5902 if (Operand.isOffsetOfLocal()) 5903 Constraint = "r"; 5904 else 5905 Constraint = "i"; 5906 } 5907 5908 bool isOutput = (i == 1) && Desc.mayStore(); 5909 SMLoc Start = SMLoc::getFromPointer(SymName.data()); 5910 if (isOutput) { 5911 ++InputIdx; 5912 OutputDecls.push_back(OpDecl); 5913 OutputDeclsAddressOf.push_back(Operand.needAddressOf()); 5914 OutputConstraints.push_back(("=" + Constraint).str()); 5915 AsmStrRewrites.emplace_back(AOK_Output, Start, SymName.size()); 5916 } else { 5917 InputDecls.push_back(OpDecl); 5918 InputDeclsAddressOf.push_back(Operand.needAddressOf()); 5919 InputConstraints.push_back(Constraint.str()); 5920 if (Desc.OpInfo[i - 1].isBranchTarget()) 5921 AsmStrRewrites.emplace_back(AOK_CallInput, Start, SymName.size()); 5922 else 5923 AsmStrRewrites.emplace_back(AOK_Input, Start, SymName.size()); 5924 } 5925 } 5926 5927 // Consider implicit defs to be clobbers. Think of cpuid and push. 5928 ArrayRef<MCPhysReg> ImpDefs(Desc.getImplicitDefs(), 5929 Desc.getNumImplicitDefs()); 5930 llvm::append_range(ClobberRegs, ImpDefs); 5931 } 5932 5933 // Set the number of Outputs and Inputs. 5934 NumOutputs = OutputDecls.size(); 5935 NumInputs = InputDecls.size(); 5936 5937 // Set the unique clobbers. 5938 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end()); 5939 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()), 5940 ClobberRegs.end()); 5941 Clobbers.assign(ClobberRegs.size(), std::string()); 5942 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) { 5943 raw_string_ostream OS(Clobbers[I]); 5944 IP->printRegName(OS, ClobberRegs[I]); 5945 } 5946 5947 // Merge the various outputs and inputs. Output are expected first. 5948 if (NumOutputs || NumInputs) { 5949 unsigned NumExprs = NumOutputs + NumInputs; 5950 OpDecls.resize(NumExprs); 5951 Constraints.resize(NumExprs); 5952 for (unsigned i = 0; i < NumOutputs; ++i) { 5953 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]); 5954 Constraints[i] = OutputConstraints[i]; 5955 } 5956 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) { 5957 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]); 5958 Constraints[j] = InputConstraints[i]; 5959 } 5960 } 5961 5962 // Build the IR assembly string. 5963 std::string AsmStringIR; 5964 raw_string_ostream OS(AsmStringIR); 5965 StringRef ASMString = 5966 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer(); 5967 const char *AsmStart = ASMString.begin(); 5968 const char *AsmEnd = ASMString.end(); 5969 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort); 5970 for (auto it = AsmStrRewrites.begin(); it != AsmStrRewrites.end(); ++it) { 5971 const AsmRewrite &AR = *it; 5972 // Check if this has already been covered by another rewrite... 5973 if (AR.Done) 5974 continue; 5975 AsmRewriteKind Kind = AR.Kind; 5976 5977 const char *Loc = AR.Loc.getPointer(); 5978 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!"); 5979 5980 // Emit everything up to the immediate/expression. 5981 if (unsigned Len = Loc - AsmStart) 5982 OS << StringRef(AsmStart, Len); 5983 5984 // Skip the original expression. 5985 if (Kind == AOK_Skip) { 5986 AsmStart = Loc + AR.Len; 5987 continue; 5988 } 5989 5990 unsigned AdditionalSkip = 0; 5991 // Rewrite expressions in $N notation. 5992 switch (Kind) { 5993 default: 5994 break; 5995 case AOK_IntelExpr: 5996 assert(AR.IntelExp.isValid() && "cannot write invalid intel expression"); 5997 if (AR.IntelExp.NeedBracs) 5998 OS << "["; 5999 if (AR.IntelExp.hasBaseReg()) 6000 OS << AR.IntelExp.BaseReg; 6001 if (AR.IntelExp.hasIndexReg()) 6002 OS << (AR.IntelExp.hasBaseReg() ? " + " : "") 6003 << AR.IntelExp.IndexReg; 6004 if (AR.IntelExp.Scale > 1) 6005 OS << " * $$" << AR.IntelExp.Scale; 6006 if (AR.IntelExp.hasOffset()) { 6007 if (AR.IntelExp.hasRegs()) 6008 OS << " + "; 6009 // Fuse this rewrite with a rewrite of the offset name, if present. 6010 StringRef OffsetName = AR.IntelExp.OffsetName; 6011 SMLoc OffsetLoc = SMLoc::getFromPointer(AR.IntelExp.OffsetName.data()); 6012 size_t OffsetLen = OffsetName.size(); 6013 auto rewrite_it = std::find_if( 6014 it, AsmStrRewrites.end(), [&](const AsmRewrite &FusingAR) { 6015 return FusingAR.Loc == OffsetLoc && FusingAR.Len == OffsetLen && 6016 (FusingAR.Kind == AOK_Input || 6017 FusingAR.Kind == AOK_CallInput); 6018 }); 6019 if (rewrite_it == AsmStrRewrites.end()) { 6020 OS << "offset " << OffsetName; 6021 } else if (rewrite_it->Kind == AOK_CallInput) { 6022 OS << "${" << InputIdx++ << ":P}"; 6023 rewrite_it->Done = true; 6024 } else { 6025 OS << '$' << InputIdx++; 6026 rewrite_it->Done = true; 6027 } 6028 } 6029 if (AR.IntelExp.Imm || AR.IntelExp.emitImm()) 6030 OS << (AR.IntelExp.emitImm() ? "$$" : " + $$") << AR.IntelExp.Imm; 6031 if (AR.IntelExp.NeedBracs) 6032 OS << "]"; 6033 break; 6034 case AOK_Label: 6035 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label; 6036 break; 6037 case AOK_Input: 6038 OS << '$' << InputIdx++; 6039 break; 6040 case AOK_CallInput: 6041 OS << "${" << InputIdx++ << ":P}"; 6042 break; 6043 case AOK_Output: 6044 OS << '$' << OutputIdx++; 6045 break; 6046 case AOK_SizeDirective: 6047 switch (AR.Val) { 6048 default: break; 6049 case 8: OS << "byte ptr "; break; 6050 case 16: OS << "word ptr "; break; 6051 case 32: OS << "dword ptr "; break; 6052 case 64: OS << "qword ptr "; break; 6053 case 80: OS << "xword ptr "; break; 6054 case 128: OS << "xmmword ptr "; break; 6055 case 256: OS << "ymmword ptr "; break; 6056 } 6057 break; 6058 case AOK_Emit: 6059 OS << ".byte"; 6060 break; 6061 case AOK_Align: { 6062 // MS alignment directives are measured in bytes. If the native assembler 6063 // measures alignment in bytes, we can pass it straight through. 6064 OS << ".align"; 6065 if (getContext().getAsmInfo()->getAlignmentIsInBytes()) 6066 break; 6067 6068 // Alignment is in log2 form, so print that instead and skip the original 6069 // immediate. 6070 unsigned Val = AR.Val; 6071 OS << ' ' << Val; 6072 assert(Val < 10 && "Expected alignment less then 2^10."); 6073 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4; 6074 break; 6075 } 6076 case AOK_EVEN: 6077 OS << ".even"; 6078 break; 6079 case AOK_EndOfStatement: 6080 OS << "\n\t"; 6081 break; 6082 } 6083 6084 // Skip the original expression. 6085 AsmStart = Loc + AR.Len + AdditionalSkip; 6086 } 6087 6088 // Emit the remainder of the asm string. 6089 if (AsmStart != AsmEnd) 6090 OS << StringRef(AsmStart, AsmEnd - AsmStart); 6091 6092 AsmString = OS.str(); 6093 return false; 6094 } 6095 6096 namespace llvm { 6097 namespace MCParserUtils { 6098 6099 /// Returns whether the given symbol is used anywhere in the given expression, 6100 /// or subexpressions. 6101 static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) { 6102 switch (Value->getKind()) { 6103 case MCExpr::Binary: { 6104 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value); 6105 return isSymbolUsedInExpression(Sym, BE->getLHS()) || 6106 isSymbolUsedInExpression(Sym, BE->getRHS()); 6107 } 6108 case MCExpr::Target: 6109 case MCExpr::Constant: 6110 return false; 6111 case MCExpr::SymbolRef: { 6112 const MCSymbol &S = 6113 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol(); 6114 if (S.isVariable()) 6115 return isSymbolUsedInExpression(Sym, S.getVariableValue()); 6116 return &S == Sym; 6117 } 6118 case MCExpr::Unary: 6119 return isSymbolUsedInExpression( 6120 Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr()); 6121 } 6122 6123 llvm_unreachable("Unknown expr kind!"); 6124 } 6125 6126 bool parseAssignmentExpression(StringRef Name, bool allow_redef, 6127 MCAsmParser &Parser, MCSymbol *&Sym, 6128 const MCExpr *&Value) { 6129 6130 // FIXME: Use better location, we should use proper tokens. 6131 SMLoc EqualLoc = Parser.getTok().getLoc(); 6132 if (Parser.parseExpression(Value)) 6133 return Parser.TokError("missing expression"); 6134 6135 // Note: we don't count b as used in "a = b". This is to allow 6136 // a = b 6137 // b = c 6138 6139 if (Parser.parseEOL()) 6140 return true; 6141 6142 // Validate that the LHS is allowed to be a variable (either it has not been 6143 // used as a symbol, or it is an absolute symbol). 6144 Sym = Parser.getContext().lookupSymbol(Name); 6145 if (Sym) { 6146 // Diagnose assignment to a label. 6147 // 6148 // FIXME: Diagnostics. Note the location of the definition as a label. 6149 // FIXME: Diagnose assignment to protected identifier (e.g., register name). 6150 if (isSymbolUsedInExpression(Sym, Value)) 6151 return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'"); 6152 else if (Sym->isUndefined(/*SetUsed*/ false) && !Sym->isUsed() && 6153 !Sym->isVariable()) 6154 ; // Allow redefinitions of undefined symbols only used in directives. 6155 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef) 6156 ; // Allow redefinitions of variables that haven't yet been used. 6157 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef)) 6158 return Parser.Error(EqualLoc, "redefinition of '" + Name + "'"); 6159 else if (!Sym->isVariable()) 6160 return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'"); 6161 else if (!isa<MCConstantExpr>(Sym->getVariableValue())) 6162 return Parser.Error(EqualLoc, 6163 "invalid reassignment of non-absolute variable '" + 6164 Name + "'"); 6165 } else if (Name == ".") { 6166 Parser.getStreamer().emitValueToOffset(Value, 0, EqualLoc); 6167 return false; 6168 } else 6169 Sym = Parser.getContext().getOrCreateSymbol(Name); 6170 6171 Sym->setRedefinable(allow_redef); 6172 6173 return false; 6174 } 6175 6176 } // end namespace MCParserUtils 6177 } // end namespace llvm 6178 6179 /// Create an MCAsmParser instance. 6180 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C, 6181 MCStreamer &Out, const MCAsmInfo &MAI, 6182 unsigned CB) { 6183 return new AsmParser(SM, C, Out, MAI, CB); 6184 } 6185