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