Path: blob/main/contrib/llvm-project/clang/lib/Parse/ParseStmtAsm.cpp
35233 views
//===---- ParseStmtAsm.cpp - Assembly Statement Parser --------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file implements parsing for GCC and Microsoft inline assembly.9//10//===----------------------------------------------------------------------===//1112#include "clang/AST/ASTContext.h"13#include "clang/Basic/Diagnostic.h"14#include "clang/Basic/TargetInfo.h"15#include "clang/Parse/Parser.h"16#include "clang/Parse/RAIIObjectsForParser.h"17#include "llvm/ADT/SmallString.h"18#include "llvm/ADT/StringExtras.h"19#include "llvm/MC/MCAsmInfo.h"20#include "llvm/MC/MCContext.h"21#include "llvm/MC/MCInstPrinter.h"22#include "llvm/MC/MCInstrInfo.h"23#include "llvm/MC/MCObjectFileInfo.h"24#include "llvm/MC/MCParser/MCAsmParser.h"25#include "llvm/MC/MCParser/MCTargetAsmParser.h"26#include "llvm/MC/MCRegisterInfo.h"27#include "llvm/MC/MCStreamer.h"28#include "llvm/MC/MCSubtargetInfo.h"29#include "llvm/MC/MCTargetOptions.h"30#include "llvm/MC/TargetRegistry.h"31#include "llvm/Support/SourceMgr.h"32#include "llvm/Support/TargetSelect.h"33using namespace clang;3435namespace {36class ClangAsmParserCallback : public llvm::MCAsmParserSemaCallback {37Parser &TheParser;38SourceLocation AsmLoc;39StringRef AsmString;4041/// The tokens we streamed into AsmString and handed off to MC.42ArrayRef<Token> AsmToks;4344/// The offset of each token in AsmToks within AsmString.45ArrayRef<unsigned> AsmTokOffsets;4647public:48ClangAsmParserCallback(Parser &P, SourceLocation Loc, StringRef AsmString,49ArrayRef<Token> Toks, ArrayRef<unsigned> Offsets)50: TheParser(P), AsmLoc(Loc), AsmString(AsmString), AsmToks(Toks),51AsmTokOffsets(Offsets) {52assert(AsmToks.size() == AsmTokOffsets.size());53}5455void LookupInlineAsmIdentifier(StringRef &LineBuf,56llvm::InlineAsmIdentifierInfo &Info,57bool IsUnevaluatedContext) override;5859StringRef LookupInlineAsmLabel(StringRef Identifier, llvm::SourceMgr &LSM,60llvm::SMLoc Location,61bool Create) override;6263bool LookupInlineAsmField(StringRef Base, StringRef Member,64unsigned &Offset) override {65return TheParser.getActions().LookupInlineAsmField(Base, Member, Offset,66AsmLoc);67}6869static void DiagHandlerCallback(const llvm::SMDiagnostic &D, void *Context) {70((ClangAsmParserCallback *)Context)->handleDiagnostic(D);71}7273private:74/// Collect the appropriate tokens for the given string.75void findTokensForString(StringRef Str, SmallVectorImpl<Token> &TempToks,76const Token *&FirstOrigToken) const;7778SourceLocation translateLocation(const llvm::SourceMgr &LSM,79llvm::SMLoc SMLoc);8081void handleDiagnostic(const llvm::SMDiagnostic &D);82};83}8485void ClangAsmParserCallback::LookupInlineAsmIdentifier(86StringRef &LineBuf, llvm::InlineAsmIdentifierInfo &Info,87bool IsUnevaluatedContext) {88// Collect the desired tokens.89SmallVector<Token, 16> LineToks;90const Token *FirstOrigToken = nullptr;91findTokensForString(LineBuf, LineToks, FirstOrigToken);9293unsigned NumConsumedToks;94ExprResult Result = TheParser.ParseMSAsmIdentifier(LineToks, NumConsumedToks,95IsUnevaluatedContext);9697// If we consumed the entire line, tell MC that.98// Also do this if we consumed nothing as a way of reporting failure.99if (NumConsumedToks == 0 || NumConsumedToks == LineToks.size()) {100// By not modifying LineBuf, we're implicitly consuming it all.101102// Otherwise, consume up to the original tokens.103} else {104assert(FirstOrigToken && "not using original tokens?");105106// Since we're using original tokens, apply that offset.107assert(FirstOrigToken[NumConsumedToks].getLocation() ==108LineToks[NumConsumedToks].getLocation());109unsigned FirstIndex = FirstOrigToken - AsmToks.begin();110unsigned LastIndex = FirstIndex + NumConsumedToks - 1;111112// The total length we've consumed is the relative offset113// of the last token we consumed plus its length.114unsigned TotalOffset =115(AsmTokOffsets[LastIndex] + AsmToks[LastIndex].getLength() -116AsmTokOffsets[FirstIndex]);117LineBuf = LineBuf.substr(0, TotalOffset);118}119120// Initialize Info with the lookup result.121if (!Result.isUsable())122return;123TheParser.getActions().FillInlineAsmIdentifierInfo(Result.get(), Info);124}125126StringRef ClangAsmParserCallback::LookupInlineAsmLabel(StringRef Identifier,127llvm::SourceMgr &LSM,128llvm::SMLoc Location,129bool Create) {130SourceLocation Loc = translateLocation(LSM, Location);131LabelDecl *Label =132TheParser.getActions().GetOrCreateMSAsmLabel(Identifier, Loc, Create);133return Label->getMSAsmLabel();134}135136void ClangAsmParserCallback::findTokensForString(137StringRef Str, SmallVectorImpl<Token> &TempToks,138const Token *&FirstOrigToken) const {139// For now, assert that the string we're working with is a substring140// of what we gave to MC. This lets us use the original tokens.141assert(!std::less<const char *>()(Str.begin(), AsmString.begin()) &&142!std::less<const char *>()(AsmString.end(), Str.end()));143144// Try to find a token whose offset matches the first token.145unsigned FirstCharOffset = Str.begin() - AsmString.begin();146const unsigned *FirstTokOffset =147llvm::lower_bound(AsmTokOffsets, FirstCharOffset);148149// For now, assert that the start of the string exactly150// corresponds to the start of a token.151assert(*FirstTokOffset == FirstCharOffset);152153// Use all the original tokens for this line. (We assume the154// end of the line corresponds cleanly to a token break.)155unsigned FirstTokIndex = FirstTokOffset - AsmTokOffsets.begin();156FirstOrigToken = &AsmToks[FirstTokIndex];157unsigned LastCharOffset = Str.end() - AsmString.begin();158for (unsigned i = FirstTokIndex, e = AsmTokOffsets.size(); i != e; ++i) {159if (AsmTokOffsets[i] >= LastCharOffset)160break;161TempToks.push_back(AsmToks[i]);162}163}164165SourceLocation166ClangAsmParserCallback::translateLocation(const llvm::SourceMgr &LSM,167llvm::SMLoc SMLoc) {168// Compute an offset into the inline asm buffer.169// FIXME: This isn't right if .macro is involved (but hopefully, no170// real-world code does that).171const llvm::MemoryBuffer *LBuf =172LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(SMLoc));173unsigned Offset = SMLoc.getPointer() - LBuf->getBufferStart();174175// Figure out which token that offset points into.176const unsigned *TokOffsetPtr = llvm::lower_bound(AsmTokOffsets, Offset);177unsigned TokIndex = TokOffsetPtr - AsmTokOffsets.begin();178unsigned TokOffset = *TokOffsetPtr;179180// If we come up with an answer which seems sane, use it; otherwise,181// just point at the __asm keyword.182// FIXME: Assert the answer is sane once we handle .macro correctly.183SourceLocation Loc = AsmLoc;184if (TokIndex < AsmToks.size()) {185const Token &Tok = AsmToks[TokIndex];186Loc = Tok.getLocation();187Loc = Loc.getLocWithOffset(Offset - TokOffset);188}189return Loc;190}191192void ClangAsmParserCallback::handleDiagnostic(const llvm::SMDiagnostic &D) {193const llvm::SourceMgr &LSM = *D.getSourceMgr();194SourceLocation Loc = translateLocation(LSM, D.getLoc());195TheParser.Diag(Loc, diag::err_inline_ms_asm_parsing) << D.getMessage();196}197198/// Parse an identifier in an MS-style inline assembly block.199ExprResult Parser::ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks,200unsigned &NumLineToksConsumed,201bool IsUnevaluatedContext) {202// Push a fake token on the end so that we don't overrun the token203// stream. We use ';' because it expression-parsing should never204// overrun it.205const tok::TokenKind EndOfStream = tok::semi;206Token EndOfStreamTok;207EndOfStreamTok.startToken();208EndOfStreamTok.setKind(EndOfStream);209LineToks.push_back(EndOfStreamTok);210211// Also copy the current token over.212LineToks.push_back(Tok);213214PP.EnterTokenStream(LineToks, /*DisableMacroExpansions*/ true,215/*IsReinject*/ true);216217// Clear the current token and advance to the first token in LineToks.218ConsumeAnyToken();219220// Parse an optional scope-specifier if we're in C++.221CXXScopeSpec SS;222if (getLangOpts().CPlusPlus)223ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,224/*ObjectHasErrors=*/false,225/*EnteringContext=*/false);226227// Require an identifier here.228SourceLocation TemplateKWLoc;229UnqualifiedId Id;230bool Invalid = true;231ExprResult Result;232if (Tok.is(tok::kw_this)) {233Result = ParseCXXThis();234Invalid = false;235} else {236Invalid =237ParseUnqualifiedId(SS, /*ObjectType=*/nullptr,238/*ObjectHadErrors=*/false,239/*EnteringContext=*/false,240/*AllowDestructorName=*/false,241/*AllowConstructorName=*/false,242/*AllowDeductionGuide=*/false, &TemplateKWLoc, Id);243// Perform the lookup.244Result = Actions.LookupInlineAsmIdentifier(SS, TemplateKWLoc, Id,245IsUnevaluatedContext);246}247// While the next two tokens are 'period' 'identifier', repeatedly parse it as248// a field access. We have to avoid consuming assembler directives that look249// like '.' 'else'.250while (Result.isUsable() && Tok.is(tok::period)) {251Token IdTok = PP.LookAhead(0);252if (IdTok.isNot(tok::identifier))253break;254ConsumeToken(); // Consume the period.255IdentifierInfo *Id = Tok.getIdentifierInfo();256ConsumeToken(); // Consume the identifier.257Result = Actions.LookupInlineAsmVarDeclField(Result.get(), Id->getName(),258Tok.getLocation());259}260261// Figure out how many tokens we are into LineToks.262unsigned LineIndex = 0;263if (Tok.is(EndOfStream)) {264LineIndex = LineToks.size() - 2;265} else {266while (LineToks[LineIndex].getLocation() != Tok.getLocation()) {267LineIndex++;268assert(LineIndex < LineToks.size() - 2); // we added two extra tokens269}270}271272// If we've run into the poison token we inserted before, or there273// was a parsing error, then claim the entire line.274if (Invalid || Tok.is(EndOfStream)) {275NumLineToksConsumed = LineToks.size() - 2;276} else {277// Otherwise, claim up to the start of the next token.278NumLineToksConsumed = LineIndex;279}280281// Finally, restore the old parsing state by consuming all the tokens we282// staged before, implicitly killing off the token-lexer we pushed.283for (unsigned i = 0, e = LineToks.size() - LineIndex - 2; i != e; ++i) {284ConsumeAnyToken();285}286assert(Tok.is(EndOfStream));287ConsumeToken();288289// Leave LineToks in its original state.290LineToks.pop_back();291LineToks.pop_back();292293return Result;294}295296/// Turn a sequence of our tokens back into a string that we can hand297/// to the MC asm parser.298static bool buildMSAsmString(Preprocessor &PP, SourceLocation AsmLoc,299ArrayRef<Token> AsmToks,300SmallVectorImpl<unsigned> &TokOffsets,301SmallString<512> &Asm) {302assert(!AsmToks.empty() && "Didn't expect an empty AsmToks!");303304// Is this the start of a new assembly statement?305bool isNewStatement = true;306307for (unsigned i = 0, e = AsmToks.size(); i < e; ++i) {308const Token &Tok = AsmToks[i];309310// Start each new statement with a newline and a tab.311if (!isNewStatement && (Tok.is(tok::kw_asm) || Tok.isAtStartOfLine())) {312Asm += "\n\t";313isNewStatement = true;314}315316// Preserve the existence of leading whitespace except at the317// start of a statement.318if (!isNewStatement && Tok.hasLeadingSpace())319Asm += ' ';320321// Remember the offset of this token.322TokOffsets.push_back(Asm.size());323324// Don't actually write '__asm' into the assembly stream.325if (Tok.is(tok::kw_asm)) {326// Complain about __asm at the end of the stream.327if (i + 1 == e) {328PP.Diag(AsmLoc, diag::err_asm_empty);329return true;330}331332continue;333}334335// Append the spelling of the token.336SmallString<32> SpellingBuffer;337bool SpellingInvalid = false;338Asm += PP.getSpelling(Tok, SpellingBuffer, &SpellingInvalid);339assert(!SpellingInvalid && "spelling was invalid after correct parse?");340341// We are no longer at the start of a statement.342isNewStatement = false;343}344345// Ensure that the buffer is null-terminated.346Asm.push_back('\0');347Asm.pop_back();348349assert(TokOffsets.size() == AsmToks.size());350return false;351}352353// Determine if this is a GCC-style asm statement.354bool Parser::isGCCAsmStatement(const Token &TokAfterAsm) const {355return TokAfterAsm.is(tok::l_paren) || isGNUAsmQualifier(TokAfterAsm);356}357358bool Parser::isGNUAsmQualifier(const Token &TokAfterAsm) const {359return getGNUAsmQualifier(TokAfterAsm) != GNUAsmQualifiers::AQ_unspecified;360}361362/// ParseMicrosoftAsmStatement. When -fms-extensions/-fasm-blocks is enabled,363/// this routine is called to collect the tokens for an MS asm statement.364///365/// [MS] ms-asm-statement:366/// ms-asm-block367/// ms-asm-block ms-asm-statement368///369/// [MS] ms-asm-block:370/// '__asm' ms-asm-line '\n'371/// '__asm' '{' ms-asm-instruction-block[opt] '}' ';'[opt]372///373/// [MS] ms-asm-instruction-block374/// ms-asm-line375/// ms-asm-line '\n' ms-asm-instruction-block376///377StmtResult Parser::ParseMicrosoftAsmStatement(SourceLocation AsmLoc) {378SourceManager &SrcMgr = PP.getSourceManager();379SourceLocation EndLoc = AsmLoc;380SmallVector<Token, 4> AsmToks;381382bool SingleLineMode = true;383unsigned BraceNesting = 0;384unsigned short savedBraceCount = BraceCount;385bool InAsmComment = false;386FileID FID;387unsigned LineNo = 0;388unsigned NumTokensRead = 0;389SmallVector<SourceLocation, 4> LBraceLocs;390bool SkippedStartOfLine = false;391392if (Tok.is(tok::l_brace)) {393// Braced inline asm: consume the opening brace.394SingleLineMode = false;395BraceNesting = 1;396EndLoc = ConsumeBrace();397LBraceLocs.push_back(EndLoc);398++NumTokensRead;399} else {400// Single-line inline asm; compute which line it is on.401std::pair<FileID, unsigned> ExpAsmLoc =402SrcMgr.getDecomposedExpansionLoc(EndLoc);403FID = ExpAsmLoc.first;404LineNo = SrcMgr.getLineNumber(FID, ExpAsmLoc.second);405LBraceLocs.push_back(SourceLocation());406}407408SourceLocation TokLoc = Tok.getLocation();409do {410// If we hit EOF, we're done, period.411if (isEofOrEom())412break;413414if (!InAsmComment && Tok.is(tok::l_brace)) {415// Consume the opening brace.416SkippedStartOfLine = Tok.isAtStartOfLine();417AsmToks.push_back(Tok);418EndLoc = ConsumeBrace();419BraceNesting++;420LBraceLocs.push_back(EndLoc);421TokLoc = Tok.getLocation();422++NumTokensRead;423continue;424} else if (!InAsmComment && Tok.is(tok::semi)) {425// A semicolon in an asm is the start of a comment.426InAsmComment = true;427if (!SingleLineMode) {428// Compute which line the comment is on.429std::pair<FileID, unsigned> ExpSemiLoc =430SrcMgr.getDecomposedExpansionLoc(TokLoc);431FID = ExpSemiLoc.first;432LineNo = SrcMgr.getLineNumber(FID, ExpSemiLoc.second);433}434} else if (SingleLineMode || InAsmComment) {435// If end-of-line is significant, check whether this token is on a436// new line.437std::pair<FileID, unsigned> ExpLoc =438SrcMgr.getDecomposedExpansionLoc(TokLoc);439if (ExpLoc.first != FID ||440SrcMgr.getLineNumber(ExpLoc.first, ExpLoc.second) != LineNo) {441// If this is a single-line __asm, we're done, except if the next442// line is MS-style asm too, in which case we finish a comment443// if needed and then keep processing the next line as a single444// line __asm.445bool isAsm = Tok.is(tok::kw_asm);446if (SingleLineMode && (!isAsm || isGCCAsmStatement(NextToken())))447break;448// We're no longer in a comment.449InAsmComment = false;450if (isAsm) {451// If this is a new __asm {} block we want to process it separately452// from the single-line __asm statements453if (PP.LookAhead(0).is(tok::l_brace))454break;455LineNo = SrcMgr.getLineNumber(ExpLoc.first, ExpLoc.second);456SkippedStartOfLine = Tok.isAtStartOfLine();457} else if (Tok.is(tok::semi)) {458// A multi-line asm-statement, where next line is a comment459InAsmComment = true;460FID = ExpLoc.first;461LineNo = SrcMgr.getLineNumber(FID, ExpLoc.second);462}463} else if (!InAsmComment && Tok.is(tok::r_brace)) {464// In MSVC mode, braces only participate in brace matching and465// separating the asm statements. This is an intentional466// departure from the Apple gcc behavior.467if (!BraceNesting)468break;469}470}471if (!InAsmComment && BraceNesting && Tok.is(tok::r_brace) &&472BraceCount == (savedBraceCount + BraceNesting)) {473// Consume the closing brace.474SkippedStartOfLine = Tok.isAtStartOfLine();475// Don't want to add the closing brace of the whole asm block476if (SingleLineMode || BraceNesting > 1) {477Tok.clearFlag(Token::LeadingSpace);478AsmToks.push_back(Tok);479}480EndLoc = ConsumeBrace();481BraceNesting--;482// Finish if all of the opened braces in the inline asm section were483// consumed.484if (BraceNesting == 0 && !SingleLineMode)485break;486else {487LBraceLocs.pop_back();488TokLoc = Tok.getLocation();489++NumTokensRead;490continue;491}492}493494// Consume the next token; make sure we don't modify the brace count etc.495// if we are in a comment.496EndLoc = TokLoc;497if (InAsmComment)498PP.Lex(Tok);499else {500// Set the token as the start of line if we skipped the original start501// of line token in case it was a nested brace.502if (SkippedStartOfLine)503Tok.setFlag(Token::StartOfLine);504AsmToks.push_back(Tok);505ConsumeAnyToken();506}507TokLoc = Tok.getLocation();508++NumTokensRead;509SkippedStartOfLine = false;510} while (true);511512if (BraceNesting && BraceCount != savedBraceCount) {513// __asm without closing brace (this can happen at EOF).514for (unsigned i = 0; i < BraceNesting; ++i) {515Diag(Tok, diag::err_expected) << tok::r_brace;516Diag(LBraceLocs.back(), diag::note_matching) << tok::l_brace;517LBraceLocs.pop_back();518}519return StmtError();520} else if (NumTokensRead == 0) {521// Empty __asm.522Diag(Tok, diag::err_expected) << tok::l_brace;523return StmtError();524}525526// Okay, prepare to use MC to parse the assembly.527SmallVector<StringRef, 4> ConstraintRefs;528SmallVector<Expr *, 4> Exprs;529SmallVector<StringRef, 4> ClobberRefs;530531// We need an actual supported target.532const llvm::Triple &TheTriple = Actions.Context.getTargetInfo().getTriple();533const std::string &TT = TheTriple.getTriple();534const llvm::Target *TheTarget = nullptr;535if (!TheTriple.isX86()) {536Diag(AsmLoc, diag::err_msasm_unsupported_arch) << TheTriple.getArchName();537} else {538std::string Error;539TheTarget = llvm::TargetRegistry::lookupTarget(TT, Error);540if (!TheTarget)541Diag(AsmLoc, diag::err_msasm_unable_to_create_target) << Error;542}543544assert(!LBraceLocs.empty() && "Should have at least one location here");545546SmallString<512> AsmString;547auto EmptyStmt = [&] {548return Actions.ActOnMSAsmStmt(AsmLoc, LBraceLocs[0], AsmToks, AsmString,549/*NumOutputs*/ 0, /*NumInputs*/ 0,550ConstraintRefs, ClobberRefs, Exprs, EndLoc);551};552// If we don't support assembly, or the assembly is empty, we don't553// need to instantiate the AsmParser, etc.554if (!TheTarget || AsmToks.empty()) {555return EmptyStmt();556}557558// Expand the tokens into a string buffer.559SmallVector<unsigned, 8> TokOffsets;560if (buildMSAsmString(PP, AsmLoc, AsmToks, TokOffsets, AsmString))561return StmtError();562563const TargetOptions &TO = Actions.Context.getTargetInfo().getTargetOpts();564std::string FeaturesStr =565llvm::join(TO.Features.begin(), TO.Features.end(), ",");566567std::unique_ptr<llvm::MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TT));568if (!MRI) {569Diag(AsmLoc, diag::err_msasm_unable_to_create_target)570<< "target MC unavailable";571return EmptyStmt();572}573// FIXME: init MCOptions from sanitizer flags here.574llvm::MCTargetOptions MCOptions;575std::unique_ptr<llvm::MCAsmInfo> MAI(576TheTarget->createMCAsmInfo(*MRI, TT, MCOptions));577// Get the instruction descriptor.578std::unique_ptr<llvm::MCInstrInfo> MII(TheTarget->createMCInstrInfo());579std::unique_ptr<llvm::MCSubtargetInfo> STI(580TheTarget->createMCSubtargetInfo(TT, TO.CPU, FeaturesStr));581// Target MCTargetDesc may not be linked in clang-based tools.582583if (!MAI || !MII || !STI) {584Diag(AsmLoc, diag::err_msasm_unable_to_create_target)585<< "target MC unavailable";586return EmptyStmt();587}588589llvm::SourceMgr TempSrcMgr;590llvm::MCContext Ctx(TheTriple, MAI.get(), MRI.get(), STI.get(), &TempSrcMgr);591std::unique_ptr<llvm::MCObjectFileInfo> MOFI(592TheTarget->createMCObjectFileInfo(Ctx, /*PIC=*/false));593Ctx.setObjectFileInfo(MOFI.get());594595std::unique_ptr<llvm::MemoryBuffer> Buffer =596llvm::MemoryBuffer::getMemBuffer(AsmString, "<MS inline asm>");597598// Tell SrcMgr about this buffer, which is what the parser will pick up.599TempSrcMgr.AddNewSourceBuffer(std::move(Buffer), llvm::SMLoc());600601std::unique_ptr<llvm::MCStreamer> Str(createNullStreamer(Ctx));602std::unique_ptr<llvm::MCAsmParser> Parser(603createMCAsmParser(TempSrcMgr, Ctx, *Str.get(), *MAI));604605std::unique_ptr<llvm::MCTargetAsmParser> TargetParser(606TheTarget->createMCAsmParser(*STI, *Parser, *MII, MCOptions));607// Target AsmParser may not be linked in clang-based tools.608if (!TargetParser) {609Diag(AsmLoc, diag::err_msasm_unable_to_create_target)610<< "target ASM parser unavailable";611return EmptyStmt();612}613614std::unique_ptr<llvm::MCInstPrinter> IP(615TheTarget->createMCInstPrinter(llvm::Triple(TT), 1, *MAI, *MII, *MRI));616617// Change to the Intel dialect.618Parser->setAssemblerDialect(1);619Parser->setTargetParser(*TargetParser.get());620Parser->setParsingMSInlineAsm(true);621TargetParser->setParsingMSInlineAsm(true);622623ClangAsmParserCallback Callback(*this, AsmLoc, AsmString, AsmToks,624TokOffsets);625TargetParser->setSemaCallback(&Callback);626TempSrcMgr.setDiagHandler(ClangAsmParserCallback::DiagHandlerCallback,627&Callback);628629unsigned NumOutputs;630unsigned NumInputs;631std::string AsmStringIR;632SmallVector<std::pair<void *, bool>, 4> OpExprs;633SmallVector<std::string, 4> Constraints;634SmallVector<std::string, 4> Clobbers;635if (Parser->parseMSInlineAsm(AsmStringIR, NumOutputs, NumInputs, OpExprs,636Constraints, Clobbers, MII.get(), IP.get(),637Callback))638return StmtError();639640// Filter out "fpsw" and "mxcsr". They aren't valid GCC asm clobber641// constraints. Clang always adds fpsr to the clobber list anyway.642llvm::erase_if(Clobbers, [](const std::string &C) {643return C == "fpsr" || C == "mxcsr";644});645646// Build the vector of clobber StringRefs.647ClobberRefs.insert(ClobberRefs.end(), Clobbers.begin(), Clobbers.end());648649// Recast the void pointers and build the vector of constraint StringRefs.650unsigned NumExprs = NumOutputs + NumInputs;651ConstraintRefs.resize(NumExprs);652Exprs.resize(NumExprs);653for (unsigned i = 0, e = NumExprs; i != e; ++i) {654Expr *OpExpr = static_cast<Expr *>(OpExprs[i].first);655if (!OpExpr)656return StmtError();657658// Need address of variable.659if (OpExprs[i].second)660OpExpr =661Actions.BuildUnaryOp(getCurScope(), AsmLoc, UO_AddrOf, OpExpr).get();662663ConstraintRefs[i] = StringRef(Constraints[i]);664Exprs[i] = OpExpr;665}666667// FIXME: We should be passing source locations for better diagnostics.668return Actions.ActOnMSAsmStmt(AsmLoc, LBraceLocs[0], AsmToks, AsmStringIR,669NumOutputs, NumInputs, ConstraintRefs,670ClobberRefs, Exprs, EndLoc);671}672673/// parseGNUAsmQualifierListOpt - Parse a GNU extended asm qualifier list.674/// asm-qualifier:675/// volatile676/// inline677/// goto678///679/// asm-qualifier-list:680/// asm-qualifier681/// asm-qualifier-list asm-qualifier682bool Parser::parseGNUAsmQualifierListOpt(GNUAsmQualifiers &AQ) {683while (true) {684const GNUAsmQualifiers::AQ A = getGNUAsmQualifier(Tok);685if (A == GNUAsmQualifiers::AQ_unspecified) {686if (Tok.isNot(tok::l_paren)) {687Diag(Tok.getLocation(), diag::err_asm_qualifier_ignored);688SkipUntil(tok::r_paren, StopAtSemi);689return true;690}691return false;692}693if (AQ.setAsmQualifier(A))694Diag(Tok.getLocation(), diag::err_asm_duplicate_qual)695<< GNUAsmQualifiers::getQualifierName(A);696ConsumeToken();697}698return false;699}700701/// ParseAsmStatement - Parse a GNU extended asm statement.702/// asm-statement:703/// gnu-asm-statement704/// ms-asm-statement705///706/// [GNU] gnu-asm-statement:707/// 'asm' asm-qualifier-list[opt] '(' asm-argument ')' ';'708///709/// [GNU] asm-argument:710/// asm-string-literal711/// asm-string-literal ':' asm-operands[opt]712/// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]713/// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]714/// ':' asm-clobbers715///716/// [GNU] asm-clobbers:717/// asm-string-literal718/// asm-clobbers ',' asm-string-literal719///720StmtResult Parser::ParseAsmStatement(bool &msAsm) {721assert(Tok.is(tok::kw_asm) && "Not an asm stmt");722SourceLocation AsmLoc = ConsumeToken();723724if (getLangOpts().AsmBlocks && !isGCCAsmStatement(Tok)) {725msAsm = true;726return ParseMicrosoftAsmStatement(AsmLoc);727}728729SourceLocation Loc = Tok.getLocation();730GNUAsmQualifiers GAQ;731if (parseGNUAsmQualifierListOpt(GAQ))732return StmtError();733734if (GAQ.isGoto() && getLangOpts().SpeculativeLoadHardening)735Diag(Loc, diag::warn_slh_does_not_support_asm_goto);736737BalancedDelimiterTracker T(*this, tok::l_paren);738T.consumeOpen();739740ExprResult AsmString(ParseAsmStringLiteral(/*ForAsmLabel*/ false));741742// Check if GNU-style InlineAsm is disabled.743// Error on anything other than empty string.744if (!(getLangOpts().GNUAsm || AsmString.isInvalid())) {745const auto *SL = cast<StringLiteral>(AsmString.get());746if (!SL->getString().trim().empty())747Diag(Loc, diag::err_gnu_inline_asm_disabled);748}749750if (AsmString.isInvalid()) {751// Consume up to and including the closing paren.752T.skipToEnd();753return StmtError();754}755756SmallVector<IdentifierInfo *, 4> Names;757ExprVector Constraints;758ExprVector Exprs;759ExprVector Clobbers;760761if (Tok.is(tok::r_paren)) {762// We have a simple asm expression like 'asm("foo")'.763T.consumeClose();764return Actions.ActOnGCCAsmStmt(765AsmLoc, /*isSimple*/ true, GAQ.isVolatile(),766/*NumOutputs*/ 0, /*NumInputs*/ 0, nullptr, Constraints, Exprs,767AsmString.get(), Clobbers, /*NumLabels*/ 0, T.getCloseLocation());768}769770// Parse Outputs, if present.771bool AteExtraColon = false;772if (Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {773// In C++ mode, parse "::" like ": :".774AteExtraColon = Tok.is(tok::coloncolon);775ConsumeToken();776777if (!AteExtraColon && ParseAsmOperandsOpt(Names, Constraints, Exprs))778return StmtError();779}780781unsigned NumOutputs = Names.size();782783// Parse Inputs, if present.784if (AteExtraColon || Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {785// In C++ mode, parse "::" like ": :".786if (AteExtraColon)787AteExtraColon = false;788else {789AteExtraColon = Tok.is(tok::coloncolon);790ConsumeToken();791}792793if (!AteExtraColon && ParseAsmOperandsOpt(Names, Constraints, Exprs))794return StmtError();795}796797assert(Names.size() == Constraints.size() &&798Constraints.size() == Exprs.size() && "Input operand size mismatch!");799800unsigned NumInputs = Names.size() - NumOutputs;801802// Parse the clobbers, if present.803if (AteExtraColon || Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {804if (AteExtraColon)805AteExtraColon = false;806else {807AteExtraColon = Tok.is(tok::coloncolon);808ConsumeToken();809}810// Parse the asm-string list for clobbers if present.811if (!AteExtraColon && isTokenStringLiteral()) {812while (true) {813ExprResult Clobber(ParseAsmStringLiteral(/*ForAsmLabel*/ false));814815if (Clobber.isInvalid())816break;817818Clobbers.push_back(Clobber.get());819820if (!TryConsumeToken(tok::comma))821break;822}823}824}825if (!GAQ.isGoto() && (Tok.isNot(tok::r_paren) || AteExtraColon)) {826Diag(Tok, diag::err_expected) << tok::r_paren;827SkipUntil(tok::r_paren, StopAtSemi);828return StmtError();829}830831// Parse the goto label, if present.832unsigned NumLabels = 0;833if (AteExtraColon || Tok.is(tok::colon)) {834if (!AteExtraColon)835ConsumeToken();836837while (true) {838if (Tok.isNot(tok::identifier)) {839Diag(Tok, diag::err_expected) << tok::identifier;840SkipUntil(tok::r_paren, StopAtSemi);841return StmtError();842}843LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),844Tok.getLocation());845Names.push_back(Tok.getIdentifierInfo());846if (!LD) {847SkipUntil(tok::r_paren, StopAtSemi);848return StmtError();849}850ExprResult Res =851Actions.ActOnAddrLabel(Tok.getLocation(), Tok.getLocation(), LD);852Exprs.push_back(Res.get());853NumLabels++;854ConsumeToken();855if (!TryConsumeToken(tok::comma))856break;857}858} else if (GAQ.isGoto()) {859Diag(Tok, diag::err_expected) << tok::colon;860SkipUntil(tok::r_paren, StopAtSemi);861return StmtError();862}863T.consumeClose();864return Actions.ActOnGCCAsmStmt(AsmLoc, false, GAQ.isVolatile(), NumOutputs,865NumInputs, Names.data(), Constraints, Exprs,866AsmString.get(), Clobbers, NumLabels,867T.getCloseLocation());868}869870/// ParseAsmOperands - Parse the asm-operands production as used by871/// asm-statement, assuming the leading ':' token was eaten.872///873/// [GNU] asm-operands:874/// asm-operand875/// asm-operands ',' asm-operand876///877/// [GNU] asm-operand:878/// asm-string-literal '(' expression ')'879/// '[' identifier ']' asm-string-literal '(' expression ')'880///881//882// FIXME: Avoid unnecessary std::string trashing.883bool Parser::ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,884SmallVectorImpl<Expr *> &Constraints,885SmallVectorImpl<Expr *> &Exprs) {886// 'asm-operands' isn't present?887if (!isTokenStringLiteral() && Tok.isNot(tok::l_square))888return false;889890while (true) {891// Read the [id] if present.892if (Tok.is(tok::l_square)) {893BalancedDelimiterTracker T(*this, tok::l_square);894T.consumeOpen();895896if (Tok.isNot(tok::identifier)) {897Diag(Tok, diag::err_expected) << tok::identifier;898SkipUntil(tok::r_paren, StopAtSemi);899return true;900}901902IdentifierInfo *II = Tok.getIdentifierInfo();903ConsumeToken();904905Names.push_back(II);906T.consumeClose();907} else908Names.push_back(nullptr);909910ExprResult Constraint(ParseAsmStringLiteral(/*ForAsmLabel*/ false));911if (Constraint.isInvalid()) {912SkipUntil(tok::r_paren, StopAtSemi);913return true;914}915Constraints.push_back(Constraint.get());916917if (Tok.isNot(tok::l_paren)) {918Diag(Tok, diag::err_expected_lparen_after) << "asm operand";919SkipUntil(tok::r_paren, StopAtSemi);920return true;921}922923// Read the parenthesized expression.924BalancedDelimiterTracker T(*this, tok::l_paren);925T.consumeOpen();926ExprResult Res = Actions.CorrectDelayedTyposInExpr(ParseExpression());927T.consumeClose();928if (Res.isInvalid()) {929SkipUntil(tok::r_paren, StopAtSemi);930return true;931}932Exprs.push_back(Res.get());933// Eat the comma and continue parsing if it exists.934if (!TryConsumeToken(tok::comma))935return false;936}937}938939const char *Parser::GNUAsmQualifiers::getQualifierName(AQ Qualifier) {940switch (Qualifier) {941case AQ_volatile: return "volatile";942case AQ_inline: return "inline";943case AQ_goto: return "goto";944case AQ_unspecified: return "unspecified";945}946llvm_unreachable("Unknown GNUAsmQualifier");947}948949Parser::GNUAsmQualifiers::AQ950Parser::getGNUAsmQualifier(const Token &Tok) const {951switch (Tok.getKind()) {952case tok::kw_volatile: return GNUAsmQualifiers::AQ_volatile;953case tok::kw_inline: return GNUAsmQualifiers::AQ_inline;954case tok::kw_goto: return GNUAsmQualifiers::AQ_goto;955default: return GNUAsmQualifiers::AQ_unspecified;956}957}958bool Parser::GNUAsmQualifiers::setAsmQualifier(AQ Qualifier) {959bool IsDuplicate = Qualifiers & Qualifier;960Qualifiers |= Qualifier;961return IsDuplicate;962}963964965