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