19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/MC/MCAsmInfo.h"
21 #include "llvm/MC/MCContext.h"
22 #include "llvm/MC/MCInstPrinter.h"
23 #include "llvm/MC/MCInstrInfo.h"
24 #include "llvm/MC/MCObjectFileInfo.h"
25 #include "llvm/MC/MCParser/MCAsmParser.h"
26 #include "llvm/MC/MCRegisterInfo.h"
27 #include "llvm/MC/MCStreamer.h"
28 #include "llvm/MC/MCSubtargetInfo.h"
29 #include "llvm/MC/MCTargetAsmParser.h"
30 #include "llvm/MC/MCTargetOptions.h"
31 #include "llvm/Support/SourceMgr.h"
32 #include "llvm/Support/TargetRegistry.h"
33 #include "llvm/Support/TargetSelect.h"
34 using namespace clang;
37 class ClangAsmParserCallback :
public llvm::MCAsmParserSemaCallback {
51 : TheParser(P), AsmLoc(Loc), AsmString(AsmString), AsmToks(Toks),
52 AsmTokOffsets(Offsets) {
53 assert(AsmToks.size() == AsmTokOffsets.size());
56 void *LookupInlineAsmIdentifier(StringRef &LineBuf,
57 llvm::InlineAsmIdentifierInfo &Info,
58 bool IsUnevaluatedContext)
override {
61 const Token *FirstOrigToken =
nullptr;
62 findTokensForString(LineBuf, LineToks, FirstOrigToken);
64 unsigned NumConsumedToks;
66 LineToks, NumConsumedToks, &Info, IsUnevaluatedContext);
70 if (NumConsumedToks == 0 || NumConsumedToks == LineToks.size()) {
75 assert(FirstOrigToken &&
"not using original tokens?");
78 assert(FirstOrigToken[NumConsumedToks].getLocation() ==
79 LineToks[NumConsumedToks].getLocation());
80 unsigned FirstIndex = FirstOrigToken - AsmToks.begin();
81 unsigned LastIndex = FirstIndex + NumConsumedToks - 1;
85 unsigned TotalOffset =
86 (AsmTokOffsets[LastIndex] + AsmToks[LastIndex].getLength() -
87 AsmTokOffsets[FirstIndex]);
88 LineBuf = LineBuf.substr(0, TotalOffset);
92 Info.OpDecl =
static_cast<void *
>(Result.
get());
96 StringRef LookupInlineAsmLabel(StringRef Identifier,
llvm::SourceMgr &LSM,
101 TheParser.getActions().GetOrCreateMSAsmLabel(Identifier, Loc, Create);
105 bool LookupInlineAsmField(StringRef
Base, StringRef Member,
106 unsigned &
Offset)
override {
107 return TheParser.getActions().LookupInlineAsmField(Base, Member, Offset,
111 static void DiagHandlerCallback(
const llvm::SMDiagnostic &D,
void *
Context) {
112 ((ClangAsmParserCallback *)Context)->handleDiagnostic(D);
118 const Token *&FirstOrigToken)
const {
121 assert(!std::less<const char *>()(Str.begin(), AsmString.begin()) &&
122 !std::less<const char *>()(AsmString.end(), Str.end()));
125 unsigned FirstCharOffset = Str.begin() - AsmString.begin();
126 const unsigned *FirstTokOffset = std::lower_bound(
127 AsmTokOffsets.begin(), AsmTokOffsets.end(), FirstCharOffset);
131 assert(*FirstTokOffset == FirstCharOffset);
135 unsigned FirstTokIndex = FirstTokOffset - AsmTokOffsets.begin();
136 FirstOrigToken = &AsmToks[FirstTokIndex];
137 unsigned LastCharOffset = Str.end() - AsmString.begin();
138 for (
unsigned i = FirstTokIndex, e = AsmTokOffsets.size(); i != e; ++i) {
139 if (AsmTokOffsets[i] >= LastCharOffset)
141 TempToks.push_back(AsmToks[i]);
149 const llvm::MemoryBuffer *LBuf =
150 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(SMLoc));
151 unsigned Offset = SMLoc.getPointer() - LBuf->getBufferStart();
154 const unsigned *TokOffsetPtr =
155 std::lower_bound(AsmTokOffsets.begin(), AsmTokOffsets.end(),
Offset);
156 unsigned TokIndex = TokOffsetPtr - AsmTokOffsets.begin();
157 unsigned TokOffset = *TokOffsetPtr;
163 if (TokIndex < AsmToks.size()) {
164 const Token &Tok = AsmToks[TokIndex];
171 void handleDiagnostic(
const llvm::SMDiagnostic &D) {
174 TheParser.Diag(Loc, diag::err_inline_ms_asm_parsing) << D.getMessage();
184 unsigned &NumLineToksConsumed,
186 bool IsUnevaluatedContext) {
187 llvm::InlineAsmIdentifierInfo &Info =
188 *(llvm::InlineAsmIdentifierInfo *)CastInfo;
194 Token EndOfStreamTok;
196 EndOfStreamTok.
setKind(EndOfStream);
197 LineToks.push_back(EndOfStreamTok);
200 LineToks.push_back(Tok);
212 ParseOptionalCXXScopeSpecifier(SS,
ParsedType(),
false);
220 if (Tok.
is(tok::kw_this)) {
221 Result = ParseCXXThis();
232 IsUnevaluatedContext);
237 while (Result.
isUsable() && Tok.
is(tok::period)) {
239 if (IdTok.
isNot(tok::identifier))
249 unsigned LineIndex = 0;
250 if (Tok.
is(EndOfStream)) {
251 LineIndex = LineToks.size() - 2;
253 while (LineToks[LineIndex].getLocation() != Tok.
getLocation()) {
255 assert(LineIndex < LineToks.size() - 2);
261 if (Invalid || Tok.
is(EndOfStream)) {
262 NumLineToksConsumed = LineToks.size() - 2;
265 NumLineToksConsumed = LineIndex;
270 for (
unsigned i = 0, e = LineToks.size() - LineIndex - 2; i != e; ++i) {
273 assert(Tok.
is(EndOfStream));
289 assert(!AsmToks.empty() &&
"Didn't expect an empty AsmToks!");
292 bool isNewStatement =
true;
294 for (
unsigned i = 0, e = AsmToks.size(); i < e; ++i) {
295 const Token &Tok = AsmToks[i];
300 isNewStatement =
true;
309 TokOffsets.push_back(Asm.size());
312 if (Tok.
is(tok::kw_asm)) {
315 PP.
Diag(AsmLoc, diag::err_asm_empty);
324 bool SpellingInvalid =
false;
325 Asm += PP.
getSpelling(Tok, SpellingBuffer, &SpellingInvalid);
326 assert(!SpellingInvalid &&
"spelling was invalid after correct parse?");
329 isNewStatement =
false;
336 assert(TokOffsets.size() == AsmToks.size());
360 bool SingleLineMode =
true;
361 unsigned BraceNesting = 0;
362 unsigned short savedBraceCount = BraceCount;
363 bool InAsmComment =
false;
366 unsigned NumTokensRead = 0;
368 bool SkippedStartOfLine =
false;
370 if (Tok.
is(tok::l_brace)) {
372 SingleLineMode =
false;
374 EndLoc = ConsumeBrace();
375 LBraceLocs.push_back(EndLoc);
379 std::pair<FileID, unsigned> ExpAsmLoc =
381 FID = ExpAsmLoc.first;
392 if (!InAsmComment && Tok.
is(tok::l_brace)) {
395 EndLoc = ConsumeBrace();
397 LBraceLocs.push_back(EndLoc);
401 }
else if (!InAsmComment && Tok.
is(tok::semi)) {
404 if (!SingleLineMode) {
406 std::pair<FileID, unsigned> ExpSemiLoc =
408 FID = ExpSemiLoc.first;
411 }
else if (SingleLineMode || InAsmComment) {
414 std::pair<FileID, unsigned> ExpLoc =
416 if (ExpLoc.first != FID ||
417 SrcMgr.
getLineNumber(ExpLoc.first, ExpLoc.second) != LineNo) {
422 bool isAsm = Tok.
is(tok::kw_asm);
423 if (SingleLineMode && !isAsm)
426 InAsmComment =
false;
431 }
else if (!InAsmComment && Tok.
is(tok::r_brace)) {
439 if (!InAsmComment && BraceNesting && Tok.
is(tok::r_brace) &&
440 BraceCount == (savedBraceCount + BraceNesting)) {
443 EndLoc = ConsumeBrace();
447 if (BraceNesting == 0 && !SingleLineMode)
450 LBraceLocs.pop_back();
465 if (SkippedStartOfLine)
467 AsmToks.push_back(Tok);
472 SkippedStartOfLine =
false;
475 if (BraceNesting && BraceCount != savedBraceCount) {
477 for (
unsigned i = 0; i < BraceNesting; ++i) {
478 Diag(Tok, diag::err_expected) << tok::r_brace;
479 Diag(LBraceLocs.back(), diag::note_matching) << tok::l_brace;
480 LBraceLocs.pop_back();
483 }
else if (NumTokensRead == 0) {
485 Diag(Tok, diag::err_expected) << tok::l_brace;
496 llvm::Triple::ArchType ArchTy = TheTriple.getArch();
497 const std::string &TT = TheTriple.getTriple();
498 const llvm::Target *TheTarget =
nullptr;
499 bool UnsupportedArch =
500 (ArchTy != llvm::Triple::x86 && ArchTy != llvm::Triple::x86_64);
501 if (UnsupportedArch) {
502 Diag(AsmLoc, diag::err_msasm_unsupported_arch) << TheTriple.getArchName();
505 TheTarget = llvm::TargetRegistry::lookupTarget(TT, Error);
507 Diag(AsmLoc, diag::err_msasm_unable_to_create_target) << Error;
510 assert(!LBraceLocs.empty() &&
"Should have at least one location here");
514 if (!TheTarget || AsmToks.empty()) {
515 return Actions.
ActOnMSAsmStmt(AsmLoc, LBraceLocs[0], AsmToks, StringRef(),
517 ConstraintRefs, ClobberRefs, Exprs, EndLoc);
526 std::unique_ptr<llvm::MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TT));
527 std::unique_ptr<llvm::MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TT));
529 std::unique_ptr<llvm::MCInstrInfo> MII(TheTarget->createMCInstrInfo());
530 std::unique_ptr<llvm::MCObjectFileInfo> MOFI(
new llvm::MCObjectFileInfo());
531 std::unique_ptr<llvm::MCSubtargetInfo> STI(
532 TheTarget->createMCSubtargetInfo(TT,
"",
""));
535 llvm::MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &TempSrcMgr);
536 MOFI->InitMCObjectFileInfo(TheTriple, llvm::Reloc::Default,
537 llvm::CodeModel::Default, Ctx);
538 std::unique_ptr<llvm::MemoryBuffer>
Buffer =
539 llvm::MemoryBuffer::getMemBuffer(AsmString,
"<MS inline asm>");
542 TempSrcMgr.AddNewSourceBuffer(std::move(Buffer), llvm::SMLoc());
544 std::unique_ptr<llvm::MCStreamer> Str(createNullStreamer(Ctx));
545 std::unique_ptr<llvm::MCAsmParser>
Parser(
546 createMCAsmParser(TempSrcMgr, Ctx, *Str.get(), *MAI));
549 llvm::MCTargetOptions MCOptions;
550 std::unique_ptr<llvm::MCTargetAsmParser> TargetParser(
551 TheTarget->createMCAsmParser(*STI, *
Parser, *MII, MCOptions));
553 std::unique_ptr<llvm::MCInstPrinter> IP(
554 TheTarget->createMCInstPrinter(llvm::Triple(TT), 1, *MAI, *MII, *MRI));
557 Parser->setAssemblerDialect(1);
558 Parser->setTargetParser(*TargetParser.get());
559 Parser->setParsingInlineAsm(
true);
560 TargetParser->setParsingInlineAsm(
true);
562 ClangAsmParserCallback
Callback(*
this, AsmLoc, AsmString, AsmToks,
564 TargetParser->setSemaCallback(&
Callback);
565 TempSrcMgr.setDiagHandler(ClangAsmParserCallback::DiagHandlerCallback,
570 std::string AsmStringIR;
575 NumInputs, OpExprs, Constraints, Clobbers,
581 auto End = std::remove(Clobbers.begin(), Clobbers.end(),
"fpsw");
582 Clobbers.erase(
End, Clobbers.end());
585 ClobberRefs.insert(ClobberRefs.end(), Clobbers.begin(), Clobbers.end());
588 unsigned NumExprs = NumOutputs + NumInputs;
589 ConstraintRefs.resize(NumExprs);
590 Exprs.resize(NumExprs);
591 for (
unsigned i = 0, e = NumExprs; i != e; ++i) {
592 Expr *OpExpr =
static_cast<Expr *
>(OpExprs[i].first);
597 if (OpExprs[i].second)
601 ConstraintRefs[i] = StringRef(Constraints[i]);
606 return Actions.
ActOnMSAsmStmt(AsmLoc, LBraceLocs[0], AsmToks, AsmStringIR,
607 NumOutputs, NumInputs, ConstraintRefs,
608 ClobberRefs, Exprs, EndLoc);
630 StmtResult Parser::ParseAsmStatement(
bool &msAsm) {
631 assert(Tok.
is(tok::kw_asm) &&
"Not an asm stmt");
635 !isTypeQualifier()) {
637 return ParseMicrosoftAsmStatement(AsmLoc);
642 ParseTypeQualifierListOpt(DS, AR_VendorAttributesParsed);
646 Diag(Loc, diag::w_asm_qualifier_ignored) <<
"const";
648 Diag(Loc, diag::w_asm_qualifier_ignored) <<
"restrict";
651 Diag(Loc, diag::w_asm_qualifier_ignored) <<
"_Atomic";
655 if (Tok.
isNot(tok::l_paren)) {
656 Diag(Tok, diag::err_expected_lparen_after) <<
"asm";
663 ExprResult AsmString(ParseAsmStringLiteral());
667 if (!(
getLangOpts().GNUAsm || AsmString.isInvalid())) {
668 const auto *SL = cast<StringLiteral>(AsmString.get());
669 if (!SL->getString().trim().empty())
670 Diag(Loc, diag::err_gnu_inline_asm_disabled);
673 if (AsmString.isInvalid()) {
680 ExprVector Constraints;
684 if (Tok.
is(tok::r_paren)) {
689 Constraints, Exprs, AsmString.get(),
690 Clobbers, T.getCloseLocation());
694 bool AteExtraColon =
false;
695 if (Tok.
is(tok::colon) || Tok.
is(tok::coloncolon)) {
697 AteExtraColon = Tok.
is(tok::coloncolon);
700 if (!AteExtraColon && ParseAsmOperandsOpt(Names, Constraints, Exprs))
704 unsigned NumOutputs = Names.size();
707 if (AteExtraColon || Tok.
is(tok::colon) || Tok.
is(tok::coloncolon)) {
710 AteExtraColon =
false;
712 AteExtraColon = Tok.
is(tok::coloncolon);
716 if (!AteExtraColon && ParseAsmOperandsOpt(Names, Constraints, Exprs))
720 assert(Names.size() == Constraints.size() &&
721 Constraints.size() == Exprs.size() &&
"Input operand size mismatch!");
723 unsigned NumInputs = Names.size() - NumOutputs;
726 if (AteExtraColon || Tok.
is(tok::colon)) {
731 if (Tok.
isNot(tok::r_paren)) {
735 if (Clobber.isInvalid())
738 Clobbers.push_back(Clobber.get());
748 AsmLoc,
false, isVolatile, NumOutputs, NumInputs, Names.data(),
749 Constraints, Exprs, AsmString.get(), Clobbers, T.getCloseLocation());
769 if (!isTokenStringLiteral() && Tok.
isNot(tok::l_square))
774 if (Tok.
is(tok::l_square)) {
778 if (Tok.
isNot(tok::identifier)) {
779 Diag(Tok, diag::err_expected) << tok::identifier;
790 Names.push_back(
nullptr);
792 ExprResult Constraint(ParseAsmStringLiteral());
793 if (Constraint.isInvalid()) {
797 Constraints.push_back(Constraint.get());
799 if (Tok.
isNot(tok::l_paren)) {
800 Diag(Tok, diag::err_expected_lparen_after) <<
"asm operand";
814 Exprs.push_back(Res.
get());
bool isAtStartOfLine() const
isAtStartOfLine - Return true if this token is at the start of a line.
SourceManager & getSourceManager() const
Defines the clang::ASTContext interface.
ExprResult ParseExpression(TypeCastState isTypeCast=NotTypeCast)
Simple precedence-based parser for binary/ternary operators.
std::pair< FileID, unsigned > getDecomposedExpansionLoc(SourceLocation Loc) const
Decompose the specified location into a raw FileID + Offset pair.
StringRef getMSAsmLabel() const
const LangOptions & getLangOpts() const
const Token & LookAhead(unsigned N)
Peeks ahead N tokens and returns that token without consuming any tokens.
StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple, bool IsVolatile, unsigned NumOutputs, unsigned NumInputs, IdentifierInfo **Names, MultiExprArg Constraints, MultiExprArg Exprs, Expr *AsmString, MultiExprArg Clobbers, SourceLocation RParenLoc)
bool hasLeadingSpace() const
Return true if this token has whitespace before it.
std::unique_ptr< llvm::MemoryBuffer > Buffer
void setFlag(TokenFlags Flag)
Set the specified flag.
Parser - This implements a parser for the C family of languages.
ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *Input)
StringRef getSpelling(SourceLocation loc, SmallVectorImpl< char > &buffer, bool *invalid=nullptr) const
Return the 'spelling' of the token at the given location; does not go up to the spelling location or ...
bool SkipUntil(tok::TokenKind T, SkipUntilFlags Flags=static_cast< SkipUntilFlags >(0))
SkipUntil - Read tokens until we get to the specified token, then consume it (unless StopBeforeMatch ...
bool TryConsumeToken(tok::TokenKind Expected)
One of these records is kept for each identifier that is lexed.
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
Token - This structure provides full information about a lexed token.
void setKind(tok::TokenKind K)
RAII class that helps handle the parsing of an open/close delimiter pair, such as braces { ...
A location where the result (returned value) of evaluating a statement should be stored.
Represents a C++ unqualified-id that has been parsed.
const TargetInfo & getTargetInfo() const
SourceLocation getLocWithOffset(int Offset) const
Return a source location with the specified offset from this SourceLocation.
Represents a C++ nested-name-specifier or a global scope specifier.
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) const
Forwarding function for diagnostics.
ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member, llvm::InlineAsmIdentifierInfo &Info, SourceLocation AsmLoc)
ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, llvm::InlineAsmIdentifierInfo &Info, bool IsUnevaluatedContext)
Expr - This represents one expression.
StringRef getName() const
Return the actual identifier string.
MatchFinder::MatchCallback * Callback
static bool buildMSAsmString(Preprocessor &PP, SourceLocation AsmLoc, ArrayRef< Token > AsmToks, SmallVectorImpl< unsigned > &TokOffsets, SmallString< 512 > &Asm)
Turn a sequence of our tokens back into a string that we can hand to the MC asm parser.
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file. ...
bool isNot(tok::TokenKind K) const
static OMPLinearClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, OpenMPLinearClauseKind Modifier, SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc, ArrayRef< Expr * > VL, ArrayRef< Expr * > PL, ArrayRef< Expr * > IL, Expr *Step, Expr *CalcStep)
Creates clause with a list of variables VL and a linear step Step.
The result type of a method or function.
Stop skipping at semicolon.
ActionResult - This structure is used while parsing/acting on expressions, stmts, etc...
ExprResult ParseMSAsmIdentifier(llvm::SmallVectorImpl< Token > &LineToks, unsigned &NumLineToksConsumed, void *Info, bool IsUnevaluated)
Parse an identifier in an MS-style inline assembly block.
Encodes a location in the source.
Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies)
LabelDecl - Represents the declaration of a label.
Scope * getCurScope() const
void EnterTokenStream(const Token *Toks, unsigned NumToks, bool DisableMacroExpansion, bool OwnsTokens)
Add a "macro" context to the top of the include stack, which will cause the lexer to start returning ...
void Lex(Token &Result)
Lex the next token for this preprocessor.
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {...
bool ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext, bool AllowDestructorName, bool AllowConstructorName, ParsedType ObjectType, SourceLocation &TemplateKWLoc, UnqualifiedId &Result)
Parse a C++ unqualified-id (or a C identifier), which describes the name of an entity.
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
unsigned getLineNumber(FileID FID, unsigned FilePos, bool *Invalid=nullptr) const
Given a SourceLocation, return the spelling line number for the position indicated.
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Defines the Diagnostic-related interfaces.
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Captures information about "declaration specifiers".
SourceLocation ConsumeToken()
ConsumeToken - Consume the current 'peek token' and lex the next one.
ExprResult CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl=nullptr, llvm::function_ref< ExprResult(Expr *)> Filter=[](Expr *E) -> ExprResult{return E;})
Process any TypoExprs in the given Expr and its children, generating diagnostics as appropriate and r...
Defines the clang::TargetInfo interface.
StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc, ArrayRef< Token > AsmToks, StringRef AsmString, unsigned NumOutputs, unsigned NumInputs, ArrayRef< StringRef > Constraints, ArrayRef< StringRef > Clobbers, ArrayRef< Expr * > Exprs, SourceLocation EndLoc)
This class handles loading and caching of source files into memory.
void startToken()
Reset all flags to cleared.
void * getPtrEncoding() const
When a SourceLocation itself cannot be used, this returns an (opaque) pointer encoding for it...
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
IdentifierInfo * getIdentifierInfo() const