blob: 99b164d9738f575bb119ddcc50c397ed1de782d4 [file] [log] [blame]
Alp Toker1b935a82014-06-08 05:40:04 +00001//===---- ParseStmtAsm.cpp - Assembly Statement Parser --------------------===//
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 file implements parsing for GCC and Microsoft inline assembly.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Parse/Parser.h"
15#include "RAIIObjectsForParser.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/Basic/Diagnostic.h"
18#include "clang/Basic/TargetInfo.h"
19#include "llvm/ADT/SmallString.h"
Marina Yatsina41c45fa2016-02-03 11:32:08 +000020#include "llvm/ADT/StringExtras.h"
Alp Toker1b935a82014-06-08 05:40:04 +000021#include "llvm/MC/MCAsmInfo.h"
22#include "llvm/MC/MCContext.h"
23#include "llvm/MC/MCInstPrinter.h"
24#include "llvm/MC/MCInstrInfo.h"
25#include "llvm/MC/MCObjectFileInfo.h"
26#include "llvm/MC/MCParser/MCAsmParser.h"
Benjamin Kramer5e456302016-01-27 10:01:30 +000027#include "llvm/MC/MCParser/MCTargetAsmParser.h"
Alp Toker1b935a82014-06-08 05:40:04 +000028#include "llvm/MC/MCRegisterInfo.h"
29#include "llvm/MC/MCStreamer.h"
30#include "llvm/MC/MCSubtargetInfo.h"
Alp Toker1b935a82014-06-08 05:40:04 +000031#include "llvm/MC/MCTargetOptions.h"
32#include "llvm/Support/SourceMgr.h"
33#include "llvm/Support/TargetRegistry.h"
34#include "llvm/Support/TargetSelect.h"
35using namespace clang;
36
37namespace {
38class ClangAsmParserCallback : public llvm::MCAsmParserSemaCallback {
39 Parser &TheParser;
40 SourceLocation AsmLoc;
41 StringRef AsmString;
42
43 /// The tokens we streamed into AsmString and handed off to MC.
44 ArrayRef<Token> AsmToks;
45
46 /// The offset of each token in AsmToks within AsmString.
47 ArrayRef<unsigned> AsmTokOffsets;
48
49public:
50 ClangAsmParserCallback(Parser &P, SourceLocation Loc, StringRef AsmString,
51 ArrayRef<Token> Toks, ArrayRef<unsigned> Offsets)
52 : TheParser(P), AsmLoc(Loc), AsmString(AsmString), AsmToks(Toks),
53 AsmTokOffsets(Offsets) {
54 assert(AsmToks.size() == AsmTokOffsets.size());
55 }
56
57 void *LookupInlineAsmIdentifier(StringRef &LineBuf,
58 llvm::InlineAsmIdentifierInfo &Info,
59 bool IsUnevaluatedContext) override {
60 // Collect the desired tokens.
61 SmallVector<Token, 16> LineToks;
62 const Token *FirstOrigToken = nullptr;
63 findTokensForString(LineBuf, LineToks, FirstOrigToken);
64
65 unsigned NumConsumedToks;
66 ExprResult Result = TheParser.ParseMSAsmIdentifier(
67 LineToks, NumConsumedToks, &Info, IsUnevaluatedContext);
68
69 // If we consumed the entire line, tell MC that.
70 // Also do this if we consumed nothing as a way of reporting failure.
71 if (NumConsumedToks == 0 || NumConsumedToks == LineToks.size()) {
72 // By not modifying LineBuf, we're implicitly consuming it all.
73
74 // Otherwise, consume up to the original tokens.
75 } else {
76 assert(FirstOrigToken && "not using original tokens?");
77
78 // Since we're using original tokens, apply that offset.
79 assert(FirstOrigToken[NumConsumedToks].getLocation() ==
80 LineToks[NumConsumedToks].getLocation());
81 unsigned FirstIndex = FirstOrigToken - AsmToks.begin();
82 unsigned LastIndex = FirstIndex + NumConsumedToks - 1;
83
84 // The total length we've consumed is the relative offset
85 // of the last token we consumed plus its length.
86 unsigned TotalOffset =
87 (AsmTokOffsets[LastIndex] + AsmToks[LastIndex].getLength() -
88 AsmTokOffsets[FirstIndex]);
89 LineBuf = LineBuf.substr(0, TotalOffset);
90 }
91
92 // Initialize the "decl" with the lookup result.
93 Info.OpDecl = static_cast<void *>(Result.get());
94 return Info.OpDecl;
95 }
96
Ehsan Akhgari31097582014-09-22 02:21:54 +000097 StringRef LookupInlineAsmLabel(StringRef Identifier, llvm::SourceMgr &LSM,
98 llvm::SMLoc Location,
99 bool Create) override {
100 SourceLocation Loc = translateLocation(LSM, Location);
101 LabelDecl *Label =
102 TheParser.getActions().GetOrCreateMSAsmLabel(Identifier, Loc, Create);
103 return Label->getMSAsmLabel();
104 }
105
Alp Toker1b935a82014-06-08 05:40:04 +0000106 bool LookupInlineAsmField(StringRef Base, StringRef Member,
107 unsigned &Offset) override {
108 return TheParser.getActions().LookupInlineAsmField(Base, Member, Offset,
109 AsmLoc);
110 }
111
112 static void DiagHandlerCallback(const llvm::SMDiagnostic &D, void *Context) {
113 ((ClangAsmParserCallback *)Context)->handleDiagnostic(D);
114 }
115
116private:
117 /// Collect the appropriate tokens for the given string.
118 void findTokensForString(StringRef Str, SmallVectorImpl<Token> &TempToks,
119 const Token *&FirstOrigToken) const {
120 // For now, assert that the string we're working with is a substring
121 // of what we gave to MC. This lets us use the original tokens.
122 assert(!std::less<const char *>()(Str.begin(), AsmString.begin()) &&
123 !std::less<const char *>()(AsmString.end(), Str.end()));
124
125 // Try to find a token whose offset matches the first token.
126 unsigned FirstCharOffset = Str.begin() - AsmString.begin();
127 const unsigned *FirstTokOffset = std::lower_bound(
128 AsmTokOffsets.begin(), AsmTokOffsets.end(), FirstCharOffset);
129
130 // For now, assert that the start of the string exactly
131 // corresponds to the start of a token.
132 assert(*FirstTokOffset == FirstCharOffset);
133
134 // Use all the original tokens for this line. (We assume the
135 // end of the line corresponds cleanly to a token break.)
136 unsigned FirstTokIndex = FirstTokOffset - AsmTokOffsets.begin();
137 FirstOrigToken = &AsmToks[FirstTokIndex];
138 unsigned LastCharOffset = Str.end() - AsmString.begin();
139 for (unsigned i = FirstTokIndex, e = AsmTokOffsets.size(); i != e; ++i) {
140 if (AsmTokOffsets[i] >= LastCharOffset)
141 break;
142 TempToks.push_back(AsmToks[i]);
143 }
144 }
145
Ehsan Akhgari31097582014-09-22 02:21:54 +0000146 SourceLocation translateLocation(const llvm::SourceMgr &LSM, llvm::SMLoc SMLoc) {
Alp Toker1b935a82014-06-08 05:40:04 +0000147 // Compute an offset into the inline asm buffer.
148 // FIXME: This isn't right if .macro is involved (but hopefully, no
149 // real-world code does that).
Alp Toker1b935a82014-06-08 05:40:04 +0000150 const llvm::MemoryBuffer *LBuf =
Ehsan Akhgari31097582014-09-22 02:21:54 +0000151 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(SMLoc));
152 unsigned Offset = SMLoc.getPointer() - LBuf->getBufferStart();
Alp Toker1b935a82014-06-08 05:40:04 +0000153
154 // Figure out which token that offset points into.
155 const unsigned *TokOffsetPtr =
156 std::lower_bound(AsmTokOffsets.begin(), AsmTokOffsets.end(), Offset);
157 unsigned TokIndex = TokOffsetPtr - AsmTokOffsets.begin();
158 unsigned TokOffset = *TokOffsetPtr;
159
160 // If we come up with an answer which seems sane, use it; otherwise,
161 // just point at the __asm keyword.
162 // FIXME: Assert the answer is sane once we handle .macro correctly.
163 SourceLocation Loc = AsmLoc;
164 if (TokIndex < AsmToks.size()) {
165 const Token &Tok = AsmToks[TokIndex];
166 Loc = Tok.getLocation();
167 Loc = Loc.getLocWithOffset(Offset - TokOffset);
168 }
Ehsan Akhgari31097582014-09-22 02:21:54 +0000169 return Loc;
170 }
171
172 void handleDiagnostic(const llvm::SMDiagnostic &D) {
173 const llvm::SourceMgr &LSM = *D.getSourceMgr();
174 SourceLocation Loc = translateLocation(LSM, D.getLoc());
Alp Toker1b935a82014-06-08 05:40:04 +0000175 TheParser.Diag(Loc, diag::err_inline_ms_asm_parsing) << D.getMessage();
176 }
177};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000178}
Alp Toker1b935a82014-06-08 05:40:04 +0000179
180/// Parse an identifier in an MS-style inline assembly block.
181///
182/// \param CastInfo - a void* so that we don't have to teach Parser.h
183/// about the actual type.
184ExprResult Parser::ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks,
185 unsigned &NumLineToksConsumed,
186 void *CastInfo,
187 bool IsUnevaluatedContext) {
188 llvm::InlineAsmIdentifierInfo &Info =
189 *(llvm::InlineAsmIdentifierInfo *)CastInfo;
190
191 // Push a fake token on the end so that we don't overrun the token
192 // stream. We use ';' because it expression-parsing should never
193 // overrun it.
194 const tok::TokenKind EndOfStream = tok::semi;
195 Token EndOfStreamTok;
196 EndOfStreamTok.startToken();
197 EndOfStreamTok.setKind(EndOfStream);
198 LineToks.push_back(EndOfStreamTok);
199
200 // Also copy the current token over.
201 LineToks.push_back(Tok);
202
David Blaikie2eabcc92016-02-09 18:52:09 +0000203 PP.EnterTokenStream(LineToks, /*DisableMacroExpansions*/ true);
Alp Toker1b935a82014-06-08 05:40:04 +0000204
205 // Clear the current token and advance to the first token in LineToks.
206 ConsumeAnyToken();
207
208 // Parse an optional scope-specifier if we're in C++.
209 CXXScopeSpec SS;
210 if (getLangOpts().CPlusPlus) {
David Blaikieefdccaa2016-01-15 23:43:34 +0000211 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
Alp Toker1b935a82014-06-08 05:40:04 +0000212 }
213
214 // Require an identifier here.
215 SourceLocation TemplateKWLoc;
216 UnqualifiedId Id;
Michael Zuckerman229158c2015-12-15 14:04:18 +0000217 bool Invalid = true;
218 ExprResult Result;
219 if (Tok.is(tok::kw_this)) {
220 Result = ParseCXXThis();
221 Invalid = false;
222 } else {
David Blaikieefdccaa2016-01-15 23:43:34 +0000223 Invalid = ParseUnqualifiedId(SS,
224 /*EnteringContext=*/false,
225 /*AllowDestructorName=*/false,
226 /*AllowConstructorName=*/false,
227 /*ObjectType=*/nullptr, TemplateKWLoc, Id);
Michael Zuckerman229158c2015-12-15 14:04:18 +0000228 // Perform the lookup.
229 Result = Actions.LookupInlineAsmIdentifier(SS, TemplateKWLoc, Id, Info,
230 IsUnevaluatedContext);
231 }
Reid Kleckner14e96b42015-08-26 21:57:20 +0000232 // While the next two tokens are 'period' 'identifier', repeatedly parse it as
233 // a field access. We have to avoid consuming assembler directives that look
234 // like '.' 'else'.
235 while (Result.isUsable() && Tok.is(tok::period)) {
236 Token IdTok = PP.LookAhead(0);
237 if (IdTok.isNot(tok::identifier))
238 break;
239 ConsumeToken(); // Consume the period.
240 IdentifierInfo *Id = Tok.getIdentifierInfo();
241 ConsumeToken(); // Consume the identifier.
David Majnemer758e7982016-01-05 00:08:41 +0000242 Result = Actions.LookupInlineAsmVarDeclField(Result.get(), Id->getName(),
243 Info, Tok.getLocation());
Reid Kleckner14e96b42015-08-26 21:57:20 +0000244 }
245
Alp Toker1b935a82014-06-08 05:40:04 +0000246 // Figure out how many tokens we are into LineToks.
247 unsigned LineIndex = 0;
248 if (Tok.is(EndOfStream)) {
249 LineIndex = LineToks.size() - 2;
250 } else {
251 while (LineToks[LineIndex].getLocation() != Tok.getLocation()) {
252 LineIndex++;
253 assert(LineIndex < LineToks.size() - 2); // we added two extra tokens
254 }
255 }
256
257 // If we've run into the poison token we inserted before, or there
258 // was a parsing error, then claim the entire line.
259 if (Invalid || Tok.is(EndOfStream)) {
260 NumLineToksConsumed = LineToks.size() - 2;
261 } else {
262 // Otherwise, claim up to the start of the next token.
263 NumLineToksConsumed = LineIndex;
264 }
265
266 // Finally, restore the old parsing state by consuming all the tokens we
267 // staged before, implicitly killing off the token-lexer we pushed.
268 for (unsigned i = 0, e = LineToks.size() - LineIndex - 2; i != e; ++i) {
269 ConsumeAnyToken();
270 }
271 assert(Tok.is(EndOfStream));
272 ConsumeToken();
273
274 // Leave LineToks in its original state.
275 LineToks.pop_back();
276 LineToks.pop_back();
277
Reid Kleckner14e96b42015-08-26 21:57:20 +0000278 return Result;
Alp Toker1b935a82014-06-08 05:40:04 +0000279}
280
281/// Turn a sequence of our tokens back into a string that we can hand
282/// to the MC asm parser.
283static bool buildMSAsmString(Preprocessor &PP, SourceLocation AsmLoc,
284 ArrayRef<Token> AsmToks,
285 SmallVectorImpl<unsigned> &TokOffsets,
286 SmallString<512> &Asm) {
287 assert(!AsmToks.empty() && "Didn't expect an empty AsmToks!");
288
289 // Is this the start of a new assembly statement?
290 bool isNewStatement = true;
291
292 for (unsigned i = 0, e = AsmToks.size(); i < e; ++i) {
293 const Token &Tok = AsmToks[i];
294
295 // Start each new statement with a newline and a tab.
296 if (!isNewStatement && (Tok.is(tok::kw_asm) || Tok.isAtStartOfLine())) {
297 Asm += "\n\t";
298 isNewStatement = true;
299 }
300
301 // Preserve the existence of leading whitespace except at the
302 // start of a statement.
303 if (!isNewStatement && Tok.hasLeadingSpace())
304 Asm += ' ';
305
306 // Remember the offset of this token.
307 TokOffsets.push_back(Asm.size());
308
309 // Don't actually write '__asm' into the assembly stream.
310 if (Tok.is(tok::kw_asm)) {
311 // Complain about __asm at the end of the stream.
312 if (i + 1 == e) {
313 PP.Diag(AsmLoc, diag::err_asm_empty);
314 return true;
315 }
316
317 continue;
318 }
319
320 // Append the spelling of the token.
321 SmallString<32> SpellingBuffer;
322 bool SpellingInvalid = false;
323 Asm += PP.getSpelling(Tok, SpellingBuffer, &SpellingInvalid);
324 assert(!SpellingInvalid && "spelling was invalid after correct parse?");
325
326 // We are no longer at the start of a statement.
327 isNewStatement = false;
328 }
329
330 // Ensure that the buffer is null-terminated.
331 Asm.push_back('\0');
332 Asm.pop_back();
333
334 assert(TokOffsets.size() == AsmToks.size());
335 return false;
336}
337
338/// ParseMicrosoftAsmStatement. When -fms-extensions/-fasm-blocks is enabled,
339/// this routine is called to collect the tokens for an MS asm statement.
340///
341/// [MS] ms-asm-statement:
342/// ms-asm-block
343/// ms-asm-block ms-asm-statement
344///
345/// [MS] ms-asm-block:
346/// '__asm' ms-asm-line '\n'
347/// '__asm' '{' ms-asm-instruction-block[opt] '}' ';'[opt]
348///
349/// [MS] ms-asm-instruction-block
350/// ms-asm-line
351/// ms-asm-line '\n' ms-asm-instruction-block
352///
353StmtResult Parser::ParseMicrosoftAsmStatement(SourceLocation AsmLoc) {
354 SourceManager &SrcMgr = PP.getSourceManager();
355 SourceLocation EndLoc = AsmLoc;
356 SmallVector<Token, 4> AsmToks;
357
Ehsan Akhgari2f93b442014-07-25 02:27:14 +0000358 bool SingleLineMode = true;
Ehsan Akhgari0f89fac2014-07-06 05:26:54 +0000359 unsigned BraceNesting = 0;
Ehsan Akhgari833ed942014-07-15 02:21:41 +0000360 unsigned short savedBraceCount = BraceCount;
Alp Toker1b935a82014-06-08 05:40:04 +0000361 bool InAsmComment = false;
362 FileID FID;
363 unsigned LineNo = 0;
364 unsigned NumTokensRead = 0;
Ehsan Akhgari0f89fac2014-07-06 05:26:54 +0000365 SmallVector<SourceLocation, 4> LBraceLocs;
366 bool SkippedStartOfLine = false;
Alp Toker1b935a82014-06-08 05:40:04 +0000367
368 if (Tok.is(tok::l_brace)) {
369 // Braced inline asm: consume the opening brace.
Ehsan Akhgari2f93b442014-07-25 02:27:14 +0000370 SingleLineMode = false;
Ehsan Akhgari0f89fac2014-07-06 05:26:54 +0000371 BraceNesting = 1;
Ehsan Akhgari0f89fac2014-07-06 05:26:54 +0000372 EndLoc = ConsumeBrace();
373 LBraceLocs.push_back(EndLoc);
Alp Toker1b935a82014-06-08 05:40:04 +0000374 ++NumTokensRead;
375 } else {
376 // Single-line inline asm; compute which line it is on.
377 std::pair<FileID, unsigned> ExpAsmLoc =
378 SrcMgr.getDecomposedExpansionLoc(EndLoc);
379 FID = ExpAsmLoc.first;
380 LineNo = SrcMgr.getLineNumber(FID, ExpAsmLoc.second);
Ehsan Akhgari0f89fac2014-07-06 05:26:54 +0000381 LBraceLocs.push_back(SourceLocation());
Alp Toker1b935a82014-06-08 05:40:04 +0000382 }
383
384 SourceLocation TokLoc = Tok.getLocation();
385 do {
386 // If we hit EOF, we're done, period.
387 if (isEofOrEom())
388 break;
389
Ehsan Akhgari0f89fac2014-07-06 05:26:54 +0000390 if (!InAsmComment && Tok.is(tok::l_brace)) {
391 // Consume the opening brace.
392 SkippedStartOfLine = Tok.isAtStartOfLine();
Marina Yatsina5f776792016-03-07 18:10:25 +0000393 AsmToks.push_back(Tok);
Ehsan Akhgari0f89fac2014-07-06 05:26:54 +0000394 EndLoc = ConsumeBrace();
395 BraceNesting++;
396 LBraceLocs.push_back(EndLoc);
397 TokLoc = Tok.getLocation();
398 ++NumTokensRead;
399 continue;
400 } else if (!InAsmComment && Tok.is(tok::semi)) {
Alp Toker1b935a82014-06-08 05:40:04 +0000401 // A semicolon in an asm is the start of a comment.
402 InAsmComment = true;
Ehsan Akhgari2f93b442014-07-25 02:27:14 +0000403 if (!SingleLineMode) {
Alp Toker1b935a82014-06-08 05:40:04 +0000404 // Compute which line the comment is on.
405 std::pair<FileID, unsigned> ExpSemiLoc =
406 SrcMgr.getDecomposedExpansionLoc(TokLoc);
407 FID = ExpSemiLoc.first;
408 LineNo = SrcMgr.getLineNumber(FID, ExpSemiLoc.second);
409 }
Ehsan Akhgari2f93b442014-07-25 02:27:14 +0000410 } else if (SingleLineMode || InAsmComment) {
Alp Toker1b935a82014-06-08 05:40:04 +0000411 // If end-of-line is significant, check whether this token is on a
412 // new line.
413 std::pair<FileID, unsigned> ExpLoc =
414 SrcMgr.getDecomposedExpansionLoc(TokLoc);
415 if (ExpLoc.first != FID ||
416 SrcMgr.getLineNumber(ExpLoc.first, ExpLoc.second) != LineNo) {
Ehsan Akhgari2f93b442014-07-25 02:27:14 +0000417 // If this is a single-line __asm, we're done, except if the next
418 // line begins with an __asm too, in which case we finish a comment
419 // if needed and then keep processing the next line as a single
420 // line __asm.
421 bool isAsm = Tok.is(tok::kw_asm);
422 if (SingleLineMode && !isAsm)
Alp Toker1b935a82014-06-08 05:40:04 +0000423 break;
424 // We're no longer in a comment.
425 InAsmComment = false;
Ehsan Akhgari2f93b442014-07-25 02:27:14 +0000426 if (isAsm) {
Marina Yatsina146d2ec2016-02-23 08:53:45 +0000427 // If this is a new __asm {} block we want to process it seperately
428 // from the single-line __asm statements
429 if (PP.LookAhead(0).is(tok::l_brace))
430 break;
Ehsan Akhgari2f93b442014-07-25 02:27:14 +0000431 LineNo = SrcMgr.getLineNumber(ExpLoc.first, ExpLoc.second);
432 SkippedStartOfLine = Tok.isAtStartOfLine();
433 }
Alp Toker1b935a82014-06-08 05:40:04 +0000434 } else if (!InAsmComment && Tok.is(tok::r_brace)) {
Ehsan Akhgari2f93b442014-07-25 02:27:14 +0000435 // In MSVC mode, braces only participate in brace matching and
436 // separating the asm statements. This is an intentional
437 // departure from the Apple gcc behavior.
438 if (!BraceNesting)
439 break;
Alp Toker1b935a82014-06-08 05:40:04 +0000440 }
441 }
Ehsan Akhgari0f89fac2014-07-06 05:26:54 +0000442 if (!InAsmComment && BraceNesting && Tok.is(tok::r_brace) &&
443 BraceCount == (savedBraceCount + BraceNesting)) {
444 // Consume the closing brace.
445 SkippedStartOfLine = Tok.isAtStartOfLine();
Marina Yatsina5f776792016-03-07 18:10:25 +0000446 // Don't want to add the closing brace of the whole asm block
447 if (SingleLineMode || BraceNesting > 1) {
448 Tok.clearFlag(Token::LeadingSpace);
449 AsmToks.push_back(Tok);
450 }
Alp Toker1b935a82014-06-08 05:40:04 +0000451 EndLoc = ConsumeBrace();
Ehsan Akhgari0f89fac2014-07-06 05:26:54 +0000452 BraceNesting--;
Nico Weber022e5072014-07-17 18:19:30 +0000453 // Finish if all of the opened braces in the inline asm section were
454 // consumed.
Ehsan Akhgari2f93b442014-07-25 02:27:14 +0000455 if (BraceNesting == 0 && !SingleLineMode)
Ehsan Akhgari0f89fac2014-07-06 05:26:54 +0000456 break;
457 else {
458 LBraceLocs.pop_back();
459 TokLoc = Tok.getLocation();
460 ++NumTokensRead;
461 continue;
462 }
Alp Toker1b935a82014-06-08 05:40:04 +0000463 }
464
465 // Consume the next token; make sure we don't modify the brace count etc.
466 // if we are in a comment.
467 EndLoc = TokLoc;
468 if (InAsmComment)
469 PP.Lex(Tok);
470 else {
Ehsan Akhgari0f89fac2014-07-06 05:26:54 +0000471 // Set the token as the start of line if we skipped the original start
472 // of line token in case it was a nested brace.
473 if (SkippedStartOfLine)
474 Tok.setFlag(Token::StartOfLine);
Alp Toker1b935a82014-06-08 05:40:04 +0000475 AsmToks.push_back(Tok);
476 ConsumeAnyToken();
477 }
478 TokLoc = Tok.getLocation();
479 ++NumTokensRead;
Ehsan Akhgari0f89fac2014-07-06 05:26:54 +0000480 SkippedStartOfLine = false;
Alp Toker1b935a82014-06-08 05:40:04 +0000481 } while (1);
482
Ehsan Akhgari0f89fac2014-07-06 05:26:54 +0000483 if (BraceNesting && BraceCount != savedBraceCount) {
Alp Toker1b935a82014-06-08 05:40:04 +0000484 // __asm without closing brace (this can happen at EOF).
Ehsan Akhgari0f89fac2014-07-06 05:26:54 +0000485 for (unsigned i = 0; i < BraceNesting; ++i) {
486 Diag(Tok, diag::err_expected) << tok::r_brace;
487 Diag(LBraceLocs.back(), diag::note_matching) << tok::l_brace;
488 LBraceLocs.pop_back();
489 }
Alp Toker1b935a82014-06-08 05:40:04 +0000490 return StmtError();
491 } else if (NumTokensRead == 0) {
492 // Empty __asm.
493 Diag(Tok, diag::err_expected) << tok::l_brace;
494 return StmtError();
495 }
496
497 // Okay, prepare to use MC to parse the assembly.
498 SmallVector<StringRef, 4> ConstraintRefs;
499 SmallVector<Expr *, 4> Exprs;
500 SmallVector<StringRef, 4> ClobberRefs;
501
502 // We need an actual supported target.
503 const llvm::Triple &TheTriple = Actions.Context.getTargetInfo().getTriple();
504 llvm::Triple::ArchType ArchTy = TheTriple.getArch();
505 const std::string &TT = TheTriple.getTriple();
506 const llvm::Target *TheTarget = nullptr;
507 bool UnsupportedArch =
508 (ArchTy != llvm::Triple::x86 && ArchTy != llvm::Triple::x86_64);
509 if (UnsupportedArch) {
510 Diag(AsmLoc, diag::err_msasm_unsupported_arch) << TheTriple.getArchName();
511 } else {
512 std::string Error;
513 TheTarget = llvm::TargetRegistry::lookupTarget(TT, Error);
514 if (!TheTarget)
515 Diag(AsmLoc, diag::err_msasm_unable_to_create_target) << Error;
516 }
517
Ehsan Akhgari0f89fac2014-07-06 05:26:54 +0000518 assert(!LBraceLocs.empty() && "Should have at least one location here");
519
Alp Toker1b935a82014-06-08 05:40:04 +0000520 // If we don't support assembly, or the assembly is empty, we don't
521 // need to instantiate the AsmParser, etc.
522 if (!TheTarget || AsmToks.empty()) {
Ehsan Akhgari0f89fac2014-07-06 05:26:54 +0000523 return Actions.ActOnMSAsmStmt(AsmLoc, LBraceLocs[0], AsmToks, StringRef(),
Alp Toker1b935a82014-06-08 05:40:04 +0000524 /*NumOutputs*/ 0, /*NumInputs*/ 0,
525 ConstraintRefs, ClobberRefs, Exprs, EndLoc);
526 }
527
528 // Expand the tokens into a string buffer.
529 SmallString<512> AsmString;
530 SmallVector<unsigned, 8> TokOffsets;
531 if (buildMSAsmString(PP, AsmLoc, AsmToks, TokOffsets, AsmString))
532 return StmtError();
533
Marina Yatsina41c45fa2016-02-03 11:32:08 +0000534 TargetOptions TO = Actions.Context.getTargetInfo().getTargetOpts();
535 std::string FeaturesStr =
536 llvm::join(TO.Features.begin(), TO.Features.end(), ",");
537
Alp Toker1b935a82014-06-08 05:40:04 +0000538 std::unique_ptr<llvm::MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TT));
539 std::unique_ptr<llvm::MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TT));
540 // Get the instruction descriptor.
541 std::unique_ptr<llvm::MCInstrInfo> MII(TheTarget->createMCInstrInfo());
542 std::unique_ptr<llvm::MCObjectFileInfo> MOFI(new llvm::MCObjectFileInfo());
543 std::unique_ptr<llvm::MCSubtargetInfo> STI(
Marina Yatsina41c45fa2016-02-03 11:32:08 +0000544 TheTarget->createMCSubtargetInfo(TT, TO.CPU, FeaturesStr));
Alp Toker1b935a82014-06-08 05:40:04 +0000545
546 llvm::SourceMgr TempSrcMgr;
547 llvm::MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &TempSrcMgr);
Daniel Sanders8d8b13d2015-06-16 12:18:07 +0000548 MOFI->InitMCObjectFileInfo(TheTriple, llvm::Reloc::Default,
549 llvm::CodeModel::Default, Ctx);
Rafael Espindolad87f8d72014-08-27 20:03:29 +0000550 std::unique_ptr<llvm::MemoryBuffer> Buffer =
551 llvm::MemoryBuffer::getMemBuffer(AsmString, "<MS inline asm>");
Alp Toker1b935a82014-06-08 05:40:04 +0000552
553 // Tell SrcMgr about this buffer, which is what the parser will pick up.
David Blaikie9e095d92014-08-21 21:01:00 +0000554 TempSrcMgr.AddNewSourceBuffer(std::move(Buffer), llvm::SMLoc());
Alp Toker1b935a82014-06-08 05:40:04 +0000555
556 std::unique_ptr<llvm::MCStreamer> Str(createNullStreamer(Ctx));
557 std::unique_ptr<llvm::MCAsmParser> Parser(
558 createMCAsmParser(TempSrcMgr, Ctx, *Str.get(), *MAI));
559
560 // FIXME: init MCOptions from sanitizer flags here.
561 llvm::MCTargetOptions MCOptions;
562 std::unique_ptr<llvm::MCTargetAsmParser> TargetParser(
563 TheTarget->createMCAsmParser(*STI, *Parser, *MII, MCOptions));
564
Daniel Sanders50f17232015-09-15 16:17:27 +0000565 std::unique_ptr<llvm::MCInstPrinter> IP(
566 TheTarget->createMCInstPrinter(llvm::Triple(TT), 1, *MAI, *MII, *MRI));
Alp Toker1b935a82014-06-08 05:40:04 +0000567
568 // Change to the Intel dialect.
569 Parser->setAssemblerDialect(1);
570 Parser->setTargetParser(*TargetParser.get());
571 Parser->setParsingInlineAsm(true);
572 TargetParser->setParsingInlineAsm(true);
573
574 ClangAsmParserCallback Callback(*this, AsmLoc, AsmString, AsmToks,
575 TokOffsets);
576 TargetParser->setSemaCallback(&Callback);
577 TempSrcMgr.setDiagHandler(ClangAsmParserCallback::DiagHandlerCallback,
578 &Callback);
579
580 unsigned NumOutputs;
581 unsigned NumInputs;
582 std::string AsmStringIR;
583 SmallVector<std::pair<void *, bool>, 4> OpExprs;
584 SmallVector<std::string, 4> Constraints;
585 SmallVector<std::string, 4> Clobbers;
586 if (Parser->parseMSInlineAsm(AsmLoc.getPtrEncoding(), AsmStringIR, NumOutputs,
587 NumInputs, OpExprs, Constraints, Clobbers,
588 MII.get(), IP.get(), Callback))
589 return StmtError();
590
591 // Filter out "fpsw". Clang doesn't accept it, and it always lists flags and
592 // fpsr as clobbers.
593 auto End = std::remove(Clobbers.begin(), Clobbers.end(), "fpsw");
594 Clobbers.erase(End, Clobbers.end());
595
596 // Build the vector of clobber StringRefs.
David Majnemer05c69862014-06-23 02:16:41 +0000597 ClobberRefs.insert(ClobberRefs.end(), Clobbers.begin(), Clobbers.end());
Alp Toker1b935a82014-06-08 05:40:04 +0000598
599 // Recast the void pointers and build the vector of constraint StringRefs.
600 unsigned NumExprs = NumOutputs + NumInputs;
601 ConstraintRefs.resize(NumExprs);
602 Exprs.resize(NumExprs);
603 for (unsigned i = 0, e = NumExprs; i != e; ++i) {
604 Expr *OpExpr = static_cast<Expr *>(OpExprs[i].first);
605 if (!OpExpr)
606 return StmtError();
607
608 // Need address of variable.
609 if (OpExprs[i].second)
610 OpExpr =
611 Actions.BuildUnaryOp(getCurScope(), AsmLoc, UO_AddrOf, OpExpr).get();
612
613 ConstraintRefs[i] = StringRef(Constraints[i]);
614 Exprs[i] = OpExpr;
615 }
616
617 // FIXME: We should be passing source locations for better diagnostics.
Ehsan Akhgari0f89fac2014-07-06 05:26:54 +0000618 return Actions.ActOnMSAsmStmt(AsmLoc, LBraceLocs[0], AsmToks, AsmStringIR,
Alp Toker1b935a82014-06-08 05:40:04 +0000619 NumOutputs, NumInputs, ConstraintRefs,
620 ClobberRefs, Exprs, EndLoc);
621}
622
623/// ParseAsmStatement - Parse a GNU extended asm statement.
624/// asm-statement:
625/// gnu-asm-statement
626/// ms-asm-statement
627///
628/// [GNU] gnu-asm-statement:
629/// 'asm' type-qualifier[opt] '(' asm-argument ')' ';'
630///
631/// [GNU] asm-argument:
632/// asm-string-literal
633/// asm-string-literal ':' asm-operands[opt]
634/// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
635/// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
636/// ':' asm-clobbers
637///
638/// [GNU] asm-clobbers:
639/// asm-string-literal
640/// asm-clobbers ',' asm-string-literal
641///
642StmtResult Parser::ParseAsmStatement(bool &msAsm) {
643 assert(Tok.is(tok::kw_asm) && "Not an asm stmt");
644 SourceLocation AsmLoc = ConsumeToken();
645
646 if (getLangOpts().AsmBlocks && Tok.isNot(tok::l_paren) &&
647 !isTypeQualifier()) {
648 msAsm = true;
649 return ParseMicrosoftAsmStatement(AsmLoc);
650 }
Steven Wucb0d13f2015-01-16 23:05:28 +0000651
Alp Toker1b935a82014-06-08 05:40:04 +0000652 DeclSpec DS(AttrFactory);
653 SourceLocation Loc = Tok.getLocation();
Aaron Ballman08b06592014-07-22 12:44:22 +0000654 ParseTypeQualifierListOpt(DS, AR_VendorAttributesParsed);
Alp Toker1b935a82014-06-08 05:40:04 +0000655
656 // GNU asms accept, but warn, about type-qualifiers other than volatile.
657 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
658 Diag(Loc, diag::w_asm_qualifier_ignored) << "const";
659 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
660 Diag(Loc, diag::w_asm_qualifier_ignored) << "restrict";
661 // FIXME: Once GCC supports _Atomic, check whether it permits it here.
662 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
663 Diag(Loc, diag::w_asm_qualifier_ignored) << "_Atomic";
664
665 // Remember if this was a volatile asm.
666 bool isVolatile = DS.getTypeQualifiers() & DeclSpec::TQ_volatile;
667 if (Tok.isNot(tok::l_paren)) {
668 Diag(Tok, diag::err_expected_lparen_after) << "asm";
669 SkipUntil(tok::r_paren, StopAtSemi);
670 return StmtError();
671 }
672 BalancedDelimiterTracker T(*this, tok::l_paren);
673 T.consumeOpen();
674
675 ExprResult AsmString(ParseAsmStringLiteral());
Steven Wu18bbe192015-05-12 00:16:37 +0000676
677 // Check if GNU-style InlineAsm is disabled.
678 // Error on anything other than empty string.
679 if (!(getLangOpts().GNUAsm || AsmString.isInvalid())) {
680 const auto *SL = cast<StringLiteral>(AsmString.get());
681 if (!SL->getString().trim().empty())
682 Diag(Loc, diag::err_gnu_inline_asm_disabled);
683 }
684
Alp Toker1b935a82014-06-08 05:40:04 +0000685 if (AsmString.isInvalid()) {
686 // Consume up to and including the closing paren.
687 T.skipToEnd();
688 return StmtError();
689 }
690
691 SmallVector<IdentifierInfo *, 4> Names;
692 ExprVector Constraints;
693 ExprVector Exprs;
694 ExprVector Clobbers;
695
696 if (Tok.is(tok::r_paren)) {
697 // We have a simple asm expression like 'asm("foo")'.
698 T.consumeClose();
699 return Actions.ActOnGCCAsmStmt(AsmLoc, /*isSimple*/ true, isVolatile,
700 /*NumOutputs*/ 0, /*NumInputs*/ 0, nullptr,
701 Constraints, Exprs, AsmString.get(),
702 Clobbers, T.getCloseLocation());
703 }
704
705 // Parse Outputs, if present.
706 bool AteExtraColon = false;
707 if (Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
708 // In C++ mode, parse "::" like ": :".
709 AteExtraColon = Tok.is(tok::coloncolon);
710 ConsumeToken();
711
712 if (!AteExtraColon && ParseAsmOperandsOpt(Names, Constraints, Exprs))
713 return StmtError();
714 }
715
716 unsigned NumOutputs = Names.size();
717
718 // Parse Inputs, if present.
719 if (AteExtraColon || Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
720 // In C++ mode, parse "::" like ": :".
721 if (AteExtraColon)
722 AteExtraColon = false;
723 else {
724 AteExtraColon = Tok.is(tok::coloncolon);
725 ConsumeToken();
726 }
727
728 if (!AteExtraColon && ParseAsmOperandsOpt(Names, Constraints, Exprs))
729 return StmtError();
730 }
731
732 assert(Names.size() == Constraints.size() &&
733 Constraints.size() == Exprs.size() && "Input operand size mismatch!");
734
735 unsigned NumInputs = Names.size() - NumOutputs;
736
737 // Parse the clobbers, if present.
738 if (AteExtraColon || Tok.is(tok::colon)) {
739 if (!AteExtraColon)
740 ConsumeToken();
741
742 // Parse the asm-string list for clobbers if present.
743 if (Tok.isNot(tok::r_paren)) {
744 while (1) {
745 ExprResult Clobber(ParseAsmStringLiteral());
746
747 if (Clobber.isInvalid())
748 break;
749
750 Clobbers.push_back(Clobber.get());
751
752 if (!TryConsumeToken(tok::comma))
753 break;
754 }
755 }
756 }
757
758 T.consumeClose();
759 return Actions.ActOnGCCAsmStmt(
760 AsmLoc, false, isVolatile, NumOutputs, NumInputs, Names.data(),
761 Constraints, Exprs, AsmString.get(), Clobbers, T.getCloseLocation());
762}
763
764/// ParseAsmOperands - Parse the asm-operands production as used by
765/// asm-statement, assuming the leading ':' token was eaten.
766///
767/// [GNU] asm-operands:
768/// asm-operand
769/// asm-operands ',' asm-operand
770///
771/// [GNU] asm-operand:
772/// asm-string-literal '(' expression ')'
773/// '[' identifier ']' asm-string-literal '(' expression ')'
774///
775//
776// FIXME: Avoid unnecessary std::string trashing.
777bool Parser::ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
778 SmallVectorImpl<Expr *> &Constraints,
779 SmallVectorImpl<Expr *> &Exprs) {
780 // 'asm-operands' isn't present?
781 if (!isTokenStringLiteral() && Tok.isNot(tok::l_square))
782 return false;
783
784 while (1) {
785 // Read the [id] if present.
786 if (Tok.is(tok::l_square)) {
787 BalancedDelimiterTracker T(*this, tok::l_square);
788 T.consumeOpen();
789
790 if (Tok.isNot(tok::identifier)) {
791 Diag(Tok, diag::err_expected) << tok::identifier;
792 SkipUntil(tok::r_paren, StopAtSemi);
793 return true;
794 }
795
796 IdentifierInfo *II = Tok.getIdentifierInfo();
797 ConsumeToken();
798
799 Names.push_back(II);
800 T.consumeClose();
801 } else
802 Names.push_back(nullptr);
803
804 ExprResult Constraint(ParseAsmStringLiteral());
805 if (Constraint.isInvalid()) {
806 SkipUntil(tok::r_paren, StopAtSemi);
807 return true;
808 }
809 Constraints.push_back(Constraint.get());
810
811 if (Tok.isNot(tok::l_paren)) {
812 Diag(Tok, diag::err_expected_lparen_after) << "asm operand";
813 SkipUntil(tok::r_paren, StopAtSemi);
814 return true;
815 }
816
817 // Read the parenthesized expression.
818 BalancedDelimiterTracker T(*this, tok::l_paren);
819 T.consumeOpen();
Kaelyn Takata15867822014-11-21 18:48:04 +0000820 ExprResult Res = Actions.CorrectDelayedTyposInExpr(ParseExpression());
Alp Toker1b935a82014-06-08 05:40:04 +0000821 T.consumeClose();
822 if (Res.isInvalid()) {
823 SkipUntil(tok::r_paren, StopAtSemi);
824 return true;
825 }
826 Exprs.push_back(Res.get());
827 // Eat the comma and continue parsing if it exists.
828 if (!TryConsumeToken(tok::comma))
829 return false;
830 }
831}