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