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