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