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