Coverage Report

Created: 2020-09-19 12:23

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Parse/ParseStmtAsm.cpp
Line
Count
Source (jump to first uncovered line)
1
//===---- ParseStmtAsm.cpp - Assembly Statement Parser --------------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
// This file implements parsing for GCC and Microsoft inline assembly.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/Parse/Parser.h"
14
#include "clang/AST/ASTContext.h"
15
#include "clang/Basic/Diagnostic.h"
16
#include "clang/Basic/TargetInfo.h"
17
#include "clang/Parse/RAIIObjectsForParser.h"
18
#include "llvm/ADT/SmallString.h"
19
#include "llvm/ADT/StringExtras.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/MCParser/MCTargetAsmParser.h"
27
#include "llvm/MC/MCRegisterInfo.h"
28
#include "llvm/MC/MCStreamer.h"
29
#include "llvm/MC/MCSubtargetInfo.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;
35
36
namespace {
37
class ClangAsmParserCallback : public llvm::MCAsmParserSemaCallback {
38
  Parser &TheParser;
39
  SourceLocation AsmLoc;
40
  StringRef AsmString;
41
42
  /// The tokens we streamed into AsmString and handed off to MC.
43
  ArrayRef<Token> AsmToks;
44
45
  /// The offset of each token in AsmToks within AsmString.
46
  ArrayRef<unsigned> AsmTokOffsets;
47
48
public:
49
  ClangAsmParserCallback(Parser &P, SourceLocation Loc, StringRef AsmString,
50
                         ArrayRef<Token> Toks, ArrayRef<unsigned> Offsets)
51
      : TheParser(P), AsmLoc(Loc), AsmString(AsmString), AsmToks(Toks),
52
227
        AsmTokOffsets(Offsets) {
53
227
    assert(AsmToks.size() == AsmTokOffsets.size());
54
227
  }
55
56
  void LookupInlineAsmIdentifier(StringRef &LineBuf,
57
                                 llvm::InlineAsmIdentifierInfo &Info,
58
                                 bool IsUnevaluatedContext) override;
59
60
  StringRef LookupInlineAsmLabel(StringRef Identifier, llvm::SourceMgr &LSM,
61
                                 llvm::SMLoc Location,
62
                                 bool Create) override;
63
64
  bool LookupInlineAsmField(StringRef Base, StringRef Member,
65
25
                            unsigned &Offset) override {
66
25
    return TheParser.getActions().LookupInlineAsmField(Base, Member, Offset,
67
25
                                                       AsmLoc);
68
25
  }
69
70
20
  static void DiagHandlerCallback(const llvm::SMDiagnostic &D, void *Context) {
71
20
    ((ClangAsmParserCallback *)Context)->handleDiagnostic(D);
72
20
  }
73
74
private:
75
  /// Collect the appropriate tokens for the given string.
76
  void findTokensForString(StringRef Str, SmallVectorImpl<Token> &TempToks,
77
                           const Token *&FirstOrigToken) const;
78
79
  SourceLocation translateLocation(const llvm::SourceMgr &LSM,
80
                                   llvm::SMLoc SMLoc);
81
82
  void handleDiagnostic(const llvm::SMDiagnostic &D);
83
};
84
}
85
86
void ClangAsmParserCallback::LookupInlineAsmIdentifier(
87
    StringRef &LineBuf, llvm::InlineAsmIdentifierInfo &Info,
88
230
    bool IsUnevaluatedContext) {
89
  // Collect the desired tokens.
90
230
  SmallVector<Token, 16> LineToks;
91
230
  const Token *FirstOrigToken = nullptr;
92
230
  findTokensForString(LineBuf, LineToks, FirstOrigToken);
93
230
94
230
  unsigned NumConsumedToks;
95
230
  ExprResult Result = TheParser.ParseMSAsmIdentifier(LineToks, NumConsumedToks,
96
230
                                                     IsUnevaluatedContext);
97
230
98
  // If we consumed the entire line, tell MC that.
99
  // Also do this if we consumed nothing as a way of reporting failure.
100
230
  if (NumConsumedToks == 0 || NumConsumedToks == LineToks.size()) {
101
    // By not modifying LineBuf, we're implicitly consuming it all.
102
49
103
    // Otherwise, consume up to the original tokens.
104
181
  } else {
105
181
    assert(FirstOrigToken && "not using original tokens?");
106
181
107
    // Since we're using original tokens, apply that offset.
108
181
    assert(FirstOrigToken[NumConsumedToks].getLocation() ==
109
181
           LineToks[NumConsumedToks].getLocation());
110
181
    unsigned FirstIndex = FirstOrigToken - AsmToks.begin();
111
181
    unsigned LastIndex = FirstIndex + NumConsumedToks - 1;
112
181
113
    // The total length we've consumed is the relative offset
114
    // of the last token we consumed plus its length.
115
181
    unsigned TotalOffset =
116
181
        (AsmTokOffsets[LastIndex] + AsmToks[LastIndex].getLength() -
117
181
         AsmTokOffsets[FirstIndex]);
118
181
    LineBuf = LineBuf.substr(0, TotalOffset);
119
181
  }
120
230
121
  // Initialize Info with the lookup result.
122
230
  if (!Result.isUsable())
123
25
    return;
124
205
  TheParser.getActions().FillInlineAsmIdentifierInfo(Result.get(), Info);
125
205
}
126
127
StringRef ClangAsmParserCallback::LookupInlineAsmLabel(StringRef Identifier,
128
                                                       llvm::SourceMgr &LSM,
129
                                                       llvm::SMLoc Location,
130
43
                                                       bool Create) {
131
43
  SourceLocation Loc = translateLocation(LSM, Location);
132
43
  LabelDecl *Label =
133
43
      TheParser.getActions().GetOrCreateMSAsmLabel(Identifier, Loc, Create);
134
43
  return Label->getMSAsmLabel();
135
43
}
136
137
void ClangAsmParserCallback::findTokensForString(
138
    StringRef Str, SmallVectorImpl<Token> &TempToks,
139
230
    const Token *&FirstOrigToken) const {
140
  // For now, assert that the string we're working with is a substring
141
  // of what we gave to MC.  This lets us use the original tokens.
142
230
  assert(!std::less<const char *>()(Str.begin(), AsmString.begin()) &&
143
230
         !std::less<const char *>()(AsmString.end(), Str.end()));
144
230
145
  // Try to find a token whose offset matches the first token.
146
230
  unsigned FirstCharOffset = Str.begin() - AsmString.begin();
147
230
  const unsigned *FirstTokOffset =
148
230
      llvm::lower_bound(AsmTokOffsets, FirstCharOffset);
149
230
150
  // For now, assert that the start of the string exactly
151
  // corresponds to the start of a token.
152
230
  assert(*FirstTokOffset == FirstCharOffset);
153
230
154
  // Use all the original tokens for this line.  (We assume the
155
  // end of the line corresponds cleanly to a token break.)
156
230
  unsigned FirstTokIndex = FirstTokOffset - AsmTokOffsets.begin();
157
230
  FirstOrigToken = &AsmToks[FirstTokIndex];
158
230
  unsigned LastCharOffset = Str.end() - AsmString.begin();
159
4.09k
  for (unsigned i = FirstTokIndex, e = AsmTokOffsets.size(); i != e; 
++i3.86k
) {
160
3.86k
    if (AsmTokOffsets[i] >= LastCharOffset)
161
0
      break;
162
3.86k
    TempToks.push_back(AsmToks[i]);
163
3.86k
  }
164
230
}
165
166
SourceLocation
167
ClangAsmParserCallback::translateLocation(const llvm::SourceMgr &LSM,
168
63
                                          llvm::SMLoc SMLoc) {
169
  // Compute an offset into the inline asm buffer.
170
  // FIXME: This isn't right if .macro is involved (but hopefully, no
171
  // real-world code does that).
172
63
  const llvm::MemoryBuffer *LBuf =
173
63
      LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(SMLoc));
174
63
  unsigned Offset = SMLoc.getPointer() - LBuf->getBufferStart();
175
63
176
  // Figure out which token that offset points into.
177
63
  const unsigned *TokOffsetPtr = llvm::lower_bound(AsmTokOffsets, Offset);
178
63
  unsigned TokIndex = TokOffsetPtr - AsmTokOffsets.begin();
179
63
  unsigned TokOffset = *TokOffsetPtr;
180
63
181
  // If we come up with an answer which seems sane, use it; otherwise,
182
  // just point at the __asm keyword.
183
  // FIXME: Assert the answer is sane once we handle .macro correctly.
184
63
  SourceLocation Loc = AsmLoc;
185
63
  if (TokIndex < AsmToks.size()) {
186
61
    const Token &Tok = AsmToks[TokIndex];
187
61
    Loc = Tok.getLocation();
188
61
    Loc = Loc.getLocWithOffset(Offset - TokOffset);
189
61
  }
190
63
  return Loc;
191
63
}
192
193
20
void ClangAsmParserCallback::handleDiagnostic(const llvm::SMDiagnostic &D) {
194
20
  const llvm::SourceMgr &LSM = *D.getSourceMgr();
195
20
  SourceLocation Loc = translateLocation(LSM, D.getLoc());
196
20
  TheParser.Diag(Loc, diag::err_inline_ms_asm_parsing) << D.getMessage();
197
20
}
198
199
/// Parse an identifier in an MS-style inline assembly block.
200
ExprResult Parser::ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks,
201
                                        unsigned &NumLineToksConsumed,
202
230
                                        bool IsUnevaluatedContext) {
203
  // Push a fake token on the end so that we don't overrun the token
204
  // stream.  We use ';' because it expression-parsing should never
205
  // overrun it.
206
230
  const tok::TokenKind EndOfStream = tok::semi;
207
230
  Token EndOfStreamTok;
208
230
  EndOfStreamTok.startToken();
209
230
  EndOfStreamTok.setKind(EndOfStream);
210
230
  LineToks.push_back(EndOfStreamTok);
211
230
212
  // Also copy the current token over.
213
230
  LineToks.push_back(Tok);
214
230
215
230
  PP.EnterTokenStream(LineToks, /*DisableMacroExpansions*/ true,
216
230
                      /*IsReinject*/ true);
217
230
218
  // Clear the current token and advance to the first token in LineToks.
219
230
  ConsumeAnyToken();
220
230
221
  // Parse an optional scope-specifier if we're in C++.
222
230
  CXXScopeSpec SS;
223
230
  if (getLangOpts().CPlusPlus)
224
63
    ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
225
63
                                   /*ObjectHadErrors=*/false,
226
63
                                   /*EnteringContext=*/false);
227
230
228
  // Require an identifier here.
229
230
  SourceLocation TemplateKWLoc;
230
230
  UnqualifiedId Id;
231
230
  bool Invalid = true;
232
230
  ExprResult Result;
233
230
  if (Tok.is(tok::kw_this)) {
234
3
    Result = ParseCXXThis();
235
3
    Invalid = false;
236
227
  } else {
237
227
    Invalid =
238
227
        ParseUnqualifiedId(SS, /*ObjectType=*/nullptr,
239
227
                           /*ObjectHadErrors=*/false,
240
227
                           /*EnteringContext=*/false,
241
227
                           /*AllowDestructorName=*/false,
242
227
                           /*AllowConstructorName=*/false,
243
227
                           /*AllowDeductionGuide=*/false, &TemplateKWLoc, Id);
244
    // Perform the lookup.
245
227
    Result = Actions.LookupInlineAsmIdentifier(SS, TemplateKWLoc, Id,
246
227
                                               IsUnevaluatedContext);
247
227
  }
248
  // While the next two tokens are 'period' 'identifier', repeatedly parse it as
249
  // a field access. We have to avoid consuming assembler directives that look
250
  // like '.' 'else'.
251
272
  while (Result.isUsable() && 
Tok.is(tok::period)247
) {
252
42
    Token IdTok = PP.LookAhead(0);
253
42
    if (IdTok.isNot(tok::identifier))
254
0
      break;
255
42
    ConsumeToken(); // Consume the period.
256
42
    IdentifierInfo *Id = Tok.getIdentifierInfo();
257
42
    ConsumeToken(); // Consume the identifier.
258
42
    Result = Actions.LookupInlineAsmVarDeclField(Result.get(), Id->getName(),
259
42
                                                 Tok.getLocation());
260
42
  }
261
230
262
  // Figure out how many tokens we are into LineToks.
263
230
  unsigned LineIndex = 0;
264
230
  if (Tok.is(EndOfStream)) {
265
49
    LineIndex = LineToks.size() - 2;
266
181
  } else {
267
472
    while (LineToks[LineIndex].getLocation() != Tok.getLocation()) {
268
291
      LineIndex++;
269
291
      assert(LineIndex < LineToks.size() - 2); // we added two extra tokens
270
291
    }
271
181
  }
272
230
273
  // If we've run into the poison token we inserted before, or there
274
  // was a parsing error, then claim the entire line.
275
230
  if (Invalid || Tok.is(EndOfStream)) {
276
49
    NumLineToksConsumed = LineToks.size() - 2;
277
181
  } else {
278
    // Otherwise, claim up to the start of the next token.
279
181
    NumLineToksConsumed = LineIndex;
280
181
  }
281
230
282
  // Finally, restore the old parsing state by consuming all the tokens we
283
  // staged before, implicitly killing off the token-lexer we pushed.
284
3.69k
  for (unsigned i = 0, e = LineToks.size() - LineIndex - 2; i != e; 
++i3.46k
) {
285
3.46k
    ConsumeAnyToken();
286
3.46k
  }
287
230
  assert(Tok.is(EndOfStream));
288
230
  ConsumeToken();
289
230
290
  // Leave LineToks in its original state.
291
230
  LineToks.pop_back();
292
230
  LineToks.pop_back();
293
230
294
230
  return Result;
295
230
}
296
297
/// Turn a sequence of our tokens back into a string that we can hand
298
/// to the MC asm parser.
299
static bool buildMSAsmString(Preprocessor &PP, SourceLocation AsmLoc,
300
                             ArrayRef<Token> AsmToks,
301
                             SmallVectorImpl<unsigned> &TokOffsets,
302
228
                             SmallString<512> &Asm) {
303
228
  assert(!AsmToks.empty() && "Didn't expect an empty AsmToks!");
304
228
305
  // Is this the start of a new assembly statement?
306
228
  bool isNewStatement = true;
307
228
308
3.02k
  for (unsigned i = 0, e = AsmToks.size(); i < e; 
++i2.79k
) {
309
2.79k
    const Token &Tok = AsmToks[i];
310
2.79k
311
    // Start each new statement with a newline and a tab.
312
2.79k
    if (!isNewStatement && 
(2.41k
Tok.is(tok::kw_asm)2.41k
||
Tok.isAtStartOfLine()2.26k
)) {
313
248
      Asm += "\n\t";
314
248
      isNewStatement = true;
315
248
    }
316
2.79k
317
    // Preserve the existence of leading whitespace except at the
318
    // start of a statement.
319
2.79k
    if (!isNewStatement && 
Tok.hasLeadingSpace()2.16k
)
320
1.10k
      Asm += ' ';
321
2.79k
322
    // Remember the offset of this token.
323
2.79k
    TokOffsets.push_back(Asm.size());
324
2.79k
325
    // Don't actually write '__asm' into the assembly stream.
326
2.79k
    if (Tok.is(tok::kw_asm)) {
327
      // Complain about __asm at the end of the stream.
328
155
      if (i + 1 == e) {
329
1
        PP.Diag(AsmLoc, diag::err_asm_empty);
330
1
        return true;
331
1
      }
332
154
333
154
      continue;
334
154
    }
335
2.64k
336
    // Append the spelling of the token.
337
2.64k
    SmallString<32> SpellingBuffer;
338
2.64k
    bool SpellingInvalid = false;
339
2.64k
    Asm += PP.getSpelling(Tok, SpellingBuffer, &SpellingInvalid);
340
2.64k
    assert(!SpellingInvalid && "spelling was invalid after correct parse?");
341
2.64k
342
    // We are no longer at the start of a statement.
343
2.64k
    isNewStatement = false;
344
2.64k
  }
345
228
346
  // Ensure that the buffer is null-terminated.
347
227
  Asm.push_back('\0');
348
227
  Asm.pop_back();
349
227
350
227
  assert(TokOffsets.size() == AsmToks.size());
351
227
  return false;
352
228
}
353
354
// Determine if this is a GCC-style asm statement.
355
755
bool Parser::isGCCAsmStatement(const Token &TokAfterAsm) const {
356
755
  return TokAfterAsm.is(tok::l_paren) || 
isGNUAsmQualifier(TokAfterAsm)607
;
357
755
}
358
359
59.7k
bool Parser::isGNUAsmQualifier(const Token &TokAfterAsm) const {
360
59.7k
  return getGNUAsmQualifier(TokAfterAsm) != GNUAsmQualifiers::AQ_unspecified;
361
59.7k
}
362
363
/// ParseMicrosoftAsmStatement. When -fms-extensions/-fasm-blocks is enabled,
364
/// this routine is called to collect the tokens for an MS asm statement.
365
///
366
/// [MS]  ms-asm-statement:
367
///         ms-asm-block
368
///         ms-asm-block ms-asm-statement
369
///
370
/// [MS]  ms-asm-block:
371
///         '__asm' ms-asm-line '\n'
372
///         '__asm' '{' ms-asm-instruction-block[opt] '}' ';'[opt]
373
///
374
/// [MS]  ms-asm-instruction-block
375
///         ms-asm-line
376
///         ms-asm-line '\n' ms-asm-instruction-block
377
///
378
243
StmtResult Parser::ParseMicrosoftAsmStatement(SourceLocation AsmLoc) {
379
243
  SourceManager &SrcMgr = PP.getSourceManager();
380
243
  SourceLocation EndLoc = AsmLoc;
381
243
  SmallVector<Token, 4> AsmToks;
382
243
383
243
  bool SingleLineMode = true;
384
243
  unsigned BraceNesting = 0;
385
243
  unsigned short savedBraceCount = BraceCount;
386
243
  bool InAsmComment = false;
387
243
  FileID FID;
388
243
  unsigned LineNo = 0;
389
243
  unsigned NumTokensRead = 0;
390
243
  SmallVector<SourceLocation, 4> LBraceLocs;
391
243
  bool SkippedStartOfLine = false;
392
243
393
243
  if (Tok.is(tok::l_brace)) {
394
    // Braced inline asm: consume the opening brace.
395
129
    SingleLineMode = false;
396
129
    BraceNesting = 1;
397
129
    EndLoc = ConsumeBrace();
398
129
    LBraceLocs.push_back(EndLoc);
399
129
    ++NumTokensRead;
400
114
  } else {
401
    // Single-line inline asm; compute which line it is on.
402
114
    std::pair<FileID, unsigned> ExpAsmLoc =
403
114
        SrcMgr.getDecomposedExpansionLoc(EndLoc);
404
114
    FID = ExpAsmLoc.first;
405
114
    LineNo = SrcMgr.getLineNumber(FID, ExpAsmLoc.second);
406
114
    LBraceLocs.push_back(SourceLocation());
407
114
  }
408
243
409
243
  SourceLocation TokLoc = Tok.getLocation();
410
3.19k
  do {
411
    // If we hit EOF, we're done, period.
412
3.19k
    if (isEofOrEom())
413
3
      break;
414
3.19k
415
3.19k
    if (!InAsmComment && 
Tok.is(tok::l_brace)3.04k
) {
416
      // Consume the opening brace.
417
17
      SkippedStartOfLine = Tok.isAtStartOfLine();
418
17
      AsmToks.push_back(Tok);
419
17
      EndLoc = ConsumeBrace();
420
17
      BraceNesting++;
421
17
      LBraceLocs.push_back(EndLoc);
422
17
      TokLoc = Tok.getLocation();
423
17
      ++NumTokensRead;
424
17
      continue;
425
3.17k
    } else if (!InAsmComment && 
Tok.is(tok::semi)3.02k
) {
426
      // A semicolon in an asm is the start of a comment.
427
48
      InAsmComment = true;
428
48
      if (!SingleLineMode) {
429
        // Compute which line the comment is on.
430
9
        std::pair<FileID, unsigned> ExpSemiLoc =
431
9
            SrcMgr.getDecomposedExpansionLoc(TokLoc);
432
9
        FID = ExpSemiLoc.first;
433
9
        LineNo = SrcMgr.getLineNumber(FID, ExpSemiLoc.second);
434
9
      }
435
3.12k
    } else if (SingleLineMode || 
InAsmComment1.40k
) {
436
      // If end-of-line is significant, check whether this token is on a
437
      // new line.
438
1.76k
      std::pair<FileID, unsigned> ExpLoc =
439
1.76k
          SrcMgr.getDecomposedExpansionLoc(TokLoc);
440
1.76k
      if (ExpLoc.first != FID ||
441
1.76k
          SrcMgr.getLineNumber(ExpLoc.first, ExpLoc.second) != LineNo) {
442
        // If this is a single-line __asm, we're done, except if the next
443
        // line is MS-style asm too, in which case we finish a comment
444
        // if needed and then keep processing the next line as a single
445
        // line __asm.
446
245
        bool isAsm = Tok.is(tok::kw_asm);
447
245
        if (SingleLineMode && 
(235
!isAsm235
||
isGCCAsmStatement(NextToken())141
))
448
97
          break;
449
        // We're no longer in a comment.
450
148
        InAsmComment = false;
451
148
        if (isAsm) {
452
          // If this is a new __asm {} block we want to process it separately
453
          // from the single-line __asm statements
454
138
          if (PP.LookAhead(0).is(tok::l_brace))
455
7
            break;
456
131
          LineNo = SrcMgr.getLineNumber(ExpLoc.first, ExpLoc.second);
457
131
          SkippedStartOfLine = Tok.isAtStartOfLine();
458
10
        } else if (Tok.is(tok::semi)) {
459
          // A multi-line asm-statement, where next line is a comment
460
1
          InAsmComment = true;
461
1
          FID = ExpLoc.first;
462
1
          LineNo = SrcMgr.getLineNumber(FID, ExpLoc.second);
463
1
        }
464
1.51k
      } else if (!InAsmComment && 
Tok.is(tok::r_brace)1.41k
) {
465
        // In MSVC mode, braces only participate in brace matching and
466
        // separating the asm statements.  This is an intentional
467
        // departure from the Apple gcc behavior.
468
15
        if (!BraceNesting)
469
10
          break;
470
3.06k
      }
471
1.76k
    }
472
3.06k
    if (!InAsmComment && 
BraceNesting2.91k
&&
Tok.is(tok::r_brace)1.39k
&&
473
142
        BraceCount == (savedBraceCount + BraceNesting)) {
474
      // Consume the closing brace.
475
142
      SkippedStartOfLine = Tok.isAtStartOfLine();
476
      // Don't want to add the closing brace of the whole asm block
477
142
      if (SingleLineMode || 
BraceNesting > 1137
) {
478
16
        Tok.clearFlag(Token::LeadingSpace);
479
16
        AsmToks.push_back(Tok);
480
16
      }
481
142
      EndLoc = ConsumeBrace();
482
142
      BraceNesting--;
483
      // Finish if all of the opened braces in the inline asm section were
484
      // consumed.
485
142
      if (BraceNesting == 0 && 
!SingleLineMode131
)
486
126
        break;
487
16
      else {
488
16
        LBraceLocs.pop_back();
489
16
        TokLoc = Tok.getLocation();
490
16
        ++NumTokensRead;
491
16
        continue;
492
16
      }
493
2.91k
    }
494
2.91k
495
    // Consume the next token; make sure we don't modify the brace count etc.
496
    // if we are in a comment.
497
2.91k
    EndLoc = TokLoc;
498
2.91k
    if (InAsmComment)
499
150
      PP.Lex(Tok);
500
2.76k
    else {
501
      // Set the token as the start of line if we skipped the original start
502
      // of line token in case it was a nested brace.
503
2.76k
      if (SkippedStartOfLine)
504
138
        Tok.setFlag(Token::StartOfLine);
505
2.76k
      AsmToks.push_back(Tok);
506
2.76k
      ConsumeAnyToken();
507
2.76k
    }
508
2.91k
    TokLoc = Tok.getLocation();
509
2.91k
    ++NumTokensRead;
510
2.91k
    SkippedStartOfLine = false;
511
2.95k
  } while (1);
512
243
513
243
  if (BraceNesting && 
BraceCount != savedBraceCount3
) {
514
    // __asm without closing brace (this can happen at EOF).
515
7
    for (unsigned i = 0; i < BraceNesting; 
++i4
) {
516
4
      Diag(Tok, diag::err_expected) << tok::r_brace;
517
4
      Diag(LBraceLocs.back(), diag::note_matching) << tok::l_brace;
518
4
      LBraceLocs.pop_back();
519
4
    }
520
3
    return StmtError();
521
240
  } else if (NumTokensRead == 0) {
522
    // Empty __asm.
523
2
    Diag(Tok, diag::err_expected) << tok::l_brace;
524
2
    return StmtError();
525
2
  }
526
238
527
  // Okay, prepare to use MC to parse the assembly.
528
238
  SmallVector<StringRef, 4> ConstraintRefs;
529
238
  SmallVector<Expr *, 4> Exprs;
530
238
  SmallVector<StringRef, 4> ClobberRefs;
531
238
532
  // We need an actual supported target.
533
238
  const llvm::Triple &TheTriple = Actions.Context.getTargetInfo().getTriple();
534
238
  const std::string &TT = TheTriple.getTriple();
535
238
  const llvm::Target *TheTarget = nullptr;
536
238
  if (!TheTriple.isX86()) {
537
1
    Diag(AsmLoc, diag::err_msasm_unsupported_arch) << TheTriple.getArchName();
538
237
  } else {
539
237
    std::string Error;
540
237
    TheTarget = llvm::TargetRegistry::lookupTarget(TT, Error);
541
237
    if (!TheTarget)
542
0
      Diag(AsmLoc, diag::err_msasm_unable_to_create_target) << Error;
543
237
  }
544
238
545
238
  assert(!LBraceLocs.empty() && "Should have at least one location here");
546
238
547
238
  SmallString<512> AsmString;
548
10
  auto EmptyStmt = [&] {
549
10
    return Actions.ActOnMSAsmStmt(AsmLoc, LBraceLocs[0], AsmToks, AsmString,
550
10
                                  /*NumOutputs*/ 0, /*NumInputs*/ 0,
551
10
                                  ConstraintRefs, ClobberRefs, Exprs, EndLoc);
552
10
  };
553
  // If we don't support assembly, or the assembly is empty, we don't
554
  // need to instantiate the AsmParser, etc.
555
238
  if (!TheTarget || 
AsmToks.empty()237
) {
556
10
    return EmptyStmt();
557
10
  }
558
228
559
  // Expand the tokens into a string buffer.
560
228
  SmallVector<unsigned, 8> TokOffsets;
561
228
  if (buildMSAsmString(PP, AsmLoc, AsmToks, TokOffsets, AsmString))
562
1
    return StmtError();
563
227
564
227
  const TargetOptions &TO = Actions.Context.getTargetInfo().getTargetOpts();
565
227
  std::string FeaturesStr =
566
227
      llvm::join(TO.Features.begin(), TO.Features.end(), ",");
567
227
568
227
  std::unique_ptr<llvm::MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TT));
569
227
  if (!MRI) {
570
0
    Diag(AsmLoc, diag::err_msasm_unable_to_create_target)
571
0
        << "target MC unavailable";
572
0
    return EmptyStmt();
573
0
  }
574
  // FIXME: init MCOptions from sanitizer flags here.
575
227
  llvm::MCTargetOptions MCOptions;
576
227
  std::unique_ptr<llvm::MCAsmInfo> MAI(
577
227
      TheTarget->createMCAsmInfo(*MRI, TT, MCOptions));
578
  // Get the instruction descriptor.
579
227
  std::unique_ptr<llvm::MCInstrInfo> MII(TheTarget->createMCInstrInfo());
580
227
  std::unique_ptr<llvm::MCObjectFileInfo> MOFI(new llvm::MCObjectFileInfo());
581
227
  std::unique_ptr<llvm::MCSubtargetInfo> STI(
582
227
      TheTarget->createMCSubtargetInfo(TT, TO.CPU, FeaturesStr));
583
  // Target MCTargetDesc may not be linked in clang-based tools.
584
227
  if (!MAI || !MII | !MOFI || !STI) {
585
0
    Diag(AsmLoc, diag::err_msasm_unable_to_create_target)
586
0
        << "target MC unavailable";
587
0
    return EmptyStmt();
588
0
  }
589
227
590
227
  llvm::SourceMgr TempSrcMgr;
591
227
  llvm::MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &TempSrcMgr);
592
227
  MOFI->InitMCObjectFileInfo(TheTriple, /*PIC*/ false, Ctx);
593
227
  std::unique_ptr<llvm::MemoryBuffer> Buffer =
594
227
      llvm::MemoryBuffer::getMemBuffer(AsmString, "<MS inline asm>");
595
227
596
  // Tell SrcMgr about this buffer, which is what the parser will pick up.
597
227
  TempSrcMgr.AddNewSourceBuffer(std::move(Buffer), llvm::SMLoc());
598
227
599
227
  std::unique_ptr<llvm::MCStreamer> Str(createNullStreamer(Ctx));
600
227
  std::unique_ptr<llvm::MCAsmParser> Parser(
601
227
      createMCAsmParser(TempSrcMgr, Ctx, *Str.get(), *MAI));
602
227
603
227
  std::unique_ptr<llvm::MCTargetAsmParser> TargetParser(
604
227
      TheTarget->createMCAsmParser(*STI, *Parser, *MII, MCOptions));
605
  // Target AsmParser may not be linked in clang-based tools.
606
227
  if (!TargetParser) {
607
0
    Diag(AsmLoc, diag::err_msasm_unable_to_create_target)
608
0
        << "target ASM parser unavailable";
609
0
    return EmptyStmt();
610
0
  }
611
227
612
227
  std::unique_ptr<llvm::MCInstPrinter> IP(
613
227
      TheTarget->createMCInstPrinter(llvm::Triple(TT), 1, *MAI, *MII, *MRI));
614
227
615
  // Change to the Intel dialect.
616
227
  Parser->setAssemblerDialect(1);
617
227
  Parser->setTargetParser(*TargetParser.get());
618
227
  Parser->setParsingMSInlineAsm(true);
619
227
  TargetParser->setParsingMSInlineAsm(true);
620
227
621
227
  ClangAsmParserCallback Callback(*this, AsmLoc, AsmString, AsmToks,
622
227
                                  TokOffsets);
623
227
  TargetParser->setSemaCallback(&Callback);
624
227
  TempSrcMgr.setDiagHandler(ClangAsmParserCallback::DiagHandlerCallback,
625
227
                            &Callback);
626
227
627
227
  unsigned NumOutputs;
628
227
  unsigned NumInputs;
629
227
  std::string AsmStringIR;
630
227
  SmallVector<std::pair<void *, bool>, 4> OpExprs;
631
227
  SmallVector<std::string, 4> Constraints;
632
227
  SmallVector<std::string, 4> Clobbers;
633
227
  if (Parser->parseMSInlineAsm(AsmLoc.getPtrEncoding(), AsmStringIR, NumOutputs,
634
227
                               NumInputs, OpExprs, Constraints, Clobbers,
635
227
                               MII.get(), IP.get(), Callback))
636
20
    return StmtError();
637
207
638
  // Filter out "fpsw" and "mxcsr". They aren't valid GCC asm clobber
639
  // constraints. Clang always adds fpsr to the clobber list anyway.
640
231
  
llvm::erase_if(Clobbers, [](const std::string &C) 207
{
641
231
    return C == "fpsr" || 
C == "mxcsr"229
;
642
231
  });
643
207
644
  // Build the vector of clobber StringRefs.
645
207
  ClobberRefs.insert(ClobberRefs.end(), Clobbers.begin(), Clobbers.end());
646
207
647
  // Recast the void pointers and build the vector of constraint StringRefs.
648
207
  unsigned NumExprs = NumOutputs + NumInputs;
649
207
  ConstraintRefs.resize(NumExprs);
650
207
  Exprs.resize(NumExprs);
651
350
  for (unsigned i = 0, e = NumExprs; i != e; 
++i143
) {
652
143
    Expr *OpExpr = static_cast<Expr *>(OpExprs[i].first);
653
143
    if (!OpExpr)
654
0
      return StmtError();
655
143
656
    // Need address of variable.
657
143
    if (OpExprs[i].second)
658
10
      OpExpr =
659
10
          Actions.BuildUnaryOp(getCurScope(), AsmLoc, UO_AddrOf, OpExpr).get();
660
143
661
143
    ConstraintRefs[i] = StringRef(Constraints[i]);
662
143
    Exprs[i] = OpExpr;
663
143
  }
664
207
665
  // FIXME: We should be passing source locations for better diagnostics.
666
207
  return Actions.ActOnMSAsmStmt(AsmLoc, LBraceLocs[0], AsmToks, AsmStringIR,
667
207
                                NumOutputs, NumInputs, ConstraintRefs,
668
207
                                ClobberRefs, Exprs, EndLoc);
669
207
}
670
671
/// parseGNUAsmQualifierListOpt - Parse a GNU extended asm qualifier list.
672
///       asm-qualifier:
673
///         volatile
674
///         inline
675
///         goto
676
///
677
///       asm-qualifier-list:
678
///         asm-qualifier
679
///         asm-qualifier-list asm-qualifier
680
5.88k
bool Parser::parseGNUAsmQualifierListOpt(GNUAsmQualifiers &AQ) {
681
7.77k
  while (1) {
682
7.77k
    const GNUAsmQualifiers::AQ A = getGNUAsmQualifier(Tok);
683
7.77k
    if (A == GNUAsmQualifiers::AQ_unspecified) {
684
5.88k
      if (Tok.isNot(tok::l_paren)) {
685
3
        Diag(Tok.getLocation(), diag::err_asm_qualifier_ignored);
686
3
        SkipUntil(tok::r_paren, StopAtSemi);
687
3
        return true;
688
3
      }
689
5.88k
      return false;
690
5.88k
    }
691
1.89k
    if (AQ.setAsmQualifier(A))
692
6
      Diag(Tok.getLocation(), diag::err_asm_duplicate_qual)
693
6
          << GNUAsmQualifiers::getQualifierName(A);
694
1.89k
    ConsumeToken();
695
1.89k
  }
696
0
  return false;
697
5.88k
}
698
699
/// ParseAsmStatement - Parse a GNU extended asm statement.
700
///       asm-statement:
701
///         gnu-asm-statement
702
///         ms-asm-statement
703
///
704
/// [GNU] gnu-asm-statement:
705
///         'asm' asm-qualifier-list[opt] '(' asm-argument ')' ';'
706
///
707
/// [GNU] asm-argument:
708
///         asm-string-literal
709
///         asm-string-literal ':' asm-operands[opt]
710
///         asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
711
///         asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
712
///                 ':' asm-clobbers
713
///
714
/// [GNU] asm-clobbers:
715
///         asm-string-literal
716
///         asm-clobbers ',' asm-string-literal
717
///
718
6.12k
StmtResult Parser::ParseAsmStatement(bool &msAsm) {
719
6.12k
  assert(Tok.is(tok::kw_asm) && "Not an asm stmt");
720
6.12k
  SourceLocation AsmLoc = ConsumeToken();
721
6.12k
722
6.12k
  if (getLangOpts().AsmBlocks && 
!isGCCAsmStatement(Tok)614
) {
723
243
    msAsm = true;
724
243
    return ParseMicrosoftAsmStatement(AsmLoc);
725
243
  }
726
5.88k
727
5.88k
  SourceLocation Loc = Tok.getLocation();
728
5.88k
  GNUAsmQualifiers GAQ;
729
5.88k
  if (parseGNUAsmQualifierListOpt(GAQ))
730
3
    return StmtError();
731
5.88k
732
5.88k
  if (GAQ.isGoto() && 
getLangOpts().SpeculativeLoadHardening143
)
733
2
    Diag(Loc, diag::warn_slh_does_not_support_asm_goto);
734
5.88k
735
5.88k
  BalancedDelimiterTracker T(*this, tok::l_paren);
736
5.88k
  T.consumeOpen();
737
5.88k
738
5.88k
  ExprResult AsmString(ParseAsmStringLiteral(/*ForAsmLabel*/ false));
739
5.88k
740
  // Check if GNU-style InlineAsm is disabled.
741
  // Error on anything other than empty string.
742
5.88k
  if (!(getLangOpts().GNUAsm || 
AsmString.isInvalid()2
)) {
743
2
    const auto *SL = cast<StringLiteral>(AsmString.get());
744
2
    if (!SL->getString().trim().empty())
745
1
      Diag(Loc, diag::err_gnu_inline_asm_disabled);
746
2
  }
747
5.88k
748
5.88k
  if (AsmString.isInvalid()) {
749
    // Consume up to and including the closing paren.
750
2
    T.skipToEnd();
751
2
    return StmtError();
752
2
  }
753
5.88k
754
5.88k
  SmallVector<IdentifierInfo *, 4> Names;
755
5.88k
  ExprVector Constraints;
756
5.88k
  ExprVector Exprs;
757
5.88k
  ExprVector Clobbers;
758
5.88k
759
5.88k
  if (Tok.is(tok::r_paren)) {
760
    // We have a simple asm expression like 'asm("foo")'.
761
268
    T.consumeClose();
762
268
    return Actions.ActOnGCCAsmStmt(
763
268
        AsmLoc, /*isSimple*/ true, GAQ.isVolatile(),
764
268
        /*NumOutputs*/ 0, /*NumInputs*/ 0, nullptr, Constraints, Exprs,
765
268
        AsmString.get(), Clobbers, /*NumLabels*/ 0, T.getCloseLocation());
766
268
  }
767
5.61k
768
  // Parse Outputs, if present.
769
5.61k
  bool AteExtraColon = false;
770
5.61k
  if (Tok.is(tok::colon) || 
Tok.is(tok::coloncolon)208
) {
771
    // In C++ mode, parse "::" like ": :".
772
5.61k
    AteExtraColon = Tok.is(tok::coloncolon);
773
5.61k
    ConsumeToken();
774
5.61k
775
5.61k
    if (!AteExtraColon && 
ParseAsmOperandsOpt(Names, Constraints, Exprs)5.40k
)
776
2
      return StmtError();
777
5.61k
  }
778
5.61k
779
5.61k
  unsigned NumOutputs = Names.size();
780
5.61k
781
  // Parse Inputs, if present.
782
5.61k
  if (AteExtraColon || 
Tok.is(tok::colon)5.40k
||
Tok.is(tok::coloncolon)157
) {
783
    // In C++ mode, parse "::" like ": :".
784
5.46k
    if (AteExtraColon)
785
208
      AteExtraColon = false;
786
5.26k
    else {
787
5.26k
      AteExtraColon = Tok.is(tok::coloncolon);
788
5.26k
      ConsumeToken();
789
5.26k
    }
790
5.46k
791
5.46k
    if (!AteExtraColon && 
ParseAsmOperandsOpt(Names, Constraints, Exprs)5.45k
)
792
3
      return StmtError();
793
5.60k
  }
794
5.60k
795
5.60k
  assert(Names.size() == Constraints.size() &&
796
5.60k
         Constraints.size() == Exprs.size() && "Input operand size mismatch!");
797
5.60k
798
5.60k
  unsigned NumInputs = Names.size() - NumOutputs;
799
5.60k
800
  // Parse the clobbers, if present.
801
5.60k
  if (AteExtraColon || 
Tok.is(tok::colon)5.59k
||
Tok.is(tok::coloncolon)2.76k
) {
802
2.87k
    if (AteExtraColon)
803
15
      AteExtraColon = false;
804
2.85k
    else {
805
2.85k
      AteExtraColon = Tok.is(tok::coloncolon);
806
2.85k
      ConsumeToken();
807
2.85k
    }
808
    // Parse the asm-string list for clobbers if present.
809
2.87k
    if (!AteExtraColon && 
isTokenStringLiteral()2.84k
) {
810
3.36k
      while (1) {
811
3.36k
        ExprResult Clobber(ParseAsmStringLiteral(/*ForAsmLabel*/ false));
812
3.36k
813
3.36k
        if (Clobber.isInvalid())
814
0
          break;
815
3.36k
816
3.36k
        Clobbers.push_back(Clobber.get());
817
3.36k
818
3.36k
        if (!TryConsumeToken(tok::comma))
819
2.46k
          break;
820
3.36k
      }
821
2.46k
    }
822
2.87k
  }
823
5.60k
  if (!GAQ.isGoto() && 
(5.47k
Tok.isNot(tok::r_paren)5.47k
||
AteExtraColon5.46k
)) {
824
8
    Diag(Tok, diag::err_expected) << tok::r_paren;
825
8
    SkipUntil(tok::r_paren, StopAtSemi);
826
8
    return StmtError();
827
8
  }
828
5.60k
829
  // Parse the goto label, if present.
830
5.60k
  unsigned NumLabels = 0;
831
5.60k
  if (AteExtraColon || 
Tok.is(tok::colon)5.57k
) {
832
129
    if (!AteExtraColon)
833
106
      ConsumeToken();
834
129
835
183
    while (true) {
836
183
      if (Tok.isNot(tok::identifier)) {
837
8
        Diag(Tok, diag::err_expected) << tok::identifier;
838
8
        SkipUntil(tok::r_paren, StopAtSemi);
839
8
        return StmtError();
840
8
      }
841
175
      LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
842
175
                                                  Tok.getLocation());
843
175
      Names.push_back(Tok.getIdentifierInfo());
844
175
      if (!LD) {
845
0
        SkipUntil(tok::r_paren, StopAtSemi);
846
0
        return StmtError();
847
0
      }
848
175
      ExprResult Res =
849
175
          Actions.ActOnAddrLabel(Tok.getLocation(), Tok.getLocation(), LD);
850
175
      Exprs.push_back(Res.get());
851
175
      NumLabels++;
852
175
      ConsumeToken();
853
175
      if (!TryConsumeToken(tok::comma))
854
121
        break;
855
175
    }
856
5.47k
  } else if (GAQ.isGoto()) {
857
8
    Diag(Tok, diag::err_expected) << tok::colon;
858
8
    SkipUntil(tok::r_paren, StopAtSemi);
859
8
    return StmtError();
860
8
  }
861
5.58k
  T.consumeClose();
862
5.58k
  return Actions.ActOnGCCAsmStmt(AsmLoc, false, GAQ.isVolatile(), NumOutputs,
863
5.58k
                                 NumInputs, Names.data(), Constraints, Exprs,
864
5.58k
                                 AsmString.get(), Clobbers, NumLabels,
865
5.58k
                                 T.getCloseLocation());
866
5.58k
}
867
868
/// ParseAsmOperands - Parse the asm-operands production as used by
869
/// asm-statement, assuming the leading ':' token was eaten.
870
///
871
/// [GNU] asm-operands:
872
///         asm-operand
873
///         asm-operands ',' asm-operand
874
///
875
/// [GNU] asm-operand:
876
///         asm-string-literal '(' expression ')'
877
///         '[' identifier ']' asm-string-literal '(' expression ')'
878
///
879
//
880
// FIXME: Avoid unnecessary std::string trashing.
881
bool Parser::ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
882
                                 SmallVectorImpl<Expr *> &Constraints,
883
10.8k
                                 SmallVectorImpl<Expr *> &Exprs) {
884
  // 'asm-operands' isn't present?
885
10.8k
  if (!isTokenStringLiteral() && 
Tok.isNot(tok::l_square)2.86k
)
886
2.36k
    return false;
887
8.49k
888
18.6k
  
while (8.49k
1) {
889
    // Read the [id] if present.
890
18.6k
    if (Tok.is(tok::l_square)) {
891
852
      BalancedDelimiterTracker T(*this, tok::l_square);
892
852
      T.consumeOpen();
893
852
894
852
      if (Tok.isNot(tok::identifier)) {
895
0
        Diag(Tok, diag::err_expected) << tok::identifier;
896
0
        SkipUntil(tok::r_paren, StopAtSemi);
897
0
        return true;
898
0
      }
899
852
900
852
      IdentifierInfo *II = Tok.getIdentifierInfo();
901
852
      ConsumeToken();
902
852
903
852
      Names.push_back(II);
904
852
      T.consumeClose();
905
852
    } else
906
17.8k
      Names.push_back(nullptr);
907
18.6k
908
18.6k
    ExprResult Constraint(ParseAsmStringLiteral(/*ForAsmLabel*/ false));
909
18.6k
    if (Constraint.isInvalid()) {
910
1
      SkipUntil(tok::r_paren, StopAtSemi);
911
1
      return true;
912
1
    }
913
18.6k
    Constraints.push_back(Constraint.get());
914
18.6k
915
18.6k
    if (Tok.isNot(tok::l_paren)) {
916
0
      Diag(Tok, diag::err_expected_lparen_after) << "asm operand";
917
0
      SkipUntil(tok::r_paren, StopAtSemi);
918
0
      return true;
919
0
    }
920
18.6k
921
    // Read the parenthesized expression.
922
18.6k
    BalancedDelimiterTracker T(*this, tok::l_paren);
923
18.6k
    T.consumeOpen();
924
18.6k
    ExprResult Res = Actions.CorrectDelayedTyposInExpr(ParseExpression());
925
18.6k
    T.consumeClose();
926
18.6k
    if (Res.isInvalid()) {
927
4
      SkipUntil(tok::r_paren, StopAtSemi);
928
4
      return true;
929
4
    }
930
18.6k
    Exprs.push_back(Res.get());
931
    // Eat the comma and continue parsing if it exists.
932
18.6k
    if (!TryConsumeToken(tok::comma))
933
8.49k
      return false;
934
18.6k
  }
935
8.49k
}
936
937
9
const char *Parser::GNUAsmQualifiers::getQualifierName(AQ Qualifier) {
938
9
  switch (Qualifier) {
939
3
    case AQ_volatile: return "volatile";
940
3
    case AQ_inline: return "inline";
941
3
    case AQ_goto: return "goto";
942
0
    case AQ_unspecified: return "unspecified";
943
0
  }
944
0
  llvm_unreachable("Unknown GNUAsmQualifier");
945
0
}
946
947
Parser::GNUAsmQualifiers::AQ
948
67.5k
Parser::getGNUAsmQualifier(const Token &Tok) const {
949
67.5k
  switch (Tok.getKind()) {
950
1.95k
    case tok::kw_volatile: return GNUAsmQualifiers::AQ_volatile;
951
17
    case tok::kw_inline: return GNUAsmQualifiers::AQ_inline;
952
150
    case tok::kw_goto: return GNUAsmQualifiers::AQ_goto;
953
65.4k
    default: return GNUAsmQualifiers::AQ_unspecified;
954
67.5k
  }
955
67.5k
}
956
1.89k
bool Parser::GNUAsmQualifiers::setAsmQualifier(AQ Qualifier) {
957
1.89k
  bool IsDuplicate = Qualifiers & Qualifier;
958
1.89k
  Qualifiers |= Qualifier;
959
1.89k
  return IsDuplicate;
960
1.89k
}