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