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